<?php
header("Content-Type: application/json; charset=UTF-8");
require_once '../config/cors.php';
require_once '../config/database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception('Database connection failed');
    }
    
    // Create deals table
    $createDealsTable = "
        CREATE TABLE IF NOT EXISTS deals (
            id VARCHAR(36) PRIMARY KEY,
            product_id VARCHAR(36) NOT NULL,
            title VARCHAR(255) NOT NULL,
            description TEXT,
            discount_percentage DECIMAL(5,2) NOT NULL,
            original_price DECIMAL(10,2) NOT NULL,
            discounted_price DECIMAL(10,2) NOT NULL,
            is_flash_deal BOOLEAN DEFAULT FALSE,
            flash_deal_hours INT DEFAULT 24,
            social_requirements JSON,
            is_active BOOLEAN DEFAULT TRUE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            expires_at TIMESTAMP NULL,
            INDEX idx_product_id (product_id),
            INDEX idx_is_active (is_active),
            INDEX idx_expires_at (expires_at)
        )";
    
    $db->exec($createDealsTable);
    
    // Create user_deal_progress table
    $createProgressTable = "
        CREATE TABLE IF NOT EXISTS user_deal_progress (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            deal_id VARCHAR(36) NOT NULL,
            instagram_completed BOOLEAN DEFAULT FALSE,
            youtube_completed BOOLEAN DEFAULT FALSE,
            instagram_completed_at TIMESTAMP NULL,
            youtube_completed_at TIMESTAMP NULL,
            deal_unlocked BOOLEAN DEFAULT FALSE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY unique_user_deal (user_id, deal_id),
            INDEX idx_user_id (user_id),
            INDEX idx_deal_id (deal_id)
        )";
    
    $db->exec($createProgressTable);
    
    // Add discount columns to products table if they don't exist
    try {
        $db->exec("ALTER TABLE products ADD COLUMN discount_percentage DECIMAL(5,2) DEFAULT 0");
    } catch (Exception $e) {
        // Column might already exist
    }
    
    try {
        $db->exec("ALTER TABLE products ADD COLUMN discounted_price DECIMAL(10,2) NULL");
    } catch (Exception $e) {
        // Column might already exist
    }
    
    try {
        $db->exec("ALTER TABLE products ADD COLUMN has_deal BOOLEAN DEFAULT FALSE");
    } catch (Exception $e) {
        // Column might already exist
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Deals tables created successfully'
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>