<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once '../config/database.php';

try {
    $pdo = getDBConnection();
    
    // SQL Commands to fix the database schema
    $sqlCommands = [
        "ALTER TABLE appointments ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP",
        "ALTER TABLE appointments MODIFY COLUMN status ENUM('pending', 'pending_payment', 'confirmed', 'cancelled', 'completed') DEFAULT 'pending'"
    ];
    
    $results = [];
    
    foreach ($sqlCommands as $sql) {
        try {
            $pdo->exec($sql);
            $results[] = [
                'sql' => $sql,
                'success' => true,
                'message' => 'Executed successfully'
            ];
        } catch (PDOException $e) {
            $results[] = [
                'sql' => $sql,
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
    
    // Check current schema
    $stmt = $pdo->prepare("SHOW COLUMNS FROM appointments");
    $stmt->execute();
    $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Test insert with pending status
    try {
        $stmt = $pdo->prepare("
            INSERT INTO appointments (
                user_id, user_name, user_mobile, appointment_date, 
                time_slot, amount, status, consultation_type
            ) VALUES (?, ?, ?, ?, ?, ?, 'pending', ?)
        ");
        
        $testResult = $stmt->execute([
            1, 'Test User', '9999999999', '2024-01-01',
            '10:00 - 11:00', 100, 'video_call'
        ]);
        
        $testId = $pdo->lastInsertId();
        
        // Get the test record
        $stmt = $pdo->prepare("SELECT * FROM appointments WHERE id = ?");
        $stmt->execute([$testId]);
        $testRecord = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Clean up test record
        $pdo->exec("DELETE FROM appointments WHERE id = $testId");
        
        $testInsert = true;
    } catch (PDOException $e) {
        $testInsert = false;
        $testError = $e->getMessage();
    }
    
    echo json_encode([
        'success' => true,
        'sql_results' => $results,
        'current_columns' => $columns,
        'test_insert' => $testInsert,
        'test_error' => $testError ?? null,
        'test_record' => $testRecord ?? null
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
