<?php
// src/views/payrolls/index.php (refatorado)
// Lista/consulta de folhas de pagamento
// - Usa header/footer padronizados
// - Filtros por colaborador, mês, ano e status
// - Ações: criar, visualizar, editar e exportar CSV

if (session_status() === PHP_SESSION_NONE) session_start();

// Partials cuidam de BASE_URL e demais configurações
require_once __DIR__ . '/../partials/header.php';

// Variáveis vindas do Controller (garante valores padrão caso não venham)
$employees   = $employees   ?? [];
$payrolls    = $payrolls    ?? [];
$filters     = $filters     ?? [
  'employee_id' => $_GET['employee_id'] ?? '',
  'month'       => $_GET['month'] ?? '',
  'year'        => $_GET['year'] ?? '',
  'status'      => $_GET['status'] ?? ''
];
$totalCount  = isset($totalCount) ? (int)$totalCount : count($payrolls);
$page        = max(1, (int)($_GET['page'] ?? 1));
$perPage     = max(10, (int)($_GET['per_page'] ?? 10));

// >>> Fallback: buscar colaboradores direto no banco se o controller não populou
// Bootstrap de env/db e manter estado do filtro de colaborador
if (!function_exists('public_root')) {
  require_once __DIR__ . '/../../config/env.php';
}
require_once __DIR__ . '/../../config/db.php';
if (!isset($pdo) || !($pdo instanceof PDO)) {
  if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
    $pdo = $GLOBALS['pdo'];
  }
}
$selectedEmployee = $filters['employee_id'] ?? '';
if (empty($employees)) {
  try {
    if (!isset($pdo) || !($pdo instanceof PDO)) {
      throw new Exception('Conexão com banco indisponível.');
    }
    $stmt = $pdo->query("SELECT id, full_name, salary, job_title FROM employees WHERE status = 'ativo' ORDER BY full_name");
    $employees = $stmt->fetchAll();
  } catch (Throwable $e) {
    $dbError = 'Falha ao carregar colaboradores: ' . $e->getMessage();
  }
}


// >>> Fallback: buscar folhas direto no banco se o controller não populou
if (empty($payrolls)) {
  try {
    if (!isset($pdo) || !($pdo instanceof PDO)) {
      throw new Exception('Conexão com banco indisponível para buscar folhas.');
    }
    // Montar WHERE dinâmico com base nos filtros
    $where   = [];
    $params  = [];
    if (!empty($filters['employee_id'])) { $where[] = "p.employee_id = :employee_id"; $params[':employee_id'] = (int)$filters['employee_id']; }
    if (!empty($filters['month']))       { $where[] = "p.reference_month = :month";   $params[':month']       = (int)$filters['month']; }
    if (!empty($filters['year']))        { $where[] = "p.reference_year  = :year";    $params[':year']        = (int)$filters['year']; }
    $whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

    // Total para paginação
    $sqlCount = "SELECT COUNT(*) AS total FROM payrolls p {$whereSql}";
    $stmtCnt  = $pdo->prepare($sqlCount);
    foreach ($params as $k=>$v) { $stmtCnt->bindValue($k, $v, PDO::PARAM_INT); }
    $stmtCnt->execute();
    $totalCount = (int)$stmtCnt->fetchColumn();

    // Buscar folhas
    $sql = "
      SELECT
        p.id,
        p.employee_id,
        e.full_name           AS employee_name,
        p.reference_month,
        p.reference_year,
        p.base_salary,
        p.total_discounts,
        p.net_salary,
        'processada'          AS status,
        p.generated_at
      FROM payrolls p
      JOIN employees e ON e.id = p.employee_id
      {$whereSql}
      ORDER BY p.reference_year DESC, p.reference_month DESC, e.full_name ASC
      LIMIT :limit OFFSET :offset
    ";
    $stmt = $pdo->prepare($sql);
    foreach ($params as $k=>$v) { $stmt->bindValue($k, $v, PDO::PARAM_INT); }
    $stmt->bindValue(':limit',  $perPage, PDO::PARAM_INT);
    $stmt->bindValue(':offset', ($page - 1) * $perPage, PDO::PARAM_INT);
    $stmt->execute();
    $payrolls = $stmt->fetchAll(PDO::FETCH_ASSOC);
  } catch (Throwable $e) {
    $dbError = 'Falha ao carregar folhas: ' . $e->getMessage();
    $payrolls = [];
    $totalCount = 0;
  }
}

// Funções utilitárias locais
$fmtMoney = function($v){ return 'R$ ' . number_format((float)$v, 2, ',', '.'); };
$badge = function($status){
  $map = [
    'aberta'   => 'bg-secondary',
    'processada'=> 'bg-primary',
    'paga'     => 'bg-success',
    'cancelada'=> 'bg-danger'
  ];
  $cls = $map[strtolower((string)$status)] ?? 'bg-secondary';
  return '<span class="badge '.$cls.'">'.htmlspecialchars(ucfirst((string)$status)).'</span>';
};

?>

<!-- Cabeçalho / Breadcrumb -->
<div class="bg-white border-bottom">
  <div class="container py-4">

    <div class="d-flex align-items-center justify-content-between">
      <h1 class="h4 mb-0">Folhas de pagamento</h1>
      <div class="d-flex gap-2">
        <a class="btn btn-outline-secondary" href="<?= rtrim(BASE_URL,'/') ?>/payrolls/export?format=csv">
          <i class="bi bi-download me-1"></i> Exportar CSV
        </a>
        <a class="btn btn-secondary" href="#" onclick="window.history.back(); return false;">
          <i class="bi bi-arrow-left me-1"></i> Voltar
        </a>
        <a class="btn btn-primary" href="<?= rtrim(BASE_URL,'/') ?>/src/views/payrolls/create.php">
          <i class="bi bi-plus-lg me-1"></i> Nova folha
        </a>
      </div>
    </div>
  </div>
</div>

<div class="container py-4">
  <!-- Alerts -->
  <?php if (!empty($_SESSION['success'])): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
      <?= htmlspecialchars($_SESSION['success']); unset($_SESSION['success']); ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
  <?php endif; ?>

  <?php if (!empty($_SESSION['error'])): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
      <?= htmlspecialchars($_SESSION['error']); unset($_SESSION['error']); ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
  <?php endif; ?>

  <?php if (!empty($dbError)): ?>
    <div class="alert alert-warning alert-dismissible fade show" role="alert">
      <?= htmlspecialchars($dbError) ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
  <?php endif; ?>

  <!-- Filtros -->
  <form class="card card-body shadow-sm mb-4" method="get" action="<?= rtrim(BASE_URL,'/') ?>/src/views/payrolls/">
    <div class="row g-3 align-items-end">
      <div class="col-12 col-md-4">
        <label class="form-label" for="employee_id">Colaborador</label>
        <select class="form-select" id="employee_id" name="employee_id">
          <option value="">Todos</option>
          <?php foreach ($employees as $employee): ?>
            <?php
              $empId   = $employee['id']        ?? '';
              $empName = $employee['full_name'] ?? '';
              $salary  = $employee['salary']    ?? '';
              $title   = $employee['job_title'] ?? '';
            ?>
            <option value="<?= htmlspecialchars((string)$empId) ?>"
                    data-salary="<?= htmlspecialchars((string)$salary) ?>"
                    <?= ($selectedEmployee == $empId) ? 'selected' : '' ?>>
              <?= htmlspecialchars($empName) ?><?= $title ? ' - '.htmlspecialchars($title) : '' ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-6 col-md-2">
        <label class="form-label" for="month">Mês</label>
        <select class="form-select" id="month" name="month">
          <option value="">Todos</option>
          <?php for ($m=1;$m<=12;$m++): ?>
            <option value="<?= $m ?>" <?= ($filters['month']==(string)$m?'selected':'') ?>><?= str_pad((string)$m,2,'0',STR_PAD_LEFT) ?></option>
          <?php endfor; ?>
        </select>
      </div>
      <div class="col-6 col-md-2">
        <label class="form-label" for="year">Ano</label>
        <input class="form-control" type="number" id="year" name="year" min="2000" max="2100" value="<?= htmlspecialchars((string)$filters['year']) ?>">
      </div>
      <div class="col-6 col-md-2">
        <label class="form-label" for="status">Status</label>
        <select class="form-select" id="status" name="status">
          <option value="">Todos</option>
          <?php foreach (['aberta','processada','paga','cancelada'] as $st): ?>
            <option value="<?= $st ?>" <?= ($filters['status']===$st?'selected':'') ?>><?= ucfirst($st) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-6 col-md-2 d-grid">
        <button type="submit" class="btn btn-dark"><i class="bi bi-search me-1"></i> Filtrar</button>
      </div>
    </div>
  </form>

  <!-- Tabela -->
  <div class="card shadow-sm">
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-hover align-middle mb-0">
          <thead class="table-light">
            <tr>
              <th style="width:70px">#</th>
              <th>Colaborador</th>
              <th class="text-center">Mês/Ano</th>
              <th class="text-end">Salário base</th>
              <th class="text-end">Descontos</th>
              <th class="text-end">Líquido</th>
              <th class="text-center">Status</th>
              <th style="width:160px" class="text-end">Ações</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($payrolls)): ?>
              <tr>
                <td colspan="8" class="text-center text-muted py-4">Nenhum registro encontrado.</td>
              </tr>
            <?php else: ?>
              <?php foreach ($payrolls as $row): ?>
                <?php
                  $id      = $row['id'] ?? $row->id ?? '';
                  $nome    = $row['employee_name'] ?? $row['name'] ?? $row->employee_name ?? '';
                  $mes     = $row['reference_month'] ?? $row->reference_month ?? '';
                  $ano     = $row['reference_year']  ?? $row->reference_year  ?? '';
                  $base    = $row['base_salary']     ?? $row->base_salary     ?? 0;
                  $desc    = $row['total_discounts'] ?? $row->total_discounts ?? 0;
                  $liq     = $row['net_salary']      ?? $row->net_salary      ?? 0;
                  $status  = $row['status']          ?? $row->status          ?? 'aberta';
                ?>
                <tr>
                  <td><?= htmlspecialchars((string)$id) ?></td>
                  <td><?= htmlspecialchars((string)$nome) ?></td>
                  <td class="text-center"><?= str_pad((string)$mes,2,'0',STR_PAD_LEFT) ?>/<?= htmlspecialchars((string)$ano) ?></td>
                  <td class="text-end"><?= $fmtMoney($base) ?></td>
                  <td class="text-end"><?= $fmtMoney($desc) ?></td>
                  <td class="text-end fw-semibold"><?= $fmtMoney($liq) ?></td>
                  <td class="text-center"><?= $badge($status) ?></td>
                  <td class="text-end">
                    <div class="btn-group" role="group">
                      <a class="btn btn-sm btn-outline-secondary" href="<?= rtrim(BASE_URL,'/') ?>/payrolls/show?id=<?= urlencode((string)$id) ?>" title="Visualizar">
                        <i class="bi bi-eye"></i>
                      </a>
                      <a class="btn btn-sm btn-outline-primary" href="<?= rtrim(BASE_URL,'/') ?>/payrolls/edit?id=<?= urlencode((string)$id) ?>" title="Editar">
                        <i class="bi bi-pencil"></i>
                      </a>
                      <a class="btn btn-sm btn-outline-dark" href="<?= rtrim(BASE_URL,'/') ?>/payrolls/export?format=csv&id=<?= urlencode((string)$id) ?>" title="Exportar CSV">
                        <i class="bi bi-filetype-csv"></i>
                      </a>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

    <!-- Paginação simples (opcional; controlada pelo Controller) -->
    <?php
      $totalPages = max(1, (int)ceil($totalCount / $perPage));
      $qs = $_GET; unset($qs['page']);
      $baseLink = rtrim(BASE_URL,'/') . '/payrolls?' . http_build_query($qs);
    ?>
    <?php if ($totalPages > 1): ?>
    <div class="card-footer d-flex justify-content-between align-items-center">
      <small class="text-muted">Total: <?= (int)$totalCount ?> registro(s)</small>
      <nav>
        <ul class="pagination mb-0">
          <li class="page-item <?= $page<=1?'disabled':'' ?>">
            <a class="page-link" href="<?= $baseLink . '&page=' . max(1,$page-1) ?>" tabindex="-1" aria-disabled="true">Anterior</a>
          </li>
          <?php for ($p=1; $p<=$totalPages; $p++): ?>
            <li class="page-item <?= $p===$page?'active':'' ?>">
              <a class="page-link" href="<?= $baseLink . '&page=' . $p ?>"><?= $p ?></a>
            </li>
          <?php endfor; ?>
          <li class="page-item <?= $page>=$totalPages?'disabled':'' ?>">
            <a class="page-link" href="<?= $baseLink . '&page=' . min($totalPages,$page+1) ?>">Próxima</a>
          </li>
        </ul>
      </nav>
    </div>
    <?php endif; ?>
  </div>
</div>

<?php require_once __DIR__ . '/../partials/footer.php'; ?>
