# Postery Social Media Admin Panel - Firebase Edition

A comprehensive admin panel for managing a social media application built with Firebase Firestore and PHP.

## 🚀 Features

### Core Functionality
- **User Management**: View, block, unblock, verify, and delete users
- **Content Management**: Manage posts, comments, stories, and chats
- **Moderation Tools**: Handle reports, content moderation, and user feedback
- **Analytics Dashboard**: Real-time insights and engagement metrics
- **Monetization Management**: Earnings tracking, withdrawals, and ad management
- **Notification System**: Send push notifications and broadcast messages
- **Settings Management**: Configure app settings and monetization parameters

### Firebase Collections
- **users**: User profiles and account information
- **posts**: User posts and content
- **comments**: Comments on posts
- **stories**: 24-hour user stories
- **chats**: Chat conversations
- **messages**: Individual messages (subcollection)
- **Reports**: User reports and moderation
- **notifications**: Push notifications
- **CustomAds**: Custom advertisement management
- **withdrawals**: User withdrawal requests
- **monetization_config**: App monetization settings
- **earnings**: User earnings tracking
- **monetizationRequests**: Monetization program requests
- **app_settings**: Global app configuration
- **userFeedbacks**: User feedback and suggestions
- **reportProblems**: Technical problem reports
- **deleteAccountRequests**: Account deletion requests

## 📋 Prerequisites

- PHP 7.4 or higher
- Composer
- Firebase project with Firestore enabled
- Firebase Admin SDK credentials

## 🛠️ Installation

### 1. Clone the Repository
```bash
git clone <repository-url>
cd postery-admin-firebase
```

### 2. Install Dependencies
```bash
composer require google/cloud-firestore
composer require kreait/firebase-php
```

### 3. Firebase Setup

#### 3.1 Create Firebase Project
1. Go to [Firebase Console](https://console.firebase.google.com/)
2. Create a new project named "postry-social-media"
3. Enable Firestore Database
4. Enable Authentication
5. Enable Cloud Storage

#### 3.2 Download Service Account Key
1. Go to Project Settings > Service Accounts
2. Click "Generate new private key"
3. Download the JSON file
4. Rename it to `serviceAccountKey.json`
5. Place it in the `backend/` directory

#### 3.3 Configure Firestore Security Rules
```javascript
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Users can read/write their own data
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
    
    // Posts are readable by all authenticated users
    match /posts/{postId} {
      allow read: if request.auth != null;
      allow write: if request.auth != null && 
        (resource == null || resource.data.postUser == request.auth.uid);
    }
    
    // Admin-only collections
    match /reports/{reportId} {
      allow read, write: if request.auth != null && 
        get(/databases/$(database)/documents/users/$(request.auth.uid)).data.isAdmin == true;
    }
  }
}
```

### 4. Configuration

#### 4.1 Update Firebase Configuration
Edit `backend/firebase_config.php` and update the Firebase configuration:

```php
const FIREBASE_CONFIG = [
    'apiKey' => 'YOUR_API_KEY',
    'authDomain' => 'your-project.firebaseapp.com',
    'projectId' => 'your-project-id',
    'storageBucket' => 'your-project.appspot.com',
    'messagingSenderId' => 'YOUR_SENDER_ID',
    'appId' => 'YOUR_APP_ID',
    'measurementId' => 'YOUR_MEASUREMENT_ID'
];
```

#### 4.2 Set Up Admin Authentication
Update the login credentials in `pages/login_firebase.php`:

```php
// Replace with your admin credentials
if ($username === 'your_admin_username' && $password === 'your_secure_password') {
    // Login logic
}
```

## 🎯 Usage

### 1. Access the Admin Panel
1. Navigate to `pages/login_firebase.php`
2. Use the default credentials:
   - Username: `admin`
   - Password: `admin123`
3. Change these credentials in production!

### 2. Dashboard Overview
The main dashboard provides:
- User statistics (total, active, verified, blocked)
- Content metrics (posts, stories, comments)
- Recent activity feed
- Quick action buttons
- Analytics charts

### 3. User Management
- **View Users**: Browse all registered users
- **Search & Filter**: Find users by name, email, or status
- **User Actions**: Block, unblock, verify, or delete users
- **User Details**: View detailed user information and activity

### 4. Content Management
- **Posts**: Manage user posts, moderate content
- **Comments**: Review and moderate comments
- **Stories**: Monitor 24-hour stories
- **Chats**: View chat conversations and messages

### 5. Moderation Tools
- **Reports**: Handle user reports and complaints
- **Content Moderation**: Review flagged content
- **User Feedback**: Manage user suggestions and feedback
- **Problem Reports**: Handle technical issues

### 6. Analytics & Insights
- **User Analytics**: User growth and engagement metrics
- **Content Analytics**: Post performance and engagement
- **Engagement Metrics**: Likes, comments, shares analysis
- **Revenue Analytics**: Monetization and earnings data

### 7. Monetization Management
- **Earnings**: Track user earnings and balances
- **Withdrawals**: Process withdrawal requests
- **Monetization Requests**: Approve users for monetization
- **Custom Ads**: Manage custom advertisements
- **Configuration**: Set monetization parameters

### 8. Settings & Configuration
- **App Settings**: Configure global app settings
- **Monetization Config**: Set earning rates and thresholds
- **Firebase Management**: Monitor Firebase usage and performance

## 🔧 Customization

### Adding New Collections
1. Update `FIREBASE_SCHEMA.md` with your new collection structure
2. Add helper methods in `FirebaseHelper` class
3. Create new admin pages following the existing pattern

### Styling Customization
The admin panel uses CSS custom properties for easy theming:

```css
:root {
    --primary: #6366f1;
    --secondary: #8b5cf6;
    --success: #10b981;
    --danger: #ef4444;
    --warning: #f59e0b;
    /* ... other variables */
}
```

### Adding New Features
1. Create new PHP files in the `pages/` directory
2. Follow the existing naming convention: `feature_firebase.php`
3. Update the sidebar navigation in `sidebar_firebase.php`
4. Implement proper error handling and user feedback

## 📊 Firebase Schema

The complete Firebase schema is documented in `FIREBASE_SCHEMA.md`. Key collections include:

### Users Collection
```javascript
{
  email: "string",
  display_name: "string",
  photo_url: "string",
  uid: "string",
  created_time: "timestamp",
  followers: ["array of user references"],
  following: ["array of user references"],
  isVerified: "boolean",
  isBlocked: "boolean",
  balance: "number"
  // ... more fields
}
```

### Posts Collection
```javascript
{
  postImage: "string",
  postUser: "document reference",
  postText: "string",
  createdOn: "timestamp",
  likedBy: ["array of user references"],
  hashtags: ["array of strings"],
  isActive: "boolean"
  // ... more fields
}
```

## 🔒 Security Considerations

### 1. Authentication
- Implement proper admin authentication
- Use strong passwords and consider 2FA
- Regularly rotate admin credentials

### 2. Firestore Security Rules
- Implement proper security rules
- Restrict admin operations to authenticated admins
- Validate data on both client and server side

### 3. Data Validation
- Validate all user inputs
- Sanitize data before storing in Firestore
- Implement rate limiting for admin operations

### 4. Access Control
- Limit admin access to necessary personnel only
- Implement role-based access control
- Log all admin actions for audit purposes

## 🚀 Deployment

### 1. Production Setup
1. Set up a production Firebase project
2. Configure production security rules
3. Set up proper admin authentication
4. Configure monitoring and logging

### 2. Environment Configuration
```php
// Production configuration
const FIREBASE_CONFIG = [
    'apiKey' => 'PRODUCTION_API_KEY',
    'authDomain' => 'your-production-project.firebaseapp.com',
    'projectId' => 'your-production-project-id',
    // ... other production settings
];
```

### 3. Performance Optimization
- Implement pagination for large datasets
- Use Firestore indexes for better query performance
- Cache frequently accessed data
- Optimize image loading and storage

## 📈 Monitoring & Analytics

### 1. Firebase Analytics
- Track admin panel usage
- Monitor user engagement metrics
- Set up custom events and conversions

### 2. Error Monitoring
- Implement error logging
- Set up alerts for critical errors
- Monitor Firebase quota usage

### 3. Performance Monitoring
- Track page load times
- Monitor database query performance
- Set up performance budgets

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Test thoroughly
5. Submit a pull request

## 📝 License

This project is licensed under the MIT License - see the LICENSE file for details.

## 🆘 Support

For support and questions:
- Create an issue in the repository
- Check the documentation in `FIREBASE_SCHEMA.md`
- Review the Firebase documentation

## 🔄 Updates & Maintenance

### Regular Maintenance Tasks
- Update Firebase SDK versions
- Review and update security rules
- Monitor and optimize database queries
- Update admin panel features based on user feedback

### Version History
- v1.0.0: Initial Firebase-based admin panel
- Future versions will include additional features and improvements

---

**Note**: This admin panel is designed for managing a social media application. Make sure to customize it according to your specific requirements and implement proper security measures before deploying to production.
