<?php
// gabinete/src/views/employees/documentos.php

require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../helpers/AuthHelper.php';

// Se quiser forçar login, troque para: AuthHelper::requireLogin();
AuthHelper::check();

// Fallback: carregar colaboradores direto do banco se a página for acessada sem passar pelo controller
$employees = $employees ?? null;
if ($employees === null || !is_array($employees) || count($employees) === 0) {
  try {
    // Usa a conexão global $pdo definida em src/config/db.php
    require_once __DIR__ . '/../../config/db.php';

    if (isset($pdo)) {
      $stmt = $pdo->prepare("SELECT id, full_name FROM employees ORDER BY full_name");
      $stmt->execute();
      $employees = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
  } catch (Throwable $e) {
    $employees = [];
  }
}

$pageTitle = "Documentos";
$nome = $_SESSION['nome'] ?? 'Usuário';
?>
<!DOCTYPE html>
<html lang="pt-br">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= htmlspecialchars($pageTitle) ?></title>

  <!-- Bootstrap 5 + Icons -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">

  <style>
    body {
      background: #f5f7fb;
    }

    .page-hero {
      /* Cor padrão do sistema - Ajuste conforme necessário */
      background: linear-gradient(135deg, #0B1F3A, #102B54);
      color: #fff;
      border-bottom-left-radius: 24px;
      border-bottom-right-radius: 24px;
    }

    .page-hero .title {
      font-weight: 700;
      letter-spacing: .2px;
    }

    .card {
      border-radius: 12px;
      box-shadow: 0 4px 16px rgba(0, 0, 0, .06);
    }

    .btn-soft {
      border-radius: 12px;
      font-weight: 600;
      padding: .6rem 1rem;
    }

    .doc-card {
      transition: transform .2s ease;
    }

    .doc-card:hover {
      transform: translateY(-3px);
    }
  </style>
</head>

<body>

  <!-- HERO -->
  <section class="page-hero py-5">
    <div class="container">
      <div class="d-flex justify-content-between align-items-start align-items-md-center flex-column flex-md-row gap-3">
        <div class="text-white">
          <h1 class="title h2 mb-2">
            <i class="bi bi-folder2-open me-2"></i><?= htmlspecialchars($pageTitle) ?>
          </h1>
          <p class="mb-0 text-white-50">Gerencie documentos dos colaboradores</p>
        </div>
        <div class="d-flex gap-2">
          <a href="<?= BASE_URL ?>/employees" class="btn btn-light btn-soft">
            <i class="bi bi-arrow-left me-2"></i>Voltar
          </a>
          <button class="btn btn-success btn-soft" data-bs-toggle="modal" data-bs-target="#uploadModal">
            <i class="bi bi-upload me-2"></i>Novo Documento
          </button>
        </div>
      </div>
    </div>
  </section>

  <!-- CONTEÚDO -->
  <main class="container py-4 py-md-5">

    <!-- Filtros -->
    <div class="card mb-4">
      <div class="card-body">
        <h5 class="card-title mb-3">Filtros</h5>
        <form class="row g-3" method="GET" action="<?= rtrim(BASE_URL, '/') ?>/documents">
          <div class="col-md-4">
            <label class="form-label">Colaborador</label>
            <select name="colaborador" class="form-select">
              <option value="">Todos</option>
              <?php foreach ($employees ?? [] as $emp): ?>
                <option value="<?= (int) $emp['id'] ?>" <?= (!empty($_GET['colaborador']) && $_GET['colaborador'] == $emp['id']) ? 'selected' : '' ?>><?= htmlspecialchars($emp['full_name']) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label">Tipo de Documento</label>
            <select class="form-select">
              <option value="">Todos</option>
              <option>Contrato</option>
              <option>Exame Médico</option>
              <option>Certificado</option>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label">Data de Upload</label>
            <input type="date" class="form-control">
          </div>
          <div class="col-12">
            <button type="submit" class="btn btn-primary">Filtrar</button>
            <button type="reset" class="btn btn-outline-secondary">Limpar</button>
          </div>
        </form>
      </div>
    </div>

    <!-- Documentos -->
    <div class="row g-4">
      <?php if (!empty($_SESSION['error'])): ?>
        <div class="col-12">
          <div class="alert alert-danger"><?= htmlspecialchars($_SESSION['error']) ?></div>
        </div>
        <?php unset($_SESSION['error']); endif; ?>
      <?php if (!empty($_SESSION['success'])): ?>
        <div class="col-12">
          <div class="alert alert-success"><?= htmlspecialchars($_SESSION['success']) ?></div>
        </div>
        <?php unset($_SESSION['success']); endif; ?>

      <?php if (!empty($rows)): ?>
        <?php foreach ($rows as $doc): ?>
          <div class="col-md-6 col-lg-4">
            <div class="card doc-card h-100">
              <div class="card-body">
                <div class="d-flex justify-content-between mb-3">
                  <div class="d-flex align-items-center">
                    <?php
                    $icon = 'bi-file-earmark-text';
                    if (strpos($doc['tipo_arquivo'], 'pdf') !== false)
                      $icon = 'bi-file-earmark-pdf text-danger';
                    elseif (strpos($doc['tipo_arquivo'], 'image') !== false)
                      $icon = 'bi-image text-success';
                    ?>
                    <i class="bi <?= $icon ?> fs-3 me-2"></i>
                    <h5 class="card-title mb-0"><?= htmlspecialchars($doc['titulo']) ?></h5>
                  </div>
                  <div class="dropdown">
                    <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="dropdown">
                      <i class="bi bi-three-dots-vertical"></i>
                    </button>
                    <ul class="dropdown-menu">
                      <li><a class="dropdown-item"
                          href="<?= rtrim(BASE_URL, '/') ?>/documents/download/<?= (int) $doc['id'] ?>"><i
                            class="bi bi-download me-2"></i>Download</a></li>
                      <li><a class="dropdown-item" href="#"><i class="bi bi-pencil me-2"></i>Editar</a></li>
                      <li>
                        <hr class="dropdown-divider">
                      </li>
                      <li><a class="dropdown-item text-danger"
                          href="<?= rtrim(BASE_URL, '/') ?>/documents/delete/<?= (int) $doc['id'] ?>"
                          onclick="return confirm('Excluir este documento?');"><i class="bi bi-trash me-2"></i>Excluir</a>
                      </li>
                    </ul>
                  </div>
                </div>
                <p class="card-text text-muted mb-1">Enviado por: <?= htmlspecialchars($doc['uploader'] ?? 'Sistema') ?></p>
                <p class="card-text text-muted mb-3">Enviado em: <?= date('d/m/Y H:i', strtotime($doc['data_upload'])) ?>
                </p>
                <div class="d-grid">
                  <a href="<?= rtrim(BASE_URL, '/') ?>/documents/download/<?= (int) $doc['id'] ?>"
                    class="btn btn-outline-primary btn-sm">
                    <i class="bi bi-eye me-2"></i>Visualizar / Download
                  </a>
                </div>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      <?php else: ?>
        <div class="col-12">
          <div class="alert alert-info">Nenhum documento encontrado.</div>
        </div>
      <?php endif; ?>
    </div>
  </main>

  <!-- Modal de Upload -->
  <div class="modal fade" id="uploadModal" tabindex="-1">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Novo Documento</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form method="POST" action="<?= rtrim(BASE_URL, '/') ?>/documents/store" enctype="multipart/form-data"
            id="uploadForm">
            <div class="mb-3">
              <label class="form-label">Colaborador</label>
              <select name="colaborador_id" class="form-select">
                <option value="">Selecione...</option>
                <?php foreach ($employees ?? [] as $emp): ?>
                  <option value="<?= (int) $emp['id'] ?>"><?= htmlspecialchars($emp['full_name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="mb-3">
              <label class="form-label">Tipo de Documento</label>
              <select name="categoria" class="form-select" required>
                <option value="">Selecione...</option>
                <option>Ofício</option>
                <option>Requerimento</option>
                <option>Projetos</option>
                <option>Prestação de Contas</option>
                <option>Diversos</option>
              </select>
            </div>
            <div class="mb-3">
              <label class="form-label">Arquivo</label>
              <input name="file" type="file" class="form-control" required>
            </div>
            <div class="mb-3">
              <label class="form-label">Descrição</label>
              <textarea name="descricao" class="form-control" rows="3"></textarea>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
          <button type="submit" class="btn btn-primary" form="uploadForm">Enviar</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Bootstrap JS -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>