<?php
require_once __DIR__ . '/../vendor/autoload.php';

use App\Controllers\AssignmentController;
use App\Middleware\RoleMiddleware;
use App\Services\AuthService;

RoleMiddleware::auth();
$auth = new AuthService();

// Instanciar controlador directamente (Page Controller pattern)
$controller = new AssignmentController();
$assignments = $controller->index();

// Si se envia formulario de generación (Admin o Coordinador)
if (isPost() && ($auth->isAdmin() || $auth->isCoordinador())) {
    $controller->generate();
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rotaciones - Contenedor Ibiza</title>
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <?php include 'partials/navbar.php'; ?>

    <div class="container">
        <div class="card-header">
            <h1 class="card-title">📅 Tabla de Rotación de Ayudantes</h1>
            <a href="export-pdf.php" target="_blank" class="btn btn-success">Descargar PDF</a>
        </div>

        <?php if ($msg = flash('success')): ?>
            <div class="alert alert-success"><?= e($msg) ?></div>
        <?php endif; ?>
        
        <?php if ($msg = flash('error')): ?>
            <div class="alert alert-error"><?= e($msg) ?></div>
        <?php endif; ?>

        <!-- Panel de Administración (Admin y Coordinador) -->
        <?php if ($auth->isAdmin() || $auth->isCoordinador()): ?>
            <div class="card" style="border: 1px solid #cbd5e1; background: #f8fafc;">
                <h3 class="card-title" style="font-size: 1rem; margin-bottom: 1rem;">⚙️ Panel de Generación</h3>
                <form method="POST" onsubmit="return confirm('¿Estás seguro de generar nuevas rotaciones?')">
                    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
                    <div style="display: flex; gap: 1rem; align-items: center;">
                        <select name="type" class="form-control" style="width: auto;">
                            <option value="extend">Extender (Agregar al final)</option>
                            <option value="regenerate">Regenerar (Borrar futuras y rehacer)</option>
                        </select>
                        <select name="weeks" class="form-control" style="width: auto;">
                            <option value="4">4 Semanas</option>
                            <option value="8" selected>8 Semanas</option>
                            <option value="12">12 Semanas</option>
                        </select>
                        <button type="submit" class="btn btn-primary">Generar Rotación</button>
                    </div>
                </form>
            </div>
        <?php endif; ?>

        <?php if ($auth->isCoordinador() || $auth->isAdmin()): ?>
            <div class="mb-4 text-center">
                <a href="coordinador/reorganizar.php" class="btn btn-secondary btn-block">
                    ↔️ Reorganizar Orden (Drag & Drop)
                </a>
            </div>
        <?php endif; ?>

        <div class="card">
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Semana</th>
                            <th>Periodo (Dom - Sáb)</th>
                            <th>Ayudante Asignado</th>
                            <th>Rol</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($assignments)): ?>
                            <tr>
                                <td colspan="4" class="text-center">No hay rotaciones generadas.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($assignments as $asg): ?>
                                <tr>
                                    <td>
                                        <span class="badge badge-warning">Sem <?= $asg['week_number'] ?></span>
                                    </td>
                                    <td>
                                        <?= formatDate($asg['start_date']) ?> - <?= formatDate($asg['end_date']) ?>
                                    </td>
                                    <td style="font-weight: 600;">
                                        <?= e($asg['full_name']) ?>
                                    </td>
                                    <td style="font-size: 0.85rem; color: #64748b;">
                                        <!-- Esto requeriría join con users para rol, ya viene en consulta -->
                                         (<?= e($asg['username']) ?>)
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>
