<?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 {
    // Get database connection first
    $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 = ['user_id', 'user_name', 'user_mobile', 'appointment_date', 'time_slot', 'amount', 'consultation_type'];
    foreach ($required_fields as $field) {
        if (empty($input[$field])) {
            throw new Exception("Field '$field' is required");
        }
    }
    
    // Validate user_id
    if (!is_numeric($input['user_id']) || $input['user_id'] <= 0) {
        throw new Exception('Invalid user ID');
    }
    
    // Validate appointment date
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $input['appointment_date'])) {
        throw new Exception('Invalid appointment date format');
    }
    
    // Check if date is in the past
    $appointmentDate = new DateTime($input['appointment_date']);
    $today = new DateTime();
    $today->setTime(0, 0, 0);
    
    if ($appointmentDate < $today) {
        throw new Exception('Cannot book appointments for past dates');
    }
    
    // Validate amount
    if (!is_numeric($input['amount']) || $input['amount'] <= 0) {
        throw new Exception('Invalid amount');
    }
    
    // Validate consultation type
    $valid_consultation_types = ['office_meeting', 'video_call', 'audio_call'];
    if (!in_array($input['consultation_type'], $valid_consultation_types)) {
        throw new Exception('Invalid consultation type');
    }
    
    // Check if consultation type is enabled
    $consultation_type_key = $input['consultation_type'] . '_enabled';
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
    $stmt->execute([$consultation_type_key]);
    $consultation_enabled = $stmt->fetchColumn();
    
    // Handle different boolean values from database
    $is_enabled = false;
    if ($consultation_enabled !== null) {
        if (is_numeric($consultation_enabled)) {
            $is_enabled = ($consultation_enabled == 1);
        } elseif (is_string($consultation_enabled)) {
            $is_enabled = in_array(strtolower($consultation_enabled), ['on', '1', 'true', 'yes', 'enabled']);
        } else {
            $is_enabled = (bool)$consultation_enabled;
        }
    }
    
    if (!$is_enabled) {
        throw new Exception('This consultation type is currently disabled');
    }
    
    // Verify user exists
    $stmt = $pdo->prepare("SELECT id FROM users WHERE id = ?");
    $stmt->execute([$input['user_id']]);
    if (!$stmt->fetch()) {
        throw new Exception('User not found');
    }
    
    // Check if slot is still available (only block confirmed/completed)
    $stmt = $pdo->prepare("
        SELECT id FROM appointments 
        WHERE appointment_date = ? AND time_slot = ? 
        AND status IN ('confirmed', 'completed')
    ");
    $stmt->execute([$input['appointment_date'], $input['time_slot']]);
    
    if ($stmt->fetch()) {
        throw new Exception('This time slot is no longer available or is currently being booked');
    }
    
    // Get settings to validate advance booking
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'advance_booking_days'");
    $stmt->execute();
    $advanceDays = (int)($stmt->fetchColumn() ?? 30);
    
    $maxDate = clone $today;
    $maxDate->add(new DateInterval("P{$advanceDays}D"));
    
    if ($appointmentDate > $maxDate) {
        throw new Exception("Bookings are only allowed up to {$advanceDays} days in advance");
    }
    
    // Check if this day is enabled for booking
    $day_name = strtolower($appointmentDate->format('l'));
    $day_booking_key = $day_name . '_booking';
    
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
    $stmt->execute([$day_booking_key]);
    $day_enabled = $stmt->fetchColumn();
    
    // Handle different boolean values from database
    $is_day_enabled = false;
    if ($day_enabled !== null) {
        if (is_numeric($day_enabled)) {
            $is_day_enabled = ($day_enabled == 1);
        } elseif (is_string($day_enabled)) {
            $is_day_enabled = in_array(strtolower($day_enabled), ['on', '1', 'true', 'yes', 'enabled']);
        } else {
            $is_day_enabled = (bool)$day_enabled;
        }
    }
    
    if (!$is_day_enabled) {
        throw new Exception('Bookings are not allowed on ' . ucfirst($day_name));
    }
    
    // Check if date is specifically blocked
    $stmt = $pdo->prepare("SELECT id FROM blocked_dates WHERE block_date = ?");
    $stmt->execute([$input['appointment_date']]);
    if ($stmt->fetch()) {
        throw new Exception('This date is blocked for bookings');
    }
    
    // User can book multiple appointments per day (removed limit)
    // This allows users to book as many appointments as they want
    
            // Insert appointment
        $stmt = $pdo->prepare("
            INSERT INTO appointments (
                user_id, user_name, user_mobile, appointment_date, 
                time_slot, amount, status, consultation_type
            ) VALUES (?, ?, ?, ?, ?, ?, 'pending', ?)
        ");
        
        $stmt->execute([
            $input['user_id'],
            trim($input['user_name']),
            trim($input['user_mobile']),
            $input['appointment_date'],
            trim($input['time_slot']),
            $input['amount'],
            $input['consultation_type'] ?? 'video_call'
        ]);
    
    $appointmentId = $pdo->lastInsertId();
    
    echo json_encode([
        'success' => true,
        'message' => 'Appointment booked successfully',
        'appointment_id' => $appointmentId,
        'appointment_date' => $input['appointment_date'],
        'time_slot' => $input['time_slot'],
        'amount' => $input['amount']
    ]);
    
} 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'
    ]);
}
?> 