<?php
require_once 'config/db.php';

try {
    // 1. Create 'services' table (Products/Services listed by users)
    $sql_services = "CREATE TABLE IF NOT EXISTS services (
        id INT AUTO_INCREMENT PRIMARY KEY,
        seller_id INT NOT NULL,
        title VARCHAR(100) NOT NULL,
        description TEXT,
        price INT NOT NULL, -- Price in Diamonds
        image_url VARCHAR(255) DEFAULT NULL,
        category VARCHAR(50) DEFAULT 'general',
        is_active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (seller_id) REFERENCES users(id) ON DELETE CASCADE
    )";
    $pdo->exec($sql_services);
    echo "✅ Table 'services' created successfully.<br>";

    // 2. Create 'orders' table (Purchases made)
    $sql_orders = "CREATE TABLE IF NOT EXISTS orders (
        id INT AUTO_INCREMENT PRIMARY KEY,
        service_id INT NOT NULL,
        buyer_id INT NOT NULL,
        seller_id INT NOT NULL,
        amount INT NOT NULL, -- Diamonds paid
        status ENUM('pending', 'completed', 'cancelled', 'disputed') DEFAULT 'pending',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (service_id) REFERENCES services(id),
        FOREIGN KEY (buyer_id) REFERENCES users(id),
        FOREIGN KEY (seller_id) REFERENCES users(id)
    )";
    $pdo->exec($sql_orders);
    echo "✅ Table 'orders' created successfully.<br>";

    echo "<hr>🎉 Marketplace DB Setup Complete!";

} catch (PDOException $e) {
    die("❌ DB Error: " . $e->getMessage());
}
?>
