<?php
// D:\wamp64\www\shtaller-gk\turnos.php
session_start();
include 'includes/db.php';
include 'includes/header.php';

// Logic for Calendar View
$view = $_GET['view'] ?? 'list';
$week_offset = isset($_GET['week']) ? (int) $_GET['week'] : 0;

if ($view == 'calendar') {
    // Calculate start (Monday) and end (Friday) dates
    $today = new DateTime();

    // Adjust to Monday of the current week (if today is Sunday, 'monday this week' works)
    if ($week_offset !== 0) {
        $interval = ($week_offset > 0) ? "+$week_offset weeks" : "$week_offset weeks";
        $today->modify($interval);
    }

    // Ensure we get Monday
    // If today is Monday, 'monday this week' keeps it today.
    $start_week = clone $today;
    $start_week->modify('monday this week');

    $end_week = clone $start_week;
    $end_week->modify('saturday this week'); // Show until Saturday

    // Fetch turnos between start and end date (inclusive-ish)
    // IMPORTANT: db stores fecha_turno as datetime.
    $start_str = $start_week->format('Y-m-d 00:00:00');
    $end_str = $end_week->format('Y-m-d 23:59:59');

    $query = "SELECT * FROM turnos WHERE fecha_turno BETWEEN ? AND ? ORDER BY fecha_turno ASC";
    $stmt = $pdo->prepare($query);
    $stmt->execute([$start_str, $end_str]);
    $turnos_semana = $stmt->fetchAll();

    // Map turnos by Day (1-5) and Hour (0-23)
    $db_turnos = [];
    foreach ($turnos_semana as $t) {
        $ts = strtotime($t['fecha_turno']);
        $day_num = date('N', $ts); // 1 = Mon, 5 = Fri
        $hour = (int) date('H', $ts);

        if (!isset($db_turnos[$day_num]))
            $db_turnos[$day_num] = [];
        if (!isset($db_turnos[$day_num][$hour]))
            $db_turnos[$day_num][$hour] = [];

        $db_turnos[$day_num][$hour][] = $t;
    }

} else {
    // List View Logic
    $query = "SELECT * FROM turnos ORDER BY fecha_turno DESC";
    $turnos = $pdo->query($query)->fetchAll();
}
?>

<style>
    /* SOLUCIÓN RADICAL CAPA OSCURA */
    .modal {
        z-index: 2000 !important;
        background: rgba(0, 0, 0, 0.5);
    }

    .modal-backdrop {
        display: none !important;
    }

    .badge-patente {
        background: #333;
        color: #fff;
        font-family: monospace;
        padding: 4px 8px;
        border-radius: 4px;
    }

    .st-finalizado {
        background-color: #28a745 !important;
        color: white;
    }

    /* CALENDAR STYLES */
    .cal-table {
        table-layout: fixed;
        width: 100%;
        border-collapse: collapse;
    }

    .cal-header {
        color: white;
        text-align: center;
        font-weight: bold;
        text-transform: uppercase;
        padding: 10px;
        font-size: 0.9rem;
    }

    .cal-cell {
        border: 1px solid #000;
        height: 80px;
        vertical-align: top;
        padding: 5px;
        font-size: 0.85rem;
        background: #fff;
    }

    .cal-hour-col {
        width: 60px;
        text-align: center;
        vertical-align: middle;
        font-weight: bold;
        background: #f8f9fa;
        border: 1px solid #000;
    }

    .cal-turno-card {
        background: #e3f2fd;
        border-left: 3px solid #0d6efd;
        padding: 2px 4px;
        margin-bottom: 2px;
        font-size: 0.75rem;
        cursor: pointer;
    }

    .bg-lunes {
        background-color: #D98880;
    }

    .bg-martes {
        background-color: #45B39D;
    }

    .bg-miercoles {
        background-color: #F5CBA7;
    }

    .bg-jueves {
        background-color: #6C3483;
    }

    .bg-viernes {
        background-color: #5D6D7E;
    }

    .bg-sabado {
        background-color: #BA4A00;
    }
</style>

<div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="fw-bold"><i class="fas fa-calendar-alt me-2 text-primary"></i> Gestión de Turnos</h2>

        <div>
            <div class="btn-group me-2">
                <a href="turnos.php?view=list"
                    class="btn btn-outline-primary <?= ($view == 'list') ? 'active' : '' ?>"><i class="fas fa-list"></i>
                    Lista</a>
                <a href="turnos.php?view=calendar"
                    class="btn btn-outline-primary <?= ($view == 'calendar') ? 'active' : '' ?>"><i
                        class="fas fa-th"></i>
                    Calendario</a>
            </div>

            <button class="btn btn-primary shadow" data-bs-toggle="modal" data-bs-target="#modalTurno">
                <i class="fas fa-plus me-1"></i> NUEVO TURNO
            </button>
        </div>
    </div>

    <?php if ($view == 'calendar'): ?>
        <!-- VISTA CALENDARIO -->
        <div class="card shadow-sm border-0">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h4 class="mb-0">Calendario Semanal</h4>
                    <div class="d-flex align-items-center gap-3">
                        <a href="turnos.php?view=calendar&week=<?= $week_offset - 1 ?>"
                            class="btn btn-sm btn-outline-secondary"><i class="fas fa-chevron-left"></i> Anterior</a>
                        <span class="fw-bold fs-5">Semana del <?= $start_week->format('d/m') ?> al
                            <?= $end_week->format('d/m') ?></span>
                        <a href="turnos.php?view=calendar&week=<?= $week_offset + 1 ?>"
                            class="btn btn-sm btn-outline-secondary">Siguiente <i class="fas fa-chevron-right"></i></a>
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="cal-table">
                        <thead>
                            <tr>
                                <th class="cal-hour-col">HORA</th>
                                <th class="cal-header bg-lunes">LUNES <?= $start_week->format('d') ?></th>
                                <th class="cal-header bg-martes">MARTES
                                    <?= (clone $start_week)->modify('+1 day')->format('d') ?>
                                </th>
                                <th class="cal-header bg-miercoles">MIÉRCOLES
                                    <?= (clone $start_week)->modify('+2 days')->format('d') ?>
                                </th>
                                <th class="cal-header bg-jueves">JUEVES
                                    <?= (clone $start_week)->modify('+3 days')->format('d') ?>
                                </th>
                                <th class="cal-header bg-viernes">VIERNES
                                    <?= (clone $start_week)->modify('+4 days')->format('d') ?>
                                </th>
                                <th class="cal-header bg-sabado">SABADO
                                    <?= (clone $start_week)->modify('+4 days')->format('d') ?>
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php for ($h = 8; $h <= 19; $h++): ?>
                                <tr>
                                    <td class="cal-hour-col"><?= $h ?>:00</td>
                                    <?php for ($d = 1; $d <= 6; $d++): ?>
                                        <td class="cal-cell">
                                            <?php
                                            if (isset($db_turnos[$d][$h])) {
                                                foreach ($db_turnos[$d][$h] as $t_item) {
                                                    echo "<div class='cal-turno-card' onclick='editarTurno({$t_item['id']})'>";
                                                    echo "<strong>" . htmlspecialchars($t_item['nombres_apellido'] ?? 'S/N') . "</strong><br>";
                                                    echo "<small>" . htmlspecialchars($t_item['vehiculo_modelo'] ?? '') . "</small>";
                                                    echo "</div>";
                                                }
                                            }
                                            ?>
                                        </td>
                                    <?php endfor; ?>
                                </tr>
                            <?php endfor; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    <?php else: ?>
        <!-- VISTA LISTA (ORIGINAL) -->
        <div class="card shadow-sm border-0">
            <div class="card-body p-0">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th class="ps-4">Cliente</th>
                            <th>Vehículo</th>
                            <th>Patente</th>
                            <th>Fecha/Hora</th>
                            <th class="text-center">Estado</th>
                            <th class="text-center">Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($turnos as $t): ?>
                            <tr>
                                <td class="ps-4 fw-bold"><?= htmlspecialchars($t['nombres_apellido'] ?? 'S/N') ?></td>
                                <td><?= htmlspecialchars($t['vehiculo_modelo'] ?? '---') ?></td>
                                <td><span class="badge-patente"><?= htmlspecialchars($t['patente'] ?? '-------') ?></span></td>
                                <td><?= date('d/m/Y H:i', strtotime($t['fecha_turno'])) ?> hs</td>
                                <td class="text-center">
                                    <span
                                        class="badge <?= ($t['estado'] == 'Finalizado') ? 'st-finalizado' : 'bg-info text-dark' ?>">
                                        <?= $t['estado'] ?>
                                    </span>
                                </td>
                                <td class="text-center">
                                    <button class="btn btn-warning btn-sm me-1" onclick="editarTurno(<?= $t['id'] ?>)">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <a href="borrar_turno.php?id=<?= $t['id'] ?>" class="btn btn-danger btn-sm"
                                        onclick="return confirm('¿Eliminar?');">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php endif; ?>
</div>

<!-- Modal Turno movido a includes/modals_globales.php -->

<!-- Modal Editar Turno movido a includes/modals_globales.php -->

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    // FUNCIÓN GLOBAL para evitar "is not defined"
    function editarTurno(id) {
        $.getJSON('get_turno_info.php', { id: id }, function (data) {
            if (!data.error) {
                $('#edit_id').val(data.id);
                $('#edit_nombres_apellido').val(data.nombres_apellido);
                $('#edit_vehiculo').val(data.vehiculo_modelo);
                $('#edit_patente').val(data.patente);
                if (data.fecha_turno) $('#edit_fecha').val(data.fecha_turno.replace(" ", "T").substring(0, 16));
                $('#edit_estado').val(data.estado);

                // Updated ID to modalEditarTurno to avoid conflict
                var myModal = new bootstrap.Modal(document.getElementById('modalEditarTurno'));
                myModal.show();
            }
        });
    }

    $(document).ready(function () {
        $('#cliente_select').on('change', function () {
            var id = $(this).val();
            $('#hidden_nombre').val($("#cliente_select option:selected").text());
            if (id) {
                $.getJSON('includes/get_cliente.php', { id: id }, function (data) {
                    if (!data.error) {
                        $('#t_vehiculo').val(data.vehiculo_modelo || '');
                        $('#t_patente').val(data.patente || '');
                    }
                });
            }
        });
    });
</script>

<?php include 'includes/footer.php'; ?>