<?php
// Prevent direct access
if (count(get_included_files()) === 1) {
    http_response_code(403);
    exit('Forbidden');
}

// Check authentication
if (!isset($_SESSION['user_id'])) {
    header('Location: /login');
    exit;
}

$tenant_id = $_SESSION['tenant_id'];
$db = DB::connect();

// Acciones sobre una cita (siempre scopeadas por tenant_id).
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $apptId = (int) ($_POST['appointment_id'] ?? 0);
    if ($apptId > 0) {
        $statusMap = ['confirm' => 'confirmed', 'complete' => 'completed', 'cancel' => 'canceled', 'no_show' => 'no_show'];
        if (isset($statusMap[$action])) {
            $stmt = $db->prepare("UPDATE appointments SET status = :s WHERE id = :id AND tenant_id = :t");
            $stmt->execute([':s' => $statusMap[$action], ':id' => $apptId, ':t' => $tenant_id]);
            $_SESSION['flash'] = 'Cita actualizada.';
        } elseif ($action === 'delete') {
            $stmt = $db->prepare("DELETE FROM appointments WHERE id = :id AND tenant_id = :t");
            $stmt->execute([':id' => $apptId, ':t' => $tenant_id]);
            $_SESSION['flash'] = 'Cita eliminada.';
        }
    }
    header('Location: /agenda');
    exit;
}

$flash = $_SESSION['flash'] ?? '';
unset($_SESSION['flash']);

// Citas del tenant. Scopeado por tenant_id.
$stmt = $db->prepare(
    "SELECT a.id, a.scheduled_at, a.status, a.source,
            c.name AS contact_name, c.phone AS contact_phone,
            s.name AS service_name
     FROM appointments a
     JOIN contacts c ON a.contact_id = c.id AND c.tenant_id = a.tenant_id
     LEFT JOIN services s ON a.service_id = s.id AND s.tenant_id = a.tenant_id
     WHERE a.tenant_id = :tenant_id
     ORDER BY a.scheduled_at DESC"
);
$stmt->execute([':tenant_id' => $tenant_id]);
$appointments = $stmt->fetchAll();

require dirname(__DIR__) . '/views/agenda.php';
