# Firebase Admin Panel Setup Guide

## Overview
यह guide आपको social media app के लिए Firebase-based admin panel setup करने में help करेगा।

## Prerequisites
- Firebase project
- PHP 7.4+ with Composer
- Firebase Admin SDK
- OneSignal account (notifications के लिए)

## Step 1: Firebase Project Setup

### 1.1 Firebase Console में Project बनाएं
1. [Firebase Console](https://console.firebase.google.com/) पर जाएं
2. "Add project" click करें
3. Project name enter करें (e.g., "your-social-media-app")
4. Google Analytics enable/disable करें
5. Project create करें

### 1.2 Firestore Database Setup
1. Firebase Console में अपने project को select करें
2. Left sidebar में "Firestore Database" click करें
3. "Create database" click करें
4. "Start in test mode" select करें (बाद में security rules update करेंगे)
5. Location select करें और "Done" click करें

### 1.3 Authentication Setup
1. Left sidebar में "Authentication" click करें
2. "Get started" click करें
3. "Sign-in method" tab पर जाएं
4. "Email/Password" enable करें
5. Admin user के लिए email/password add करें

### 1.4 Storage Setup (Optional)
1. Left sidebar में "Storage" click करें
2. "Get started" click करें
3. Security rules accept करें
4. Location select करें

## Step 2: Service Account Key Download

### 2.1 Service Account Key Generate करें
1. Firebase Console में project settings (gear icon) click करें
2. "Service accounts" tab पर जाएं
3. "Generate new private key" button click करें
4. JSON file download करें
5. इस file को `backend/serviceAccountKey.json` के नाम से save करें

## Step 3: PHP Dependencies Install करें

### 3.1 Composer Install करें
```bash
composer require kreait/firebase-php
```

### 3.2 Required PHP Extensions
```bash
# Ubuntu/Debian
sudo apt-get install php-curl php-json php-mbstring

# CentOS/RHEL
sudo yum install php-curl php-json php-mbstring
```

## Step 4: Configuration Update करें

### 4.1 Firebase Config Update करें
`backend/firebase_config.php` file में अपने Firebase project details update करें:

```php
const FIREBASE_CONFIG = [
    'apiKey' => 'YOUR_API_KEY_HERE',
    'authDomain' => 'your-social-media-app.firebaseapp.com',
    'projectId' => 'your-social-media-app',
    'storageBucket' => 'your-social-media-app.firebasestorage.app',
    'messagingSenderId' => 'YOUR_SENDER_ID',
    'appId' => 'YOUR_APP_ID',
    'measurementId' => 'YOUR_MEASUREMENT_ID'
];
```

### 4.2 Admin Credentials Update करें
```php
const ADMIN_EMAIL = 'admin@yourdomain.com';
const ADMIN_PASSWORD = 'your_admin_password';
```

### 4.3 OneSignal Configuration (Notifications के लिए)
`backend/firebase_notifications.php` में OneSignal credentials update करें:

```php
define('ONESIGNAL_APP_ID', 'YOUR_ONESIGNAL_APP_ID');
define('ONESIGNAL_API_KEY', 'YOUR_ONESIGNAL_API_KEY');
```

## Step 5: Firestore Collections Structure

### 5.1 Required Collections
आपके Firestore database में ये collections automatically create होंगे:

```
users/
├── {userId}/
│   ├── email: string
│   ├── username: string
│   ├── full_name: string
│   ├── profile_picture: string
│   ├── bio: string
│   ├── is_verified: boolean
│   ├── is_blocked: boolean
│   ├── followers_count: number
│   ├── following_count: number
│   ├── posts_count: number
│   ├── device_id: string
│   ├── fcm_token: string
│   ├── last_active: timestamp
│   ├── created_at: timestamp
│   └── updated_at: timestamp

posts/
├── {postId}/
│   ├── user_id: string
│   ├── content: string
│   ├── media_urls: array
│   ├── media_type: string
│   ├── location: string
│   ├── hashtags: array
│   ├── mentions: array
│   ├── likes_count: number
│   ├── comments_count: number
│   ├── shares_count: number
│   ├── views_count: number
│   ├── is_reported: boolean
│   ├── is_deleted: boolean
│   ├── report_reason: string
│   ├── created_at: timestamp
│   └── updated_at: timestamp

notifications/
├── {notificationId}/
│   ├── title: string
│   ├── message: string
│   ├── image_url: string
│   ├── action_url: string
│   ├── platform: string
│   ├── schedule_time: timestamp
│   ├── status: string
│   ├── button1_text: string
│   ├── button1_url: string
│   ├── button2_text: string
│   ├── button2_url: string
│   ├── sent_time: timestamp
│   ├── user_count: number
│   ├── onesignal_id: string
│   ├── created_at: timestamp
│   └── updated_at: timestamp

app_settings/
└── main/
    ├── app_name: string
    ├── app_version: string
    ├── maintenance_mode: boolean
    ├── registration_enabled: boolean
    ├── post_creation_enabled: boolean
    ├── max_post_length: number
    ├── max_media_per_post: number
    ├── max_file_size_mb: number
    ├── allowed_media_types: array
    ├── enable_notifications: boolean
    ├── enable_push_notifications: boolean
    ├── enable_email_notifications: boolean
    ├── admin_email: string
    ├── support_email: string
    ├── privacy_policy_url: string
    ├── terms_of_service_url: string
    ├── about_us_url: string
    ├── contact_us_url: string
    ├── facebook_url: string
    ├── twitter_url: string
    ├── instagram_url: string
    ├── youtube_url: string
    ├── linkedin_url: string
    ├── app_store_url: string
    ├── play_store_url: string
    ├── created_at: timestamp
    └── updated_at: timestamp
```

## Step 6: Security Rules Setup

### 6.1 Firestore Security Rules
Firebase Console > Firestore Database > Rules में ये rules add करें:

```javascript
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Admin users can read/write everything
    match /{document=**} {
      allow read, write: if request.auth != null && 
        request.auth.token.admin == true;
    }
    
    // Regular users can only read/write their own data
    match /users/{userId} {
      allow read, write: if request.auth != null && 
        request.auth.uid == userId;
    }
    
    match /posts/{postId} {
      allow read: if true; // Public read
      allow write: if request.auth != null && 
        request.auth.uid == resource.data.user_id;
    }
  }
}
```

### 6.2 Storage Security Rules
Firebase Console > Storage > Rules में ये rules add करें:

```javascript
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read: if true; // Public read
      allow write: if request.auth != null && 
        request.auth.token.admin == true;
    }
  }
}
```

## Step 7: API Endpoints

### 7.1 Available Endpoints
```
Authentication:
POST /backend/firebase_auth.php?action=login
POST /backend/firebase_auth.php?action=logout
POST /backend/firebase_auth.php?action=create_admin

Users Management:
GET /backend/firebase_users.php
GET /backend/firebase_users.php?id={userId}
POST /backend/firebase_users.php
PUT /backend/firebase_users.php?id={userId}
DELETE /backend/firebase_users.php?id={userId}
POST /backend/firebase_users.php?action=block&id={userId}
POST /backend/firebase_users.php?action=unblock&id={userId}
POST /backend/firebase_users.php?action=verify&id={userId}
POST /backend/firebase_users.php?action=unverify&id={userId}

Posts Management:
GET /backend/firebase_posts.php
GET /backend/firebase_posts.php?id={postId}
POST /backend/firebase_posts.php
PUT /backend/firebase_posts.php?id={postId}
DELETE /backend/firebase_posts.php?id={postId}
POST /backend/firebase_posts.php?action=report&id={postId}
POST /backend/firebase_posts.php?action=unreport&id={postId}
POST /backend/firebase_posts.php?action=hide&id={postId}
POST /backend/firebase_posts.php?action=unhide&id={postId}

Dashboard:
GET /backend/firebase_dashboard.php

Analytics:
GET /backend/firebase_analytics.php?action=overview
GET /backend/firebase_analytics.php?action=users
GET /backend/firebase_analytics.php?action=posts
GET /backend/firebase_analytics.php?action=engagement
GET /backend/firebase_analytics.php?action=reports
GET /backend/firebase_analytics.php?action=export

Notifications:
GET /backend/firebase_notifications.php
GET /backend/firebase_notifications.php?id={notificationId}
POST /backend/firebase_notifications.php
PUT /backend/firebase_notifications.php?id={notificationId}
DELETE /backend/firebase_notifications.php?id={notificationId}
GET /backend/firebase_notifications.php?cron=1

Settings:
GET /backend/firebase_settings.php
PUT /backend/firebase_settings.php
POST /backend/firebase_settings.php?action=reset_to_defaults
POST /backend/firebase_settings.php?action=export_settings
POST /backend/firebase_settings.php?action=import_settings
```

## Step 8: Testing

### 8.1 Admin User Create करें
```bash
curl -X POST http://yourdomain.com/backend/firebase_auth.php?action=create_admin \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@yourdomain.com","password":"your_password"}'
```

### 8.2 Login Test करें
```bash
curl -X POST http://yourdomain.com/backend/firebase_auth.php?action=login \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@yourdomain.com","password":"your_password"}'
```

### 8.3 Dashboard Test करें
```bash
curl -X GET http://yourdomain.com/backend/firebase_dashboard.php \
  -H "Authorization: Bearer YOUR_CUSTOM_TOKEN"
```

## Step 9: Cron Job Setup (Optional)

### 9.1 Scheduled Notifications के लिए
```bash
# Add to crontab
0 * * * * curl -X GET http://yourdomain.com/backend/firebase_notifications.php?cron=1
```

## Step 10: Troubleshooting

### 10.1 Common Issues

**Firebase Connection Error:**
- Service account key file path check करें
- Firebase project ID correct है या नहीं
- Internet connection check करें

**Authentication Error:**
- Admin user properly create हुआ है या नहीं
- Custom claims properly set हुए हैं या नहीं
- Token format correct है या नहीं

**Permission Denied:**
- Firestore security rules check करें
- Admin token properly verify हो रहा है या नहीं

### 10.2 Debug Mode Enable करें
`backend/firebase_config.php` में error logging enable करें:

```php
// Add at the top
error_reporting(E_ALL);
ini_set('display_errors', 1);
```

## Step 11: Production Deployment

### 11.1 Security Checklist
- [ ] Service account key file secure location में है
- [ ] Firestore security rules properly configured हैं
- [ ] Storage security rules properly configured हैं
- [ ] Admin credentials strong हैं
- [ ] HTTPS enabled है
- [ ] Error logging disabled है production में

### 11.2 Performance Optimization
- [ ] Firebase connection pooling enable करें
- [ ] Query limits properly set करें
- [ ] Indexes create करें frequently queried fields के लिए
- [ ] Caching implement करें where possible

## Support

अगर कोई issue आए तो:
1. Firebase Console में logs check करें
2. PHP error logs check करें
3. Network requests debug करें
4. Firebase documentation refer करें

## Additional Resources

- [Firebase Documentation](https://firebase.google.com/docs)
- [Firebase PHP SDK](https://firebase-php.readthedocs.io/)
- [OneSignal Documentation](https://documentation.onesignal.com/)
- [Firestore Security Rules](https://firebase.google.com/docs/firestore/security/get-started)
