<?php
// Desk - Revisión de Documentos (Staff)
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

function isUserLoggedIn(){ return isset($_SESSION['user_id']); }
if (!isUserLoggedIn()) { header('Location: /modules/users/login.php'); exit; }

$db = Database::getInstance();
$pdo = $db->getConnection();

// Verificación de permiso: documents.review
if (!function_exists('userHasPermissionByName')) {
    function userHasPermissionByName(PDO $pdo, string $permName, int $userId): bool {
        if ($userId <= 0) return false;
        $stmt = $pdo->prepare("SELECT 1 FROM role_permissions rp INNER JOIN permissions p ON rp.permission_id = p.id INNER JOIN user_roles ur ON rp.role_id = ur.role_id WHERE ur.user_id = ? AND p.name = ? LIMIT 1");
        $stmt->execute([$userId, $permName]);
        return (bool)$stmt->fetchColumn();
    }
}
$current_user_id = (int)($_SESSION['user_id'] ?? 0);
if (!userHasPermissionByName($pdo, 'documents.review', $current_user_id)) {
    http_response_code(403);
    echo '<h2 style="padding:20px;">Permiso requerido: documents.review</h2>';
    exit;
}

$stmt = $pdo->query("SELECT d.id, d.client_id, d.type, d.original_name, d.filename, d.status, d.uploaded_at, c.first_name, c.last_name FROM client_documents d JOIN clients c ON c.id = d.client_id ORDER BY d.uploaded_at DESC LIMIT 100");
$docs = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Revisión de Documentos</title>
    <link rel="stylesheet" href="/test/simple_crm/public/style.css">
    <link rel="stylesheet" href="/test/simple_crm/public/dashboard.css">
</head>
<body>
    <div class="dashboard-container">
        <header class="dashboard-header">
            <div class="breadcrumbs">
                <a href="/modules/dashboard/index.php" class="breadcrumb">Panel</a>
                <span class="breadcrumb-sep">›</span>
                <span class="breadcrumb current">Revisión de Documentos</span>
            </div>
            <h1>Revisión de Documentos</h1>
        </header>
        <main class="dashboard-main">
            <section class="documents-section">
                <div class="documents-table-container">
                    <table class="documents-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Cliente</th>
                                <th>Tipo</th>
                                <th>Nombre</th>
                                <th>Estado</th>
                                <th>Fecha</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($docs): foreach ($docs as $d): ?>
                            <tr data-id="<?= (int)$d['id'] ?>">
                                <td><?= (int)$d['id'] ?></td>
                                <td><?= htmlspecialchars($d['first_name'].' '.$d['last_name']) ?> (#<?= (int)$d['client_id'] ?>)</td>
                                <td><?= htmlspecialchars($d['type']) ?></td>
                                <td><a href="<?= htmlspecialchars($d['filename']) ?>" target="_blank"><?= htmlspecialchars($d['original_name']) ?></a></td>
                                <td><?= htmlspecialchars($d['status'] ?? 'submitted') ?></td>
                                <td><?= htmlspecialchars(date('Y-m-d', strtotime($d['uploaded_at']))) ?></td>
                                <td>
                                    <button class="action-btn-small" onclick="updateDocStatus(<?= (int)$d['id'] ?>, 'approved')"><i class="fas fa-check"></i> Aprobar</button>
                                    <button class="action-btn-small" onclick="updateDocStatus(<?= (int)$d['id'] ?>, 'rejected')"><i class="fas fa-times"></i> Rechazar</button>
                                </td>
                            </tr>
                            <?php endforeach; else: ?>
                            <tr><td colspan="7">No hay documentos.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </section>
        </main>
    </div>

    <script>
    async function updateDocStatus(id, status){
        try {
            const res = await fetch('/modules/desks/update_document_status.php', {
                method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ id, status })
            });
            const data = await res.json();
            if (!data.success) throw new Error(data.error || 'Error actualizando estado');
            location.reload();
        } catch(e){ alert(e.message || 'Error'); }
    }
    </script>

    <script src="https://kit.fontawesome.com/a2e0a6ad53.js" crossorigin="anonymous"></script>
</body>
</html>