# ChatBud PHP - Quick Start & Setup Guide

## ✅ Setup Status

**Current State:**
- ✅ Project files created
- ✅ Directory structure initialized  
- ✅ `.env` configuration file created
- ⚠️ Database: Not configured (requires MySQL/PostgreSQL)
- ⚠️ Email: Not configured (requires SMTP service)

## 📋 Next Steps to Complete Setup

### Step 1: Database Setup

#### Option A: Using MySQL (Recommended for Development)

1. **Install MySQL** (if not already installed):
   - Download: https://dev.mysql.com/downloads/mysql/
   - Install community edition

2. **Create Database and User**:
   ```sql
   mysql -u root -p
   
   CREATE DATABASE chatbud DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
   CREATE USER 'chatbud_user'@'localhost' IDENTIFIED BY 'StrongPassword123!';
   GRANT ALL PRIVILEGES ON chatbud.* TO 'chatbud_user'@'localhost';
   FLUSH PRIVILEGES;
   EXIT;
   ```

3. **Import Database Schema**:
   ```bash
   mysql -u chatbud_user -p chatbud < database.sql
   ```

4. **Update `.env` file**:
   ```env
   DB_HOST=127.0.0.1
   DB_PORT=3306
   DB_DATABASE=chatbud
   DB_USERNAME=chatbud_user
   DB_PASSWORD=StrongPassword123!
   ```

5. **Verify Connection**:
   ```bash
   php test_db.php
   ```

#### Option B: Using PostgreSQL

1. **Install PostgreSQL**: https://www.postgresql.org/download/

2. **Create Database and User**:
   ```sql
   createdb chatbud
   createuser chatbud_user --password
   psql -d chatbud -c "GRANT ALL PRIVILEGES ON DATABASE chatbud TO chatbud_user;"
   ```

3. **Import Schema** (convert to PostgreSQL first):
   ```bash
   psql -U chatbud_user -d chatbud -f database.sql
   ```

4. **Update `.env` file**:
   ```env
   DB_CONNECTION=pgsql
   DB_HOST=localhost
   DB_PORT=5432
   DB_DATABASE=chatbud
   DB_USERNAME=chatbud_user
   DB_PASSWORD=your_password
   ```

### Step 2: Email Service Setup

#### Option A: Using Mailtrap (Development)

1. **Sign Up**: https://mailtrap.io (free account)

2. **Create Inbox**:
   - Click "Create Inbox"
   - Name it "Development"

3. **Get SMTP Credentials**:
   - Go to Inbox Settings
   - Click "Integrations" tab
   - Select "SMTP"
   - Copy credentials

4. **Update `.env` file**:
   ```env
   MAIL_DRIVER=smtp
   MAIL_HOST=smtp.mailtrap.io
   MAIL_PORT=465
   MAIL_USERNAME=your_mailtrap_username
   MAIL_PASSWORD=your_mailtrap_password
   MAIL_FROM_ADDRESS=noreply@chatbud.com
   ```

5. **Verify Configuration**:
   ```bash
   php test_email.php
   ```

#### Option B: Using SendGrid (Production)

1. **Sign Up**: https://sendgrid.com (free tier available)

2. **Create API Key**:
   - Go to Settings → API Keys
   - Click "Create API Key"
   - Name it "ChatBud"
   - Grant full access
   - Copy the key

3. **Update `.env` file**:
   ```env
   MAIL_DRIVER=sendgrid
   SENDGRID_API_KEY=SG.your_api_key_here
   MAIL_FROM_ADDRESS=noreply@chatbud.com
   ```

#### Option C: Using Gmail SMTP

1. **Enable 2-Factor Authentication**:
   - Go to https://myaccount.google.com/
   - Security → 2-Step Verification

2. **Create App Password**:
   - Go to Security → App passwords
   - Generate password for "Mail"
   - Copy the 16-character password

3. **Update `.env` file**:
   ```env
   MAIL_DRIVER=smtp
   MAIL_HOST=smtp.gmail.com
   MAIL_PORT=587
   MAIL_USERNAME=your-email@gmail.com
   MAIL_PASSWORD=your-16-char-app-password
   MAIL_FROM_ADDRESS=your-email@gmail.com
   ```

### Step 3: Verify Installation

```bash
# Test database connection
php test_db.php

# Test email service
php test_email.php
```

Expected Output (if configured):
```
✓ Database connection successful
✓ Connected to database: chatbud
✓ Users table
✓ Posts table
[... etc]

✓ Email sent successfully!
```

## 🚀 Using the API

Once setup is complete, you can start using the API!

### Starting a Web Server

**Option A: PHP Built-in Server**
```bash
cd ChatBud-PHP/public
php -S localhost:8000
```

**Option B: Apache/Nginx**
- Configure vhost to point to `ChatBud-PHP/public/`
- Enable mod_rewrite for Apache
- Create similar config for Nginx

### API Base URL

```
http://localhost:8000/api.php/v1/
```

### Example 1: Register a User

```bash
curl -X POST http://localhost:8000/api.php/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "username": "testuser",
    "password": "SecurePassword123",
    "display_name": "Test User"
  }'
```

Response:
```json
{
  "success": true,
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "email": "user@example.com",
    "username": "testuser",
    "display_name": "Test User",
    "created_at": "2026-08-18 10:30:00"
  }
}
```

### Example 2: Login

```bash
curl -X POST http://localhost:8000/api.php/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "SecurePassword123"
  }' \
  -c cookies.txt
```

Response:
```json
{
  "success": true,
  "data": {
    "user": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "email": "user@example.com",
      "username": "testuser"
    },
    "token": "session_token_here"
  }
}
```

### Example 3: Create a Post

```bash
curl -X POST http://localhost:8000/api.php/v1/posts \
  -H "Content-Type: application/json" \
  -b cookies.txt \
  -d '{
    "content": "Hello, ChatBud! This is my first post! 🎉"
  }'
```

### Example 4: Get Feed

```bash
curl -X GET "http://localhost:8000/api.php/v1/feed?limit=20" \
  -H "Content-Type: application/json" \
  -b cookies.txt
```

### Example 5: Upload Media

```bash
curl -X POST http://localhost:8000/api.php/v1/upload \
  -b cookies.txt \
  -F "file=@/path/to/image.jpg"
```

Response:
```json
{
  "success": true,
  "data": [
    {
      "filename": "1629314400_a1b2c3d4e5.jpg",
      "url": "/uploads/posts/1629314400_a1b2c3d4e5.jpg",
      "mime_type": "image/jpeg",
      "file_size": 245632,
      "type": "image",
      "width": 1920,
      "height": 1080,
      "thumbnail_url": "/uploads/posts/thumb_1629314400_a1b2c3d4e5.jpg"
    }
  ]
}
```

## 📚 Full API Reference

See **API_DOCUMENTATION.md** for complete endpoint documentation with:
- All 25+ endpoints
- Request/response formats
- Status codes
- Error handling
- Pagination
- More examples

## 📁 Project Structure

```
ChatBud-PHP/
├── public/
│   ├── index.php           - Web interface entry point
│   ├── api.php             - REST API entry point
│   ├── .htaccess           - URL rewriting rules
│   └── uploads/            - User uploaded files
│
├── src/
│   ├── lib/                - Core PHP classes
│   │   ├── Database.php    - Database abstraction
│   │   ├── Auth.php        - Authentication
│   │   ├── User.php        - User model
│   │   ├── Post.php        - Post model
│   │   ├── API.php         - API endpoints
│   │   ├── FileUpload.php  - File handling
│   │   ├── EmailService.php- Email sending
│   │   ├── Notification.php- Notifications
│   │   └── ... more
│   ├── templates/
│   │   ├── routes/         - Page templates
│   │   └── emails/         - Email templates
│   └── components/         - Reusable components
│
├── .env                    - Configuration (CREATED)
├── .env.example            - Configuration template
├── database.sql            - Database schema
├── README_COMPLETE.md      - Full documentation
├── API_DOCUMENTATION.md    - API reference
├── DATABASE_SETUP.md       - Database setup guide
├── EMAIL_SETUP.md          - Email configuration guide
└── ... more docs
```

## 🔧 Configuration Checklist

- [ ] Database installed and running
- [ ] Database created with chatbud_user
- [ ] `database.sql` imported into database
- [ ] `.env` file updated with DB credentials
- [ ] Email service account created
- [ ] `.env` file updated with email credentials
- [ ] `php test_db.php` passes
- [ ] `php test_email.php` passes
- [ ] Web server running on localhost:8000
- [ ] Can access http://localhost:8000

## 🆘 Troubleshooting

### Database Connection Failed

**Error:** "could not find driver"
- **Cause:** MySQL PDO driver not installed
- **Solution:** Install PHP MySQL extension
  - Windows: Uncomment `extension=pdo_mysql` in php.ini
  - macOS: `brew install php@8.2`
  - Linux: `sudo apt-get install php-mysql`

**Error:** "Access denied for user"
- **Cause:** Wrong credentials
- **Solution:** Verify username/password in .env matches database

**Error:** "Unknown database"
- **Cause:** Database not created
- **Solution:** Run: `mysql -u root -p < database.sql`

### Email Not Sending

**Error:** "Failed to connect to mailserver"
- **Cause:** SMTP credentials not configured
- **Solution:** Set up Mailtrap account and add credentials to .env

**Error:** "Authorization failed"
- **Cause:** Wrong email service credentials
- **Solution:** Verify API key or password in .env

### API Returns 404

**Cause:** Web server not configured properly
**Solution:** 
1. Check `.htaccess` is in public/ directory
2. Verify Apache mod_rewrite is enabled
3. Use PHP built-in server: `php -S localhost:8000 -t public/`

## 📖 Documentation

- **README_COMPLETE.md** - Complete project documentation
- **API_DOCUMENTATION.md** - All API endpoints with examples
- **DATABASE_SETUP.md** - Database configuration and maintenance
- **EMAIL_SETUP.md** - Email service setup for all providers
- **INTEGRATION_GUIDE.md** - System architecture and design patterns

## 🎯 Quick Testing Flow

1. **Register a new user**:
   ```bash
   POST /api/v1/auth/register
   ```

2. **Login**:
   ```bash
   POST /api/v1/auth/login
   ```

3. **Create a post**:
   ```bash
   POST /api/v1/posts
   ```

4. **Get feed**:
   ```bash
   GET /api/v1/feed
   ```

5. **Upload media**:
   ```bash
   POST /api/v1/upload
   ```

6. **Follow a user**:
   ```bash
   POST /api/v1/users/:id/follow
   ```

## 🎓 Learning Resources

- **API Examples:** See API_DOCUMENTATION.md for curl examples
- **Postman:** Import API collection from examples
- **Source Code:** Read the PHP files in src/lib/ to understand architecture
- **Database:** Check database.sql for schema documentation

## 📞 Support

- **Documentation:** README_COMPLETE.md
- **API Reference:** API_DOCUMENTATION.md
- **Setup Help:** DATABASE_SETUP.md, EMAIL_SETUP.md
- **Email:** support@chatbud.com

---

**Ready to get started?**

Follow these steps in order:
1. Set up database (MySQL/PostgreSQL)
2. Configure email service (Mailtrap/SendGrid)
3. Update `.env` file
4. Run test scripts to verify
5. Start web server and test API

**Enjoy building with ChatBud! 🚀**
