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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

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

try {
    $pdo = getDBConnection();
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid JSON input');
    }
    
    // Validate required fields
    $required_fields = ['appointment_id', 'transaction_id', 'amount'];
    foreach ($required_fields as $field) {
        if (empty($input[$field])) {
            throw new Exception("Field '$field' is required");
        }
    }
    
    $appointmentId = $input['appointment_id'];
    $transactionId = $input['transaction_id'];
    $amount = $input['amount'];
    
    // Validate appointment ID
    if (!is_numeric($appointmentId) || $appointmentId <= 0) {
        throw new Exception('Invalid appointment ID');
    }
    
    // Validate amount
    if (!is_numeric($amount) || $amount <= 0) {
        throw new Exception('Invalid amount');
    }
    
    // Check if tatkal appointment exists
    $stmt = $pdo->prepare("
        SELECT id, user_id, user_name, appointment_date, amount, status, payment_status
        FROM tatkal_appointments 
        WHERE id = ?
    ");
    $stmt->execute([$appointmentId]);
    $appointment = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$appointment) {
        throw new Exception('Tatkal appointment not found');
    }
    
    // Check if appointment is in correct status for confirmation
    if (!in_array($appointment['status'], ['pending'])) {
        // If already confirmed, return success
        if ($appointment['status'] === 'confirmed') {
            echo json_encode([
                'success' => true,
                'message' => 'Tatkal booking already confirmed',
                'appointment_id' => $appointmentId,
                'status' => 'confirmed',
                'transaction_id' => $transactionId
            ]);
            exit;
        }
        
        throw new Exception('Tatkal appointment status is ' . $appointment['status'] . ', expected pending');
    }
    
    // Check if appointment is already confirmed by payment callback
    if ($appointment['status'] === 'confirmed') {
        echo json_encode([
            'success' => true,
            'message' => 'Tatkal booking already confirmed by payment callback',
            'appointment_id' => $appointmentId,
            'status' => 'confirmed',
            'transaction_id' => $transactionId
        ]);
        exit;
    }
    
    // Start transaction
    $pdo->beginTransaction();
    
    try {
        // Update tatkal appointment status to confirmed
        $stmt = $pdo->prepare("
            UPDATE tatkal_appointments 
            SET status = 'confirmed', payment_status = 'paid', updated_at = NOW() 
            WHERE id = ?
        ");
        $stmt->execute([$appointmentId]);
        
        // Update tatkal payment record
        $stmt = $pdo->prepare("
            UPDATE tatkal_payments 
            SET payment_status = 'SUCCESS', transaction_id = ?, updated_at = NOW()
            WHERE tatkal_appointment_id = ?
        ");
        $stmt->execute([$transactionId, $appointmentId]);
        
        // Commit transaction
        $pdo->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Tatkal booking confirmed successfully',
            'appointment_id' => $appointmentId,
            'status' => 'confirmed',
            'transaction_id' => $transactionId
        ]);
        
    } catch (Exception $e) {
        // Rollback transaction on error
        $pdo->rollBack();
        throw $e;
    }
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error occurred'
    ]);
}
?>
