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

$page_title = 'Agenda - Vale';

$statusLabels = [
    'booked' => 'Agendada', 'confirmed' => 'Confirmada', 'no_show' => 'No vino',
    'completed' => 'Completada', 'canceled' => 'Cancelada',
];
$statusColors = [
    'booked' => ['bg' => 'rgba(224,163,62,.18)', 'fg' => '#9a6a14'],
    'confirmed' => ['bg' => 'rgba(30,122,77,.15)', 'fg' => '#1E7A4D'],
    'completed' => ['bg' => 'rgba(34,28,24,.08)', 'fg' => '#555'],
    'no_show' => ['bg' => 'rgba(192,57,43,.12)', 'fg' => '#C0392B'],
    'canceled' => ['bg' => 'rgba(34,28,24,.05)', 'fg' => '#999'],
];

$viewMode = ($_GET['view'] ?? 'calendar') === 'list' ? 'list' : 'calendar';

// Mes visible (YYYY-MM)
$monthParam = $_GET['month'] ?? date('Y-m');
$firstDay = DateTime::createFromFormat('Y-m-d', $monthParam . '-01');
if (!$firstDay) {
    $firstDay = new DateTime('first day of this month');
}
$firstDay->setTime(0, 0);
$monthLabel = ['01' => 'Enero', '02' => 'Febrero', '03' => 'Marzo', '04' => 'Abril', '05' => 'Mayo', '06' => 'Junio',
               '07' => 'Julio', '08' => 'Agosto', '09' => 'Septiembre', '10' => 'Octubre', '11' => 'Noviembre', '12' => 'Diciembre'];
$daysInMonth = (int) $firstDay->format('t');
$startWeekday = (int) $firstDay->format('N'); // 1=Lun..7=Dom
$prevMonth = (clone $firstDay)->modify('-1 month')->format('Y-m');
$nextMonth = (clone $firstDay)->modify('+1 month')->format('Y-m');
$todayStr = date('Y-m-d');

// Agrupar citas por día
$byDay = [];
foreach ($appointments as $a) {
    $byDay[substr($a['scheduled_at'], 0, 10)][] = $a;
}

ob_start();
?>
<div class="dashboard-container">
    <?php $activeNav = 'agenda'; require __DIR__ . '/partials/sidebar.php'; ?>

    <main class="main-content">
        <?php if (!empty($_SESSION['impersonated_by_admin'])): ?>
            <div style="background:#E0A33E;color:#221C18;padding:.5rem 1rem;font-size:.85rem;display:flex;justify-content:space-between;align-items:center;">
                <span>Estás viendo como <strong><?php echo htmlspecialchars($_SESSION['tenant_name'] ?? 'negocio'); ?></strong> (impersonación de admin).</span>
                <a href="/admin/stop-impersonate" style="color:#A8331A;font-weight:600;">Salir de impersonación</a>
            </div>
        <?php endif; ?>
        <header class="header-bar">
            <h2>Agenda</h2>
            <div style="display:flex;gap:.75rem;align-items:center;">
                <div style="display:flex;border:1px solid var(--color-border);border-radius:8px;overflow:hidden;font-size:.8rem;">
                    <a href="/agenda?view=calendar" style="padding:.4rem .8rem;<?php echo $viewMode === 'calendar' ? 'background:var(--color-barro);color:#fff;' : 'color:var(--color-text-muted);'; ?>">Calendario</a>
                    <a href="/agenda?view=list" style="padding:.4rem .8rem;<?php echo $viewMode === 'list' ? 'background:var(--color-barro);color:#fff;' : 'color:var(--color-text-muted);'; ?>">Lista</a>
                </div>
                <div class="tenant-badge"><?php echo htmlspecialchars($_SESSION['tenant_name'] ?? 'Negocio'); ?></div>
            </div>
        </header>

        <div style="flex:1;overflow-y:auto;padding:1.5rem 1rem;">
            <?php if (!empty($flash)): ?>
                <div class="alert" style="background:rgba(30,122,77,.1);color:var(--color-verde);border:1px solid rgba(30,122,77,.2);"><?php echo htmlspecialchars($flash); ?></div>
            <?php endif; ?>

            <?php if ($viewMode === 'calendar'): ?>
                <!-- Navegación de mes -->
                <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1rem;">
                    <a href="/agenda?view=calendar&month=<?php echo $prevMonth; ?>" class="btn btn-outline" style="padding:.4rem .8rem;">&larr;</a>
                    <h3 style="margin:0;"><?php echo $monthLabel[$firstDay->format('m')] . ' ' . $firstDay->format('Y'); ?></h3>
                    <a href="/agenda?view=calendar&month=<?php echo $nextMonth; ?>" class="btn btn-outline" style="padding:.4rem .8rem;">&rarr;</a>
                </div>

                <!-- Calendario: scrollable horizontalmente en mobile -->
                <div style="overflow-x:auto;-webkit-overflow-scrolling:touch;margin:0 -1rem;padding:0 1rem;">
                    <div style="min-width:480px;">
                        <!-- Encabezados de día -->
                        <div style="display:grid;grid-template-columns:repeat(7,1fr);gap:4px;margin-bottom:4px;">
                            <?php foreach (['Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb', 'Dom'] as $wd): ?>
                                <div style="text-align:center;font-size:.75rem;font-weight:600;color:var(--color-text-muted);padding:.25rem;"><?php echo $wd; ?></div>
                            <?php endforeach; ?>
                        </div>

                        <!-- Grilla -->
                        <div style="display:grid;grid-template-columns:repeat(7,1fr);gap:4px;">
                            <?php for ($i = 1; $i < $startWeekday; $i++): ?>
                                <div style="background:rgba(0,0,0,.015);border-radius:8px;min-height:80px;"></div>
                            <?php endfor; ?>
                            <?php for ($day = 1; $day <= $daysInMonth; $day++): ?>
                                <?php
                                $dateStr = $firstDay->format('Y-m') . '-' . str_pad($day, 2, '0', STR_PAD_LEFT);
                                $isToday = $dateStr === $todayStr;
                                $dayAppts = $byDay[$dateStr] ?? [];
                                usort($dayAppts, fn($a, $b) => strcmp($a['scheduled_at'], $b['scheduled_at']));
                                ?>
                                <div style="background:#fff;border:1px solid <?php echo $isToday ? 'var(--color-barro)' : 'var(--color-border)'; ?>;border-radius:8px;min-height:80px;padding:.35rem;">
                                    <div style="font-size:.75rem;font-weight:700;<?php echo $isToday ? 'color:var(--color-barro);' : ''; ?>margin-bottom:.2rem;"><?php echo $day; ?></div>
                                    <?php foreach ($dayAppts as $a): ?>
                                        <?php $c = $statusColors[$a['status']] ?? $statusColors['booked']; ?>
                                        <div title="<?php echo htmlspecialchars(($a['contact_name'] ?: $a['contact_phone']) . ' · ' . ($a['service_name'] ?? '')); ?>"
                                             style="background:<?php echo $c['bg']; ?>;color:<?php echo $c['fg']; ?>;border-radius:4px;padding:.1rem .25rem;font-size:.65rem;margin-bottom:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;<?php echo $a['status'] === 'canceled' ? 'text-decoration:line-through;' : ''; ?>">
                                            <?php echo htmlspecialchars(date('H:i', strtotime($a['scheduled_at'])) . ' ' . ($a['contact_name'] ?: 'Cliente')); ?>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endfor; ?>
                        </div>
                    </div>
                </div>
                <p style="color:var(--color-text-muted);font-size:.75rem;margin-top:1rem;">Para confirmar, cancelar o eliminar una cita, usá la vista <a href="/agenda?view=list">Lista</a>.</p>

            <?php else: ?>
                <!-- Vista lista (con acciones) -->
                <?php if (empty($appointments)): ?>
                    <div class="chat-empty" style="height:60vh;">
                        <svg style="width:56px;height:56px;color:var(--color-border);margin-bottom:1.25rem;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                        <h3>No hay citas todavía</h3>
                        <p>Cuando Vale agende una cita por WhatsApp o web, aparecerá acá.</p>
                    </div>
                <?php else: ?>
                    <!-- Tabla: scrollable en mobile -->
                    <div style="overflow-x:auto;-webkit-overflow-scrolling:touch;margin:0 -1rem;padding:0 1rem;">
                        <table style="width:100%;min-width:560px;border-collapse:collapse;background:#FFF;border-radius:12px;overflow:hidden;box-shadow:var(--shadow-soft);">
                            <thead>
                                <tr style="background:var(--color-tierra);color:#FFF;text-align:left;">
                                    <th style="padding:.75rem .9rem;white-space:nowrap;">Fecha y hora</th>
                                    <th style="padding:.75rem .9rem;">Cliente</th>
                                    <th style="padding:.75rem .9rem;">Servicio</th>
                                    <th style="padding:.75rem .9rem;">Estado</th>
                                    <th style="padding:.75rem .9rem;">Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($appointments as $appt): ?>
                                    <tr style="border-top:1px solid var(--color-border);">
                                        <td style="padding:.75rem .9rem;font-weight:600;white-space:nowrap;"><?php echo htmlspecialchars(date('d/m/Y H:i', strtotime($appt['scheduled_at']))); ?></td>
                                        <td style="padding:.75rem .9rem;white-space:nowrap;"><?php echo htmlspecialchars($appt['contact_name'] ?: $appt['contact_phone'] ?: 'Cliente'); ?></td>
                                        <td style="padding:.75rem .9rem;max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?php echo htmlspecialchars($appt['service_name'] ?? '—'); ?></td>
                                        <td style="padding:.75rem .9rem;">
                                            <span class="badge badge-<?php echo $appt['status'] === 'canceled' ? 'closed' : 'booked'; ?>"><?php echo htmlspecialchars($statusLabels[$appt['status']] ?? $appt['status']); ?></span>
                                        </td>
                                        <td style="padding:.75rem .9rem;">
                                            <div style="display:flex;gap:.3rem;flex-wrap:nowrap;">
                                                <?php
                                                $aid = (int) $appt['id'];
                                                $btn = function (string $action, string $label, string $bg, string $fg, bool $confirm = false) use ($aid) {
                                                    $onsubmit = $confirm ? " onsubmit=\"return confirm('¿Seguro?');\"" : '';
                                                    echo '<form method="POST" action="/agenda" style="display:inline;"' . $onsubmit . '>'
                                                        . '<input type="hidden" name="action" value="' . $action . '">'
                                                        . '<input type="hidden" name="appointment_id" value="' . $aid . '">'
                                                        . '<button type="submit" style="padding:.22rem .5rem;font-size:.72rem;border:none;border-radius:5px;cursor:pointer;white-space:nowrap;background:' . $bg . ';color:' . $fg . ';">' . $label . '</button>'
                                                        . '</form>';
                                                };
                                                if ($appt['status'] === 'booked') {
                                                    $btn('confirm', 'Confirmar', 'rgba(30,122,77,.12)', '#1E7A4D');
                                                }
                                                if (in_array($appt['status'], ['booked', 'confirmed'], true)) {
                                                    $btn('complete', 'Completar', 'rgba(224,163,62,.18)', '#9a6a14');
                                                    $btn('cancel', 'Cancelar', 'rgba(34,28,24,.06)', '#555');
                                                }
                                                $btn('delete', 'Eliminar', 'rgba(192,57,43,.1)', '#C0392B', true);
                                                ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </main>
</div>
<?php
$content = ob_get_clean();
require dirname(__DIR__) . '/views/layout.php';
