<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight request
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Database configuration - Try multiple connection methods
$pdo = null;

// Method 1: Try to include existing database config
try {
    if (file_exists('../config/database.php')) {
        require_once '../config/database.php';
        $pdo = getDBConnection();
    }
} catch (Exception $e) {
    // Continue to next method
}

// Method 2: Try direct connection with common configurations
if (!$pdo) {
    $configs = [
        // Common hosting configurations
        ['host' => 'localhost', 'dbname' => 'astro_db', 'username' => 'root', 'password' => ''],
        ['host' => 'localhost', 'dbname' => 'u123456789_astro', 'username' => 'u123456789_astro', 'password' => 'your_password'],
        ['host' => 'localhost', 'dbname' => 'astro_sidhi', 'username' => 'astro_sidhi', 'password' => 'your_password'],
        ['host' => 'localhost', 'dbname' => 'siddharth_astro', 'username' => 'siddharth_astro', 'password' => 'your_password'],
    ];
    
    foreach ($configs as $config) {
        try {
            $pdo = new PDO(
                "mysql:host={$config['host']};dbname={$config['dbname']};charset=utf8", 
                $config['username'], 
                $config['password']
            );
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            break; // Connection successful
        } catch (PDOException $e) {
            continue; // Try next configuration
        }
    }
}

// Method 3: Try to get connection from environment or existing files
if (!$pdo) {
    try {
        // Check if there's a config file with database details
        $config_file = '../config/config.php';
        if (file_exists($config_file)) {
            include $config_file;
            if (isset($db_host) && isset($db_name) && isset($db_user) && isset($db_pass)) {
                $pdo = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", $db_user, $db_pass);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }
        }
    } catch (Exception $e) {
        // Continue to error handling
    }
}

// If still no connection, return error
if (!$pdo) {
    echo json_encode([
        'success' => false, 
        'message' => 'Database connection failed. Please check your database configuration.',
        'debug_info' => [
            'config_file_exists' => file_exists('../config/database.php'),
            'current_dir' => __DIR__,
            'server_name' => $_SERVER['SERVER_NAME'] ?? 'unknown'
        ]
    ]);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    try {
        // First check if tatkal_settings table exists, if not create it
        $stmt = $pdo->query("SHOW TABLES LIKE 'tatkal_settings'");
        if ($stmt->rowCount() == 0) {
            // Create tatkal_settings table
            $pdo->exec("
                CREATE TABLE tatkal_settings (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    setting_key VARCHAR(100) UNIQUE NOT NULL,
                    setting_value TEXT NOT NULL,
                    description TEXT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
                )
            ");
            
            // Insert default settings
            $pdo->exec("
                INSERT INTO tatkal_settings (setting_key, setting_value, description) VALUES 
                ('tatkal_enabled', '1', 'Enable/Disable tatkal booking'),
                ('tatkal_price', '1500', 'Default tatkal price per person'),
                ('tatkal_slots', '10', 'Maximum tatkal slots per day'),
                ('tatkal_advance_days', '7', 'Maximum days in advance for booking'),
                ('tatkal_monday', '1', 'Tatkal available on Monday'),
                ('tatkal_tuesday', '1', 'Tatkal available on Tuesday'),
                ('tatkal_wednesday', '1', 'Tatkal available on Wednesday'),
                ('tatkal_thursday', '1', 'Tatkal available on Thursday'),
                ('tatkal_friday', '1', 'Tatkal available on Friday'),
                ('tatkal_saturday', '1', 'Tatkal available on Saturday'),
                ('tatkal_sunday', '0', 'Tatkal available on Sunday')
            ");
        }
        
        // Get tatkal settings
        $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM tatkal_settings");
        $stmt->execute();
        $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        
        // Check if appointments table has is_tatkal column
        $stmt = $pdo->query("SHOW COLUMNS FROM appointments LIKE 'is_tatkal'");
        if ($stmt->rowCount() == 0) {
            // Add is_tatkal column to appointments table
            $pdo->exec("ALTER TABLE appointments ADD COLUMN is_tatkal BOOLEAN DEFAULT FALSE");
        }
        
        // Get tatkal appointments
        $stmt = $pdo->prepare("
            SELECT a.*, u.name as user_name, u.mobile as user_mobile 
            FROM appointments a 
            LEFT JOIN users u ON a.user_id = u.id 
            WHERE a.is_tatkal = 1 
            ORDER BY a.appointment_date DESC, a.created_at DESC
        ");
        $stmt->execute();
        $appointments = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'settings' => $settings,
            'appointments' => $appointments,
            'debug_info' => [
                'database_connected' => true,
                'settings_count' => count($settings),
                'appointments_count' => count($appointments)
            ]
        ]);
    } catch (Exception $e) {
        echo json_encode([
            'success' => false, 
            'message' => 'Error: ' . $e->getMessage(),
            'debug_info' => [
                'error_line' => $e->getLine(),
                'error_file' => $e->getFile()
            ]
        ]);
    }
} elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if ($input['action'] == 'update_settings') {
        try {
            $settings = $input['settings'];
            
            foreach ($settings as $key => $value) {
                $stmt = $pdo->prepare("
                    INSERT INTO tatkal_settings (setting_key, setting_value) 
                    VALUES (?, ?) 
                    ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
                ");
                $stmt->execute([$key, $value]);
            }
            
            echo json_encode(['success' => true, 'message' => 'Settings updated successfully']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error updating settings: ' . $e->getMessage()]);
        }
    } elseif ($input['action'] == 'update_appointment_status') {
        try {
            $appointment_id = $input['appointment_id'];
            $status = $input['status'];
            
            $stmt = $pdo->prepare("UPDATE appointments SET status = ? WHERE id = ? AND is_tatkal = 1");
            $result = $stmt->execute([$status, $appointment_id]);
            
            if ($result) {
                echo json_encode(['success' => true, 'message' => 'Appointment status updated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to update appointment status']);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error updating appointment: ' . $e->getMessage()]);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}
?>
