<?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();
    
    // Update database schema if needed
    try {
        $pdo->exec("
            ALTER TABLE appointments 
            MODIFY COLUMN status ENUM('pending', 'pending_payment', 'confirmed', 'cancelled', 'completed') DEFAULT 'pending'
        ");
    } catch (PDOException $e) {
        // Schema might already be updated, continue
        error_log('Schema update note: ' . $e->getMessage());
    }
    
    // Add updated_at column if it doesn't exist
    try {
        $pdo->exec("
            ALTER TABLE appointments 
            ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ");
    } catch (PDOException $e) {
        // Column might already exist, continue
        error_log('Updated_at column note: ' . $e->getMessage());
    }
    
    $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 appointment exists (first check without status filter)
    $stmt = $pdo->prepare("
        SELECT id, user_id, user_name, appointment_date, time_slot, amount, status 
        FROM appointments 
        WHERE id = ?
    ");
    $stmt->execute([$appointmentId]);
    $appointment = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$appointment) {
        throw new Exception('Appointment not found');
    }
    
    // Check if appointment is in correct status for confirmation
    // Accept both 'pending' and 'pending_payment' for backward compatibility
    if (!in_array($appointment['status'], ['pending', 'pending_payment'])) {
        // If already confirmed, return success
        if ($appointment['status'] === 'confirmed') {
            echo json_encode([
                'success' => true,
                'message' => 'Booking already confirmed',
                'appointment_id' => $appointmentId,
                'status' => 'confirmed',
                'transaction_id' => $transactionId
            ]);
            exit;
        }
        
        // If appointment is cancelled or completed, don't allow confirmation
        if (in_array($appointment['status'], ['cancelled', 'completed'])) {
            throw new Exception('Appointment status is ' . $appointment['status'] . ', cannot be confirmed');
        }
        
        // For any other status, try to confirm anyway
        error_log("Appointment status is {$appointment['status']}, attempting confirmation anyway");
    }
    
    // Check if appointment is already confirmed by payment callback
    if ($appointment['status'] === 'confirmed') {
        echo json_encode([
            'success' => true,
            'message' => 'Booking already confirmed by payment callback',
            'appointment_id' => $appointmentId,
            'status' => 'confirmed',
            'transaction_id' => $transactionId
        ]);
        exit;
    }
    
    // Start transaction
    $pdo->beginTransaction();
    
    try {
        // Update appointment status to confirmed
        $stmt = $pdo->prepare("
            UPDATE appointments 
            SET status = 'confirmed', updated_at = NOW() 
            WHERE id = ?
        ");
        $stmt->execute([$appointmentId]);
        
        // Insert payment record
        $stmt = $pdo->prepare("
            INSERT INTO payments (
                appointment_id, transaction_id, amount, status, 
                payment_method, created_at, updated_at
            ) VALUES (?, ?, ?, 'SUCCESS', 'PHONEPE', NOW(), NOW())
        ");
        $stmt->execute([$appointmentId, $transactionId, $amount]);
        
        // Commit transaction
        $pdo->commit();
        
        echo json_encode([
            'success' => true,
            'message' => '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'
    ]);
}
?>
