<?php
require_once '../config.php';
header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not logged in']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$customer_id = $_SESSION['user_id'];
$property_id = intval($input['property_id'] ?? 0);
$appointment_date = trim($input['appointment_date'] ?? '');
$appointment_time = trim($input['appointment_time'] ?? '');
$message = trim($input['message'] ?? '');

if ($property_id <= 0 || empty($appointment_date) || empty($appointment_time)) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

try {
    // Ensure appointments table has required columns
    $conn->query("ALTER TABLE appointments ADD COLUMN IF NOT EXISTS customer_id INT AFTER id");
    $conn->query("ALTER TABLE appointments ADD COLUMN IF NOT EXISTS appointment_date DATE AFTER property_id");
    $conn->query("ALTER TABLE appointments ADD COLUMN IF NOT EXISTS appointment_time TIME AFTER appointment_date");
    $conn->query("ALTER TABLE appointments ADD COLUMN IF NOT EXISTS status VARCHAR(50) DEFAULT 'pending' AFTER appointment_time");
    $conn->query("ALTER TABLE appointments ADD COLUMN IF NOT EXISTS message TEXT AFTER status");
    $conn->query("ALTER TABLE appointments ADD COLUMN IF NOT EXISTS created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP");

    $stmt = $conn->prepare("
        INSERT INTO appointments (customer_id, property_id, appointment_date, appointment_time, message, status)
        VALUES (?, ?, ?, ?, ?, 'pending')
    ");
    $stmt->bind_param('iisss', $customer_id, $property_id, $appointment_date, $appointment_time, $message);
    $result = $stmt->execute();
    $stmt->close();

    if ($result) {
        echo json_encode(['success' => true, 'message' => 'Appointment created successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to create appointment']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
