<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0);

// Log errors to file
ini_set('log_errors', 1);
$logFile = dirname(__FILE__) . '/../appointment_debug.log';
ini_set('error_log', $logFile);

header('Content-Type: application/json');

try {
    // Check config exists
    $configPath = dirname(__FILE__) . '/../config.php';
    if (!file_exists($configPath)) {
        error_log('ERROR: config.php not found at ' . $configPath);
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Configuration file not found']);
        exit;
    }

    require_once $configPath;
    
    // Check connection exists
    if (!isset($conn)) {
        error_log('ERROR: $conn not defined in config.php');
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Database not configured']);
        exit;
    }
    
    // Check connection error
    if ($conn->connect_error) {
        error_log('ERROR: Database connection failed: ' . $conn->connect_error);
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Database connection failed']);
        exit;
    }
    
    // Check if request is POST
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid request method']);
        exit;
    }

    // Get JSON data
    $input = json_decode(file_get_contents('php://input'), true);

    if (!$input) {
        error_log('ERROR: Invalid JSON received');
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid JSON data']);
        exit;
    }
    
    error_log('DEBUG: Input received - ' . json_encode($input));

    // Extract and validate data
    $fullName = trim($input['fullName'] ?? '');
    $email = trim($input['email'] ?? '');
    $phone = trim($input['phone'] ?? '');
    $appointmentDate = trim($input['appointmentDate'] ?? '');
    $appointmentTime = trim($input['appointmentTime'] ?? '');
    $appointmentType = trim($input['appointmentType'] ?? '');
    $propertyTypes = $input['propertyTypes'] ?? [];
    $budgetRange = trim($input['budgetRange'] ?? '');
    $message = trim($input['message'] ?? '');

    error_log('DEBUG: Extracted data - Name: ' . $fullName . ', Email: ' . $email);

    // Validate required fields
    if (empty($fullName) || empty($email) || empty($phone) || 
        empty($appointmentDate) || empty($appointmentTime) || 
        empty($appointmentType) || empty($propertyTypes)) {
        error_log('ERROR: Missing required fields - Name:' . empty($fullName) . ', Email:' . empty($email) . ', Phone:' . empty($phone) . ', Date:' . empty($appointmentDate) . ', Time:' . empty($appointmentTime) . ', Type:' . empty($appointmentType));
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        exit;
    }

    // Validate email
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        error_log('ERROR: Invalid email format: ' . $email);
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid email address']);
        exit;
    }

    // Validate phone (basic validation)
    if (!preg_match('/^[\d\s\-\+\(\)]{10,}$/', $phone)) {
        error_log('ERROR: Invalid phone format: ' . $phone);
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid phone number']);
        exit;
    }

    // Validate date
    $date = DateTime::createFromFormat('Y-m-d', $appointmentDate);
    if (!$date || $date->format('Y-m-d') !== $appointmentDate) {
        error_log('ERROR: Invalid date format: ' . $appointmentDate);
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid date format']);
        exit;
    }

    // Validate time
    $time = DateTime::createFromFormat('H:i', $appointmentTime);
    if (!$time || $time->format('H:i') !== $appointmentTime) {
        error_log('ERROR: Invalid time format: ' . $appointmentTime);
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid time format']);
        exit;
    }

    // Validate future date
    $selectedDateTime = strtotime($appointmentDate . ' ' . $appointmentTime);
    $now = time();
    if ($selectedDateTime < $now) {
        error_log('ERROR: Date is in the past: ' . $appointmentDate . ' ' . $appointmentTime);
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Appointment date and time must be in the future']);
        exit;
    }

    // Convert arrays to comma-separated strings
    $propertyTypesStr = implode(',', array_map('trim', $propertyTypes));

    // Check if table exists, create if not
    $tableCheck = $conn->query("SHOW TABLES LIKE 'appointments'");
    if (!$tableCheck || $tableCheck->num_rows === 0) {
        error_log('DEBUG: Appointments table does not exist, creating...');
        $createTable = "CREATE TABLE IF NOT EXISTS appointments (
          id INT AUTO_INCREMENT PRIMARY KEY,
          full_name VARCHAR(100) NOT NULL,
          email VARCHAR(100) NOT NULL,
          phone VARCHAR(20) NOT NULL,
          appointment_date DATE NOT NULL,
          appointment_time TIME NOT NULL,
          appointment_type VARCHAR(50) NOT NULL,
          property_types VARCHAR(255),
          budget_range VARCHAR(50),
          message LONGTEXT,
          status VARCHAR(20) DEFAULT 'pending',
          notes LONGTEXT,
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          INDEX idx_email (email),
          INDEX idx_date (appointment_date),
          INDEX idx_status (status)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
        
        if (!$conn->query($createTable)) {
            error_log('ERROR: Failed to create appointments table: ' . $conn->error);
            throw new Exception('Error creating appointments table: ' . $conn->error);
        }
        error_log('DEBUG: Appointments table created successfully');
    }

    // Prepare SQL statement
    $query = "INSERT INTO appointments 
              (full_name, email, phone, appointment_date, appointment_time, appointment_type, 
               property_types, budget_range, message, status, created_at) 
              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())";

    $stmt = $conn->prepare($query);

    if (!$stmt) {
        error_log('ERROR: Failed to prepare statement: ' . $conn->error);
        http_response_code(500);
        throw new Exception('Database prepare error: ' . $conn->error);
    }

    // Bind parameters
    $stmt->bind_param(
        'sssssssss',
        $fullName,
        $email,
        $phone,
        $appointmentDate,
        $appointmentTime,
        $appointmentType,
        $propertyTypesStr,
        $budgetRange,
        $message
    );

    // Execute query
    if (!$stmt->execute()) {
        error_log('ERROR: Failed to execute query: ' . $stmt->error);
        http_response_code(500);
        throw new Exception('Error executing query: ' . $stmt->error);
    }

    $appointmentId = $stmt->insert_id;
    error_log('SUCCESS: Appointment created with ID: ' . $appointmentId);
    
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'message' => 'Appointment booked successfully! We will contact you soon.',
        'appointmentId' => $appointmentId
    ]);

    $stmt->close();
    $conn->close();

} catch (Exception $e) {
    error_log('EXCEPTION: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    exit;
}
?>
