<?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'];
$appointment_id = intval($input['appointment_id'] ?? 0);
$visit_date = trim($input['visit_date'] ?? '');
$visit_time = trim($input['visit_time'] ?? '');

if ($appointment_id <= 0 || empty($visit_date) || empty($visit_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 property_id INT AFTER customer_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 time TIME AFTER appointment_date");
    $conn->query("ALTER TABLE appointments ADD COLUMN IF NOT EXISTS status VARCHAR(50) DEFAULT 'pending' AFTER time");

    // Check if appointment exists and belongs to customer
    $check_stmt = $conn->prepare("SELECT id FROM appointments WHERE id = ? AND customer_id = ?");
    $check_stmt->bind_param('ii', $appointment_id, $customer_id);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Appointment not found']);
        exit;
    }
    $check_stmt->close();

    // Update appointment
    $stmt = $conn->prepare("
        UPDATE appointments 
        SET appointment_date = ?, time = ?, status = 'scheduled'
        WHERE id = ? AND customer_id = ?
    ");
    $stmt->bind_param('ssii', $visit_date, $visit_time, $appointment_id, $customer_id);
    $result = $stmt->execute();
    $stmt->close();

    if ($result) {
        echo json_encode(['success' => true, 'message' => 'Visit scheduled successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to schedule visit']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
