<?php
/**
 * Broker - Schedule Site Visit
 * POST: Allows broker to schedule/confirm/complete site visits
 */

header('Content-Type: application/json');
require_once '../../config.php';
require_once __DIR__ . '/broker-identity.php';

$session_role = $_SESSION['role'] ?? ($_SESSION['user_role'] ?? '');
if (!isset($_SESSION['user_id']) || $session_role !== 'broker') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$session_broker_id = (int)$_SESSION['user_id'];
$brokerCtx = resolveBrokerContext($conn, $session_broker_id);
$broker_id = (int)$brokerCtx['property_broker_id'];
$fallback_broker_id = $session_broker_id !== $broker_id ? $session_broker_id : 0;
$data = json_decode(file_get_contents('php://input'), true);

try {
    if (!isset($data['action'])) {
        echo json_encode(['success' => false, 'message' => 'Missing action']);
        exit;
    }

    $action = $data['action']; // 'create', 'confirm', 'complete'

    if ($action === 'create') {
        if (!isset($data['customer_id'], $data['property_id'], $data['appointment_date'], $data['appointment_time'])) {
            echo json_encode(['success' => false, 'message' => 'Missing parameters']);
            exit;
        }

        $customer_id = (int)$data['customer_id'];
        $property_id = (int)$data['property_id'];
        $appointment_date = $data['appointment_date'];
        $appointment_time = $data['appointment_time'];
        $message = $data['message'] ?? null;

        // Verify broker owns the property
        $stmt = $conn->prepare("
            SELECT id
            FROM properties
            WHERE id = ? AND (broker_id = ? OR (? > 0 AND broker_id = ?))
        ");
        $stmt->bind_param('iiii', $property_id, $broker_id, $fallback_broker_id, $fallback_broker_id);
        $stmt->execute();
        if ($stmt->get_result()->num_rows === 0) {
            echo json_encode(['success' => false, 'message' => 'Property not found']);
            $stmt->close();
            exit;
        }
        $stmt->close();

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

        echo json_encode(['success' => true, 'message' => 'Visit scheduled', 'appointment_id' => $appointment_id]);
    }
    else if ($action === 'confirm') {
        if (!isset($data['appointment_id'])) {
            echo json_encode(['success' => false, 'message' => 'Missing appointment_id']);
            exit;
        }

        $appointment_id = (int)$data['appointment_id'];

        // Verify broker owns this appointment
        $stmt = $conn->prepare("
            SELECT a.id
            FROM appointments a
            JOIN properties p ON p.id = a.property_id
            WHERE a.id = ? AND (
                a.user_id = ?
                OR p.broker_id = ?
                OR (? > 0 AND p.broker_id = ?)
            )
            LIMIT 1
        ");
        $stmt->bind_param('iiiii', $appointment_id, $session_broker_id, $broker_id, $fallback_broker_id, $fallback_broker_id);
        $stmt->execute();
        if ($stmt->get_result()->num_rows === 0) {
            echo json_encode(['success' => false, 'message' => 'Appointment not found']);
            $stmt->close();
            exit;
        }
        $stmt->close();

        $stmt = $conn->prepare("UPDATE appointments SET status = 'confirmed' WHERE id = ?");
        $stmt->bind_param('i', $appointment_id);
        $stmt->execute();
        $stmt->close();

        echo json_encode(['success' => true, 'message' => 'Visit confirmed']);
    }
    else if ($action === 'complete') {
        if (!isset($data['appointment_id'])) {
            echo json_encode(['success' => false, 'message' => 'Missing appointment_id']);
            exit;
        }

        $appointment_id = (int)$data['appointment_id'];
        $notes = $data['notes'] ?? null;

        // Verify broker owns this appointment
        $stmt = $conn->prepare("
            SELECT a.id
            FROM appointments a
            JOIN properties p ON p.id = a.property_id
            WHERE a.id = ? AND (
                a.user_id = ?
                OR p.broker_id = ?
                OR (? > 0 AND p.broker_id = ?)
            )
            LIMIT 1
        ");
        $stmt->bind_param('iiiii', $appointment_id, $session_broker_id, $broker_id, $fallback_broker_id, $fallback_broker_id);
        $stmt->execute();
        if ($stmt->get_result()->num_rows === 0) {
            echo json_encode(['success' => false, 'message' => 'Appointment not found']);
            $stmt->close();
            exit;
        }
        $stmt->close();

        $stmt = $conn->prepare("UPDATE appointments SET status = 'completed', message = ? WHERE id = ?");
        $stmt->bind_param('si', $notes, $appointment_id);
        $stmt->execute();
        $stmt->close();

        echo json_encode(['success' => true, 'message' => 'Visit marked complete']);
    }
    else {
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }

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