<?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
$host = 'localhost';
$dbname = 'astro_db';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    try {
        // Get tatkal settings
        $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM tatkal_settings");
        $stmt->execute();
        $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        
        // Get tatkal appointments with payment info
        $stmt = $pdo->prepare("
            SELECT 
                ta.*,
                tp.transaction_id,
                tp.payment_status,
                tp.payment_method,
                u.name as user_name,
                u.mobile as user_mobile 
            FROM tatkal_appointments ta 
            LEFT JOIN tatkal_payments tp ON ta.id = tp.tatkal_appointment_id
            LEFT JOIN users u ON ta.user_id = u.id 
            ORDER BY ta.appointment_date DESC, ta.created_at DESC
        ");
        $stmt->execute();
        $appointments = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get statistics
        $stats = [];
        
        // Total tatkal appointments
        $stmt = $pdo->query("SELECT COUNT(*) FROM tatkal_appointments");
        $stats['total_appointments'] = $stmt->fetchColumn();
        
        // Pending appointments
        $stmt = $pdo->query("SELECT COUNT(*) FROM tatkal_appointments WHERE status = 'pending'");
        $stats['pending_appointments'] = $stmt->fetchColumn();
        
        // Confirmed appointments
        $stmt = $pdo->query("SELECT COUNT(*) FROM tatkal_appointments WHERE status = 'confirmed'");
        $stats['confirmed_appointments'] = $stmt->fetchColumn();
        
        // Today's appointments
        $stmt = $pdo->query("SELECT COUNT(*) FROM tatkal_appointments WHERE appointment_date = CURDATE()");
        $stats['today_appointments'] = $stmt->fetchColumn();
        
        // Total revenue
        $stmt = $pdo->query("SELECT SUM(amount) FROM tatkal_appointments WHERE status != 'cancelled'");
        $stats['total_revenue'] = $stmt->fetchColumn() ?: 0;
        
        // Paid appointments
        $stmt = $pdo->query("SELECT COUNT(*) FROM tatkal_payments WHERE payment_status = 'success'");
        $stats['paid_appointments'] = $stmt->fetchColumn();
        
        echo json_encode([
            'success' => true,
            'settings' => $settings,
            'appointments' => $appointments,
            'stats' => $stats
        ]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
} 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 tatkal_appointments SET status = ? WHERE id = ?");
            $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()]);
        }
    } elseif ($input['action'] == 'update_payment_status') {
        try {
            $appointment_id = $input['appointment_id'];
            $payment_status = $input['payment_status'];
            
            $stmt = $pdo->prepare("UPDATE tatkal_payments SET payment_status = ? WHERE tatkal_appointment_id = ?");
            $result = $stmt->execute([$payment_status, $appointment_id]);
            
            if ($result) {
                // Also update appointment payment status
                $stmt = $pdo->prepare("UPDATE tatkal_appointments SET payment_status = ? WHERE id = ?");
                $stmt->execute([$payment_status, $appointment_id]);
                
                echo json_encode(['success' => true, 'message' => 'Payment status updated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to update payment status']);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error updating payment: ' . $e->getMessage()]);
        }
    } elseif ($input['action'] == 'cancel_appointment') {
        try {
            $appointment_id = $input['appointment_id'];
            $reason = $input['reason'] ?? 'Cancelled by admin';
            
            // Update appointment status
            $stmt = $pdo->prepare("UPDATE tatkal_appointments SET status = 'cancelled', notes = ? WHERE id = ?");
            $stmt->execute([$reason, $appointment_id]);
            
            // Update payment status if needed
            $stmt = $pdo->prepare("UPDATE tatkal_payments SET payment_status = 'refunded' WHERE tatkal_appointment_id = ?");
            $stmt->execute([$appointment_id]);
            
            echo json_encode(['success' => true, 'message' => 'Appointment cancelled successfully']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error cancelling appointment: ' . $e->getMessage()]);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}
?>
