<?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'] == 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    // Validate required fields
    $required_fields = ['user_id', 'user_name', 'user_mobile', 'appointment_date', 'amount', 'consultation_type', 'number_of_persons', 'city'];
    foreach ($required_fields as $field) {
        if (!isset($input[$field]) || empty($input[$field])) {
            echo json_encode(['success' => false, 'message' => "Missing required field: $field"]);
            exit();
        }
    }
    
    try {
        // Start transaction
        $pdo->beginTransaction();
        
        // Check if tatkal is enabled
        $stmt = $pdo->prepare("SELECT setting_value FROM tatkal_settings WHERE setting_key = 'enabled'");
        $stmt->execute();
        $tatkal_enabled = $stmt->fetchColumn();
        
        if ($tatkal_enabled != '1') {
            throw new Exception('Tatkal booking is currently disabled');
        }
        
        // Validate date (not in the past)
        $appointment_date = $input['appointment_date'];
        $today = date('Y-m-d');
        if ($appointment_date <= $today) {
            throw new Exception('Cannot book for today or past dates');
        }
        
        // Check advance booking days
        $stmt = $pdo->prepare("SELECT setting_value FROM tatkal_settings WHERE setting_key = 'advance_days'");
        $stmt->execute();
        $advance_days = (int)$stmt->fetchColumn();
        $max_date = date('Y-m-d', strtotime("+$advance_days days"));
        
        if ($appointment_date > $max_date) {
            throw new Exception("Cannot book more than $advance_days days in advance");
        }
        
        // Check day-specific tatkal availability
        $day_of_week = strtolower(date('l', strtotime($appointment_date)));
        $stmt = $pdo->prepare("SELECT setting_value FROM tatkal_settings WHERE setting_key = ?");
        $stmt->execute([$day_of_week]);
        $day_enabled = $stmt->fetchColumn();
        
        if ($day_enabled != '1') {
            throw new Exception('Tatkal booking not available for this day');
        }
        
        // Check slot limits
        $stmt = $pdo->prepare("SELECT setting_value FROM tatkal_settings WHERE setting_key = 'max_slots'");
        $stmt->execute();
        $max_slots = (int)$stmt->fetchColumn();
        
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM tatkal_appointments WHERE appointment_date = ? AND status != 'cancelled'");
        $stmt->execute([$appointment_date]);
        $booked_slots = $stmt->fetchColumn();
        
        if ($booked_slots >= $max_slots) {
            throw new Exception('No tatkal slots available for this date');
        }
        
        // Insert tatkal appointment
        $stmt = $pdo->prepare("
            INSERT INTO tatkal_appointments (
                user_id, user_name, user_mobile, appointment_date, 
                amount, consultation_type, meeting_location, number_of_persons, 
                city, status, payment_status, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'pending', NOW())
        ");
        
        $result = $stmt->execute([
            $input['user_id'],
            $input['user_name'],
            $input['user_mobile'],
            $appointment_date,
            $input['amount'],
            $input['consultation_type'],
            $input['meeting_location'] ?? null,
            $input['number_of_persons'],
            $input['city']
        ]);
        
        if (!$result) {
            throw new Exception('Failed to book tatkal appointment');
        }
        
        $appointment_id = $pdo->lastInsertId();
        
        // Insert payment record
        $stmt = $pdo->prepare("
            INSERT INTO tatkal_payments (
                tatkal_appointment_id, amount, payment_method, 
                transaction_id, payment_status, created_at
            ) VALUES (?, ?, ?, ?, 'pending', NOW())
        ");
        
        $transaction_id = 'TATKAL_' . $appointment_id . '_' . time();
        $payment_method = $input['payment_method'] ?? 'cash';
        
        $stmt->execute([
            $appointment_id,
            $input['amount'],
            $payment_method,
            $transaction_id
        ]);
        
        // Commit transaction
        $pdo->commit();
        
        echo json_encode([
            'success' => true, 
            'message' => 'Tatkal appointment booked successfully',
            'appointment_id' => $appointment_id,
            'transaction_id' => $transaction_id
        ]);
        
    } catch (Exception $e) {
        // Rollback transaction on error
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}
?>
