<?php
require_once __DIR__ . '/../../config/bootstrap.php';
require_once __DIR__ . '/../../includes/require-auth.php';

use App\Services\AuthService;
use App\Services\ContractService;
use App\Services\SecurityService;

$auth = new AuthService();
$contractService = new ContractService();
$security = new SecurityService();

// Obtener usuario autenticado (redirige al login si no hay sesión)
$user = requireAuth($auth);
$adminId = $user['id'];
$rol = $user['rol'] ?? 'asesor';
$esAdmin = ($rol === 'administrador');

// Obtener estadísticas
$stats = $contractService->getStats($adminId, $rol);

// Filtros
$filters = [
    'search' => $_GET['search'] ?? '',
    'estado' => $_GET['estado'] ?? '',
    'limit' => 10
];

// Obtener contratos
$contratos = $contractService->listByAdmin($adminId, $filters, $rol);

// Generar CSRF token
$csrfToken = $security->generateCSRFToken();
?>
<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Sistema de Contratos</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        * {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", "Helvetica Neue", Arial, sans-serif;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            letter-spacing: -0.011em;
        }
    </style>
</head>

<body class="bg-gray-50 flex flex-col min-h-screen">
    <?php include __DIR__ . '/../../includes/admin-nav.php'; ?>


    <!-- Main Content -->
    <main class="flex-1 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 w-full">
        <!-- Header -->
        <div class="mb-8">
            <h1 class="text-3xl font-bold text-gray-900">Dashboard</h1>
            <p class="mt-1 text-sm text-gray-600">Gestiona tus contratos digitales</p>
        </div>

        <!-- Stats -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <!-- Total Contratos -->
            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="flex-shrink-0 bg-indigo-500 rounded-lg p-3">
                        <svg class="h-6 w-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                        </svg>
                    </div>
                    <div class="ml-5 w-0 flex-1">
                        <dl>
                            <dt class="text-sm font-medium text-gray-500 truncate">Total Contratos</dt>
                            <dd class="text-2xl font-bold text-gray-900"><?= number_format($stats['total']) ?></dd>
                        </dl>
                    </div>
                </div>
            </div>

            <!-- Firmados -->
            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="flex-shrink-0 bg-green-500 rounded-lg p-3">
                        <svg class="h-6 w-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                    <div class="ml-5 w-0 flex-1">
                        <dl>
                            <dt class="text-sm font-medium text-gray-500 truncate">Firmados</dt>
                            <dd class="text-2xl font-bold text-gray-900"><?= number_format($stats['firmados']) ?></dd>
                        </dl>
                    </div>
                </div>
            </div>

            <!-- Pendientes -->
            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="flex-shrink-0 bg-yellow-500 rounded-lg p-3">
                        <svg class="h-6 w-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                    <div class="ml-5 w-0 flex-1">
                        <dl>
                            <dt class="text-sm font-medium text-gray-500 truncate">Pendientes</dt>
                            <dd class="text-2xl font-bold text-gray-900"><?= number_format($stats['pendientes']) ?></dd>
                        </dl>
                    </div>
                </div>
            </div>

            <!-- Expirados -->
            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="flex-shrink-0 bg-red-500 rounded-lg p-3">
                        <svg class="h-6 w-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                    </div>
                    <div class="ml-5 w-0 flex-1">
                        <dl>
                            <dt class="text-sm font-medium text-gray-500 truncate">Expirados</dt>
                            <dd class="text-2xl font-bold text-gray-900"><?= number_format($stats['expirados']) ?></dd>
                        </dl>
                    </div>
                </div>
            </div>
        </div>

        <!-- Actions & Filters -->
        <div class="bg-white rounded-lg shadow mb-6">
            <div class="p-6">
                <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <!-- Búsqueda -->
                    <form method="GET" action="" class="flex-1 max-w-lg">
                        <div class="relative">
                            <input
                                type="text"
                                name="search"
                                placeholder="Buscar por cliente, email o título..."
                                value="<?= htmlspecialchars($filters['search']) ?>"
                                class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent">
                            <svg class="absolute left-3 top-2.5 h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                            </svg>
                        </div>
                    </form>

                    <!-- Filtro Estado -->
                    <form method="GET" action="" class="flex items-center gap-3">
                        <?php if (!empty($filters['search'])): ?>
                            <input type="hidden" name="search" value="<?= htmlspecialchars($filters['search']) ?>">
                        <?php endif; ?>

                        <select
                            name="estado"
                            onchange="this.form.submit()"
                            class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent">
                            <option value="">Todos los estados</option>
                            <option value="pendiente" <?= $filters['estado'] === 'pendiente' ? 'selected' : '' ?>>Pendientes</option>
                            <option value="firmado" <?= $filters['estado'] === 'firmado' ? 'selected' : '' ?>>Firmados</option>
                            <option value="expirado" <?= $filters['estado'] === 'expirado' ? 'selected' : '' ?>>Expirados</option>
                            <option value="cancelado" <?= $filters['estado'] === 'cancelado' ? 'selected' : '' ?>>Cancelados</option>
                        </select>
                    </form>

                    <!-- Botón Nuevo Contrato -->
                    <a
                        href="<?= base_url('admin/crear-contrato') ?>"
                        class="inline-flex items-center px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 font-medium transition whitespace-nowrap">
                        <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                        </svg>
                        Nuevo Contrato
                    </a>
                </div>
            </div>
        </div>

        <!-- Tabla de Contratos -->
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Contrato
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Cliente
                        </th>
                        <?php if ($esAdmin): ?>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Asesor
                        </th>
                        <?php endif; ?>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Estado
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Fecha
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Expira
                        </th>
                        <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Acciones
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($contratos)): ?>
                        <tr>
                            <td colspan="<?= $esAdmin ? 7 : 6 ?>" class="px-6 py-12 text-center text-gray-500">
                                <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                                </svg>
                                <p class="mt-4 text-sm">No hay contratos que mostrar</p>
                                <a href="<?= base_url('admin/crear-contrato') ?>" class="mt-2 inline-block text-indigo-600 hover:text-indigo-700 text-sm font-medium">
                                    Crear tu primer contrato
                                </a>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($contratos as $contrato): ?>
                            <tr class="hover:bg-gray-50">
                                <td class="px-6 py-4">
                                    <div class="text-sm font-medium text-gray-900">
                                        <?= htmlspecialchars($contrato['titulo']) ?>
                                    </div>
                                    <div class="text-xs text-gray-500">#<?= str_pad($contrato['id'], 6, '0', STR_PAD_LEFT) ?></div>
                                </td>
                                <td class="px-6 py-4">
                                    <?php if ($contrato['estado'] === 'firmado' && !empty($contrato['firmante_nombre'])): ?>
                                        <div class="text-sm font-medium text-gray-900"><?= htmlspecialchars($contrato['firmante_nombre']) ?></div>
                                        <div class="text-xs text-gray-500">
                                            <?= htmlspecialchars($contrato['firmante_tipo_doc'] ?? '') ?>
                                            <?= htmlspecialchars($contrato['firmante_numero_doc'] ?? '') ?>
                                        </div>
                                        <?php if (!empty($contrato['firmante_telefono'])): ?>
                                        <div class="text-xs text-indigo-600">+<?= htmlspecialchars($contrato['firmante_telefono']) ?></div>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <div class="text-sm text-gray-900"><?= htmlspecialchars($contrato['cliente_nombre']) ?></div>
                                        <div class="text-xs text-gray-500">
                                            <?= !empty($contrato['cliente_email']) ? htmlspecialchars($contrato['cliente_email']) : '<span class="italic text-gray-400">No proporcionado</span>' ?>
                                        </div>
                                    <?php endif; ?>
                                </td>
                                <?php if ($esAdmin): ?>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700"><?= htmlspecialchars($contrato['asesor_nombre'] ?? '-') ?></div>
                                </td>
                                <?php endif; ?>
                                <td class="px-6 py-4">
                                    <?php
                                    $badgeColors = [
                                        'firmado' => 'bg-green-100 text-green-800',
                                        'pendiente' => 'bg-yellow-100 text-yellow-800',
                                        'expirado' => 'bg-red-100 text-red-800',
                                        'cancelado' => 'bg-gray-100 text-gray-800'
                                    ];
                                    $color = $badgeColors[$contrato['estado']] ?? 'bg-gray-100 text-gray-800';
                                    ?>
                                    <span class="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full <?= $color ?>">
                                        <?= ucfirst($contrato['estado']) ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-500">
                                    <?php if ($contrato['estado'] === 'firmado' && !empty($contrato['firmado_at'])): ?>
                                        <span class="text-green-700 font-medium"><?= date('d/m/Y H:i', strtotime($contrato['firmado_at'])) ?></span>
                                        <div class="text-xs text-gray-400">firmado</div>
                                    <?php else: ?>
                                        <?= date('d/m/Y H:i', strtotime($contrato['created_at'])) ?>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-500">
                                    <?php
                                    $expira = strtotime($contrato['expira_at']);
                                    $ahora = time();
                                    $diff = $expira - $ahora;
                                    $horasRestantes = round($diff / 3600);

                                    if ($contrato['estado'] === 'firmado') {
                                        echo '-';
                                    } elseif ($diff < 0) {
                                        echo '<span class="text-red-600">Expirado</span>';
                                    } elseif ($horasRestantes < 24) {
                                        echo '<span class="text-orange-600">' . $horasRestantes . ' horas</span>';
                                    } else {
                                        echo date('d/m/Y H:i', $expira);
                                    }
                                    ?>
                                </td>
                                <td class="px-6 py-4 text-right text-sm font-medium">
                                    <a href="<?= base_url('admin/ver-contrato') ?>?id=<?= $contrato['id'] ?>" class="text-indigo-600 hover:text-indigo-900">
                                        Ver detalles
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </main>

    <?php include __DIR__ . '/../../includes/admin-footer.php'; ?>
</body>

</html>