<?php
include 'conexion3.php';

// Eliminar
if (isset($_GET['eliminar'])) {
    $id = $_GET['eliminar'];
    $stmt = $pdo->prepare("DELETE FROM turnos WHERE id = ?");
    $stmt->execute([$id]);
    
    // Redirigir para evitar reenvío del formulario
    header("Location: turnos.php");
    exit();
}

// Leer
$stmt = $pdo->query("SELECT * FROM turnos ORDER BY nombre");
$turnos = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestión de Turnos</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css">
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2c3e50;
            --success-color: #27ae60;
            --warning-color: #f39c12;
            --danger-color: #e74c3c;
            --light-color: #f8f9fa;
            --dark-color: #343a40;
        }
        
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .header-section {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            padding: 25px 0;
            border-radius: 0 0 20px 20px;
            margin-bottom: 30px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
        }
        
        .header-title {
            font-weight: 700;
            margin-bottom: 5px;
            font-size: 2.2rem;
        }
        
        .header-subtitle {
            opacity: 0.9;
            font-size: 1rem;
        }
        
        .main-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 20px;
        }
        
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            margin-bottom: 30px;
            overflow: hidden;
        }
        
        .card-header {
            background-color: white;
            border-bottom: 2px solid #f0f0f0;
            padding: 20px 25px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .card-title {
            margin: 0;
            color: var(--secondary-color);
            font-weight: 600;
            font-size: 1.5rem;
            display: flex;
            align-items: center;
        }
        
        .card-title i {
            margin-right: 10px;
            color: var(--primary-color);
        }
        
        .action-buttons {
            display: flex;
            gap: 10px;
        }
        
        .btn {
            border-radius: 8px;
            font-weight: 600;
            padding: 10px 20px;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        
        .btn i {
            margin-right: 8px;
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .btn-primary:hover {
            background-color: #2980b9;
            border-color: #2980b9;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
        }
        
        .btn-secondary {
            background-color: #6c757d;
            border-color: #6c757d;
        }
        
        .btn-secondary:hover {
            background-color: #5a6268;
            border-color: #5a6268;
            transform: translateY(-2px);
        }
        
        .btn-warning {
            background-color: var(--warning-color);
            border-color: var(--warning-color);
        }
        
        .btn-danger {
            background-color: var(--danger-color);
            border-color: var(--danger-color);
        }
        
        .btn-sm {
            padding: 6px 12px;
            font-size: 0.875rem;
        }
        
        .table-container {
            padding: 0;
            overflow-x: auto;
        }
        
        .table {
            margin: 0;
            border-collapse: separate;
            border-spacing: 0;
        }
        
        .table thead th {
            background-color: var(--secondary-color);
            color: white;
            border: none;
            padding: 16px 12px;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.85rem;
            letter-spacing: 0.5px;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        
        .table tbody tr {
            transition: all 0.3s;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .table tbody tr:hover {
            background-color: rgba(52, 152, 219, 0.05);
            transform: translateY(-1px);
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
        }
        
        .table tbody td {
            padding: 14px 12px;
            vertical-align: middle;
            border: none;
        }
        
        .badge-day {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            min-width: 80px;
            text-align: center;
        }
        
        .badge-active {
            background-color: rgba(39, 174, 96, 0.15);
            color: var(--success-color);
            border: 1px solid rgba(39, 174, 96, 0.3);
        }
        
        .badge-inactive {
            background-color: rgba(236, 240, 241, 0.8);
            color: #7f8c8d;
            border: 1px solid #e0e0e0;
        }
        
        .time-badge {
            background-color: #e8f4fc;
            color: var(--primary-color);
            padding: 6px 12px;
            border-radius: 6px;
            font-weight: 600;
            font-size: 0.9rem;
            border: 1px solid rgba(52, 152, 219, 0.2);
        }
        
        .actions-cell {
            white-space: nowrap;
            text-align: center;
        }
        
        .no-data {
            text-align: center;
            padding: 50px 20px;
            color: #7f8c8d;
        }
        
        .no-data i {
            font-size: 4rem;
            margin-bottom: 20px;
            color: #bdc3c7;
        }
        
        .no-data h4 {
            color: #95a5a6;
            margin-bottom: 10px;
        }
        
        .stats-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
            border-left: 4px solid var(--primary-color);
        }
        
        .stats-number {
            font-size: 2.5rem;
            font-weight: 700;
            color: var(--secondary-color);
            line-height: 1;
        }
        
        .stats-label {
            color: #7f8c8d;
            font-size: 0.9rem;
            margin-top: 5px;
        }
        
        @media (max-width: 768px) {
            .header-title {
                font-size: 1.8rem;
            }
            
            .card-header {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .action-buttons {
                margin-top: 15px;
                width: 100%;
            }
            
            .btn {
                width: 100%;
                margin-bottom: 10px;
            }
            
            .table thead {
                display: none;
            }
            
            .table, .table tbody, .table tr, .table td {
                display: block;
                width: 100%;
            }
            
            .table tr {
                margin-bottom: 20px;
                border: 1px solid #e0e0e0;
                border-radius: 10px;
                padding: 15px;
            }
            
            .table td {
                text-align: right;
                padding-left: 50%;
                position: relative;
                border-bottom: 1px solid #f0f0f0;
            }
            
            .table td:before {
                content: attr(data-label);
                position: absolute;
                left: 15px;
                width: calc(50% - 30px);
                padding-right: 15px;
                text-align: left;
                font-weight: 600;
                color: var(--secondary-color);
            }
            
            .table td:last-child {
                border-bottom: 0;
            }
            
            .actions-cell {
                text-align: center;
                padding-top: 15px;
            }
            
            .actions-cell:before {
                display: none;
            }
        }
    </style>
</head>
<body>
    <!-- Header Section -->
    <div class="header-section">
        <div class="main-container">
            <h1 class="header-title"><i class="fas fa-calendar-alt"></i> Gestión de Turnos</h1>
            <p class="header-subtitle">Administre y consulte todos los horarios disponibles en el sistema</p>
        </div>
    </div>
    
    <div class="main-container">
        <!-- Stats Cards -->
        <div class="row">
            <div class="col-md-3 col-sm-6">
                <div class="stats-card">
                    <div class="stats-number"><?php echo count($turnos); ?></div>
                    <div class="stats-label">Total de Turnos</div>
                </div>
            </div>
            <div class="col-md-3 col-sm-6">
                <div class="stats-card">
                    <div class="stats-number">
                        <?php 
                        $activos = 0;
                        foreach ($turnos as $turno) {
                            // Contar turnos que tengan al menos un día de trabajo
                            // (lunes_libre = 0 significa que trabaja ese día)
                            if (($turno['lunes_libre'] ?? '1') == '0' || 
                                ($turno['martes_libre'] ?? '1') == '0' ||
                                ($turno['miercoles_libre'] ?? '1') == '0' ||
                                ($turno['jueves_libre'] ?? '1') == '0' ||
                                ($turno['viernes_libre'] ?? '1') == '0' ||
                                ($turno['sabado_libre'] ?? '1') == '0' ||
                                ($turno['domingo_libre'] ?? '1') == '0') {
                                $activos++;
                            }
                        }
                        echo $activos;
                        ?>
                    </div>
                    <div class="stats-label">Turnos con Días Laborales</div>
                </div>
            </div>
            <div class="col-md-6 col-sm-12">
                <div class="stats-card">
                    <h6><i class="fas fa-info-circle"></i> Información</h6>
                    <p class="mb-0" style="font-size: 0.9rem;">
                        Los turnos definen los horarios laborales disponibles. Puede crear, editar o eliminar turnos según sus necesidades.
                    </p>
                </div>
            </div>
        </div>
        
        <!-- Main Card -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title"><i class="fas fa-list"></i> Lista de Turnos Registrados</h3>
                <div class="action-buttons">
                    <a href="crear_turno.php" class="btn btn-primary">
                        <i class="fas fa-plus-circle"></i> Nuevo Turno
                    </a>
                    <a href="index.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Regresar
                    </a>
                </div>
            </div>
            
            <div class="table-container">
                <?php if (count($turnos) > 0): ?>
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Nombre</th>
                                <th>Lunes</th>
                                <th>Martes</th>
                                <th>Miércoles</th>
                                <th>Jueves</th>
                                <th>Viernes</th>
                                <th>Sábado</th>
                                <th>Domingo</th>
                                <th>Horario</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($turnos as $turno): ?>
                                <tr>
                                    <td data-label="ID">
                                        <span class="badge-day badge-inactive">#<?php echo $turno['id']; ?></span>
                                    </td>
                                    <td data-label="Nombre">
                                        <strong><?php echo htmlspecialchars($turno['nombre']); ?></strong>
                                    </td>
                                    
                                    <!-- Días de la semana -->
                                    <!-- lunes_libre = 1 significa libre, 0 significa trabaja -->
                                    <td data-label="Lunes">
                                        <?php 
                                        $lunesLibre = $turno['lunes_libre'] ?? '1';
                                        if ($lunesLibre == '0' || $lunesLibre == 0): ?>
                                            <span class="badge-day badge-active">Trabaja</span>
                                        <?php else: ?>
                                            <span class="badge-day badge-inactive">Libre</span>
                                        <?php endif; ?>
                                    </td>
                                    
                                    <td data-label="Martes">
                                        <?php 
                                        $martesLibre = $turno['martes_libre'] ?? '1';
                                        if ($martesLibre == '0' || $martesLibre == 0): ?>
                                            <span class="badge-day badge-active">Trabaja</span>
                                        <?php else: ?>
                                            <span class="badge-day badge-inactive">Libre</span>
                                        <?php endif; ?>
                                    </td>
                                    
                                    <td data-label="Miércoles">
                                        <?php 
                                        $miercolesLibre = $turno['miercoles_libre'] ?? '1';
                                        if ($miercolesLibre == '0' || $miercolesLibre == 0): ?>
                                            <span class="badge-day badge-active">Trabaja</span>
                                        <?php else: ?>
                                            <span class="badge-day badge-inactive">Libre</span>
                                        <?php endif; ?>
                                    </td>
                                    
                                    <td data-label="Jueves">
                                        <?php 
                                        $juevesLibre = $turno['jueves_libre'] ?? '1';
                                        if ($juevesLibre == '0' || $juevesLibre == 0): ?>
                                            <span class="badge-day badge-active">Trabaja</span>
                                        <?php else: ?>
                                            <span class="badge-day badge-inactive">Libre</span>
                                        <?php endif; ?>
                                    </td>
                                    
                                    <td data-label="Viernes">
                                        <?php 
                                        $viernesLibre = $turno['viernes_libre'] ?? '1';
                                        if ($viernesLibre == '0' || $viernesLibre == 0): ?>
                                            <span class="badge-day badge-active">Trabaja</span>
                                        <?php else: ?>
                                            <span class="badge-day badge-inactive">Libre</span>
                                        <?php endif; ?>
                                    </td>
                                    
                                    <td data-label="Sábado">
                                        <?php 
                                        $sabadoLibre = $turno['sabado_libre'] ?? '1';
                                        if ($sabadoLibre == '0' || $sabadoLibre == 0): ?>
                                            <span class="badge-day badge-active">Trabaja</span>
                                        <?php else: ?>
                                            <span class="badge-day badge-inactive">Libre</span>
                                        <?php endif; ?>
                                    </td>
                                    
                                    <td data-label="Domingo">
                                        <?php 
                                        $domingoLibre = $turno['domingo_libre'] ?? '1';
                                        if ($domingoLibre == '0' || $domingoLibre == 0): ?>
                                            <span class="badge-day badge-active">Trabaja</span>
                                        <?php else: ?>
                                            <span class="badge-day badge-inactive">Libre</span>
                                        <?php endif; ?>
                                    </td>
                                    
                                    <td data-label="Horario">
                                        <div class="d-flex flex-column">
                                            <span class="time-badge mb-1">
                                                <i class="far fa-clock"></i> <?php echo substr($turno['hora_inicio'], 0, 5); ?>
                                            </span>
                                            <span class="time-badge">
                                                <i class="fas fa-clock"></i> <?php echo substr($turno['hora_fin'], 0, 5); ?>
                                            </span>
                                        </div>
                                    </td>
                                    
                                    <td data-label="Acciones" class="actions-cell">
                                        <div class="btn-group" role="group">
                                            <a href="crear_turno.php?editar=<?php echo $turno['id']; ?>" 
                                               class="btn btn-warning btn-sm" 
                                               title="Editar turno">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <a href="?eliminar=<?php echo $turno['id']; ?>" 
                                               class="btn btn-danger btn-sm" 
                                               onclick="return confirmarEliminacion(<?php echo $turno['id']; ?>, '<?php echo htmlspecialchars($turno['nombre'], ENT_QUOTES); ?>');"
                                               title="Eliminar turno">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <div class="no-data">
                        <i class="far fa-calendar-times"></i>
                        <h4>No hay turnos registrados</h4>
                        <p>Comience creando su primer turno haciendo clic en el botón "Nuevo Turno"</p>
                        <a href="crear_turno.php" class="btn btn-primary mt-3">
                            <i class="fas fa-plus-circle"></i> Crear Primer Turno
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Footer Info -->
        <div class="row mt-4">
            <div class="col-md-12">
                <div class="alert alert-info" style="border-radius: 10px;">
                    <div class="d-flex align-items-center">
                        <i class="fas fa-lightbulb fa-2x mr-3"></i>
                        <div>
                            <h5 class="alert-heading mb-2">Consejo</h5>
                            <p class="mb-0">
                                Puede asignar estos turnos a empleados o departamentos desde la sección correspondiente.
                                Asegúrese de que los horarios no se solapen para evitar conflictos.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
    <script>
        // Inicializar DataTable
        $(document).ready(function() {
            $('.table').DataTable({
                "language": {
                    "lengthMenu": "Mostrar _MENU_ turnos por página",
                    "zeroRecords": "No se encontraron turnos",
                    "info": "Mostrando página _PAGE_ de _PAGES_",
                    "infoEmpty": "No hay turnos disponibles",
                    "infoFiltered": "(filtrado de _MAX_ turnos totales)",
                    "search": "Buscar:",
                    "paginate": {
                        "first": "Primera",
                        "last": "Última",
                        "next": "Siguiente",
                        "previous": "Anterior"
                    }
                },
                "pageLength": 10,
                "order": [[0, "asc"]]
            });
        });
        
        // Función para confirmar eliminación
        function confirmarEliminacion(id, nombre) {
            return confirm(`¿Está seguro de eliminar el turno "${nombre}" (ID: ${id})?\n\nEsta acción no se puede deshacer.`);
        }
        
        // Hacer la tabla responsive en dispositivos móviles
        function adaptarTablaResponsive() {
            if (window.innerWidth <= 768) {
                $('table tbody tr').each(function() {
                    var $tr = $(this);
                    $tr.find('td').each(function(index) {
                        var headerText = $('table thead th').eq(index).text();
                        $(this).attr('data-label', headerText);
                    });
                });
            }
        }
        
        // Ejecutar al cargar y al redimensionar
        $(window).on('load resize', adaptarTablaResponsive);
        $(document).ready(adaptarTablaResponsive);
    </script>
</body>
</html>