<?php
// src/views/payrolls/create.php — ajustado para carregar colaboradores do BD
// e exibir erro visível quando a query falhar.

if (session_status() === PHP_SESSION_NONE) session_start();
$pageTitle = 'Nova Folha de Pagamento';
$mode = $_GET['mode'] ?? 'create';
$currentId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$isView = ($mode === 'view');
$isEdit = ($mode === 'edit');
if ($isView) { $pageTitle = 'Visualizar Folha de Pagamento'; }
elseif ($isEdit) { $pageTitle = 'Editar Folha de Pagamento'; }
// ===== Handler de POST (salvar no BD) — executa antes de imprimir HTML =====
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  if (session_status() === PHP_SESSION_NONE) session_start();
  $errors = [];
  $brlToFloat = function($s){
    $s = preg_replace('/[^0-9,\.\-]/','', (string)$s);
    $s = str_replace('.', '', $s);     // remove milhar
    $s = str_replace(',', '.', $s);    // vírgula -> ponto
    return is_numeric($s) ? (float)$s : 0.0;
  };
  $employeeId = isset($_POST['employee_id']) ? (int)$_POST['employee_id'] : 0;
  $month      = isset($_POST['reference_month']) ? (int)$_POST['reference_month'] : 0;
  $year       = isset($_POST['reference_year']) ? (int)$_POST['reference_year'] : 0;
  $baseSalary = $brlToFloat($_POST['base_salary']     ?? '0');
  $discounts  = $brlToFloat($_POST['total_discounts'] ?? '0');
  $netSalary  = max(0, $baseSalary - $discounts);

  if ($employeeId <= 0)           $errors[] = 'Selecione um colaborador.';
  if ($month < 1 || $month > 12)  $errors[] = 'Mês inválido.';
  if ($year  < 2000 || $year>2100)$errors[] = 'Ano inválido.';

  try {
    require_once __DIR__ . '/../../config/env.php';
    require_once __DIR__ . '/../../config/db.php';
    // $pdo fornecido por db.php
    if (!isset($pdo) || !($pdo instanceof PDO)) {
      throw new Exception('Conexão PDO não inicializada.');
    }

    if (empty($errors)) {
      // Confere colaborador ativo
      $st = $pdo->prepare("SELECT COUNT(*) FROM employees WHERE id = :id AND status = 'ativo'");
      $st->execute([':id'=>$employeeId]);
      if ((int)$st->fetchColumn() === 0) $errors[] = 'Colaborador inválido ou inativo.';
    }

    if (empty($errors)) {
      // Evita duplicidade (employee + mês + ano)
      $st = $pdo->prepare("SELECT COUNT(*) FROM payrolls WHERE employee_id=:e AND reference_month=:m AND reference_year=:y");
      $st->execute([':e'=>$employeeId, ':m'=>$month, ':y'=>$year]);
      if ((int)$st->fetchColumn() > 0) $errors[] = 'Já existe uma folha para este colaborador e período.';
    }

    if (!empty($errors)) {
      $_SESSION['errors'] = $errors;
      header('Location: http://localhost:8888/gabinete/src/views/payrolls/create.php');
      exit;
    }

    // Inserção/Atualização conforme modo
    $modePost = $_POST['mode'] ?? 'create';
    $editId   = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    $isEditingPost = ($modePost === 'edit' && $editId > 0);

    // Campos obrigatórios (schema): total_earnings (NOT NULL) e worked_days (NOT NULL)
    $overtimeAmount = 0.0; // padrão
    $totalEarnings  = $baseSalary + $overtimeAmount;
    $workedDays     = 0;   // pode ser calculado posteriormente

    if ($isEditingPost) {
      // Atualiza registro existente
      $upd = $pdo->prepare("UPDATE payrolls SET
          employee_id = :e,
          reference_month = :m,
          reference_year = :y,
          base_salary = :b,
          overtime_amount = :ot,
          total_earnings = :te,
          total_discounts = :d,
          net_salary = :n,
          worked_days = :wd
        WHERE id = :id");
      $upd->execute([
        ':e'=>$employeeId,
        ':m'=>$month,
        ':y'=>$year,
        ':b'=>$baseSalary,
        ':ot'=>$overtimeAmount,
        ':te'=>$totalEarnings,
        ':d'=>$discounts,
        ':n'=>$netSalary,
        ':wd'=>$workedDays,
        ':id'=>$editId,
      ]);
      $_SESSION['success'] = 'Folha atualizada com sucesso!';
      header('Location: ' . rtrim(BASE_URL,'/') . '/payrolls');
      exit;
    } else {
      // Insere novo registro
      $ins = $pdo->prepare("INSERT INTO payrolls (
          employee_id, reference_month, reference_year,
          base_salary, overtime_amount, total_earnings,
          total_discounts, net_salary, worked_days, generated_at
        ) VALUES (
          :e, :m, :y, :b, :ot, :te, :d, :n, :wd, NOW()
        )");
      $ins->execute([
        ':e'=>$employeeId,
        ':m'=>$month,
        ':y'=>$year,
        ':b'=>$baseSalary,
        ':ot'=>$overtimeAmount,
        ':te'=>$totalEarnings,
        ':d'=>$discounts,
        ':n'=>$netSalary,
        ':wd'=>$workedDays,
      ]);

      $_SESSION['success'] = 'Folha criada com sucesso!';
      header('Location: ' . rtrim(BASE_URL,'/') . '/payrolls');
      exit;
    }
  } catch (Throwable $ex) {
    $_SESSION['error'] = 'Erro ao salvar: ' . $ex->getMessage();
    header('Location: http://localhost:8888/gabinete/src/views/payrolls/create.php');
    exit;
  }
}

require_once __DIR__ . '/../partials/header.php';

// -------------------------
// Fallback: buscar $employees do BD caso o controller não tenha enviado
// -------------------------
$employees = $employees ?? [];
$dbError   = $dbError   ?? '';

if (empty($employees)) {
  try {
    require_once __DIR__ . '/../../config/env.php';
    require_once __DIR__ . '/../../config/db.php';
    if (!isset($pdo) || !($pdo instanceof PDO)) {
      throw new Exception('Conexão PDO não inicializada.');
    }

    $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();
    // Opcional: logar
    if (function_exists('error_log')) { error_log($dbError); }
  }
}

// Defaults úteis para selects do formulário
$selectedEmployee = $selectedEmployee ?? '';
$selectedMonth    = $selectedMonth    ?? (int)date('n');
$selectedYear     = $selectedYear     ?? (int)date('Y');
$calculatedData   = $calculatedData   ?? null;
?>

<!-- Cabeçalho / Breadcrumb (Bootstrap) -->
<div class="bg-white border-bottom">
  <div class="container py-4">
    <nav class="small text-muted" aria-label="breadcrumb">
      <ol class="breadcrumb mb-2">
        <li class="breadcrumb-item"><a href="<?= rtrim(BASE_URL,'/') ?>/payrolls">Folhas de pagamento</a></li>
        <li class="breadcrumb-item active" aria-current="page">Nova folha</li>
      </ol>
    </nav>
    <h1 class="h4 mb-0">Nova folha de pagamento</h1>
  </div>
</div>

<!-- Conteúdo -->
<div class="container py-4">


  <!-- Alertas globais -->
  <?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; ?>

  <!-- Alertas de validação -->
  <?php if (!empty($_SESSION['errors'])): ?>
  <div class="alert alert-danger" role="alert">
    <strong>Corrija os seguintes erros:</strong>
    <ul class="mb-0 mt-2">
      <?php foreach ($_SESSION['errors'] as $error): ?>
        <li><?= htmlspecialchars($error) ?></li>
      <?php endforeach; ?>
    </ul>
  </div>
  <?php unset($_SESSION['errors']); ?>
<?php endif; ?>

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

  <form method="POST" action="http://localhost:8888/gabinete/src/views/payrolls/create.php" class="needs-validation" novalidate>
  <div class="row g-4">

    <!-- Coluna principal -->
    <div class="col-lg-9">
      <!-- Card: Dados da folha -->
      <div class="card shadow-sm mb-4">
        <div class="card-header bg-white"><strong>Dados da folha</strong></div>
        <div class="card-body">
          <div class="row g-3 align-items-end">
            <div class="col-12 col-md-8">
              <label for="employee_id" class="form-label">Colaborador <span class="text-danger">*</span></label>
              <select id="employee_id" name="employee_id" class="form-select" required onchange="prefillSalary();">
                <option value="">Selecione um colaborador</option>
                <?php if (!empty($employees)): ?>
                  <?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; ?>
                <?php endif; ?>
              </select>
              <div class="form-text">Apenas colaboradores com status <em>ativo</em> aparecem na lista.</div>
              <div class="invalid-feedback">Selecione um colaborador.</div>
            </div>

            <div class="col-6 col-md-2">
              <label for="reference_month" class="form-label">Mês <span class="text-danger">*</span></label>
              <select id="reference_month" name="reference_month" class="form-select" required>
                <?php for ($i = 1; $i <= 12; $i++): ?>
                  <option value="<?= $i ?>" <?= ($selectedMonth == $i) ? 'selected' : '' ?>><?= str_pad((string)$i,2,'0',STR_PAD_LEFT) ?></option>
                <?php endfor; ?>
              </select>
              <div class="invalid-feedback">Informe o mês.</div>
            </div>

            <div class="col-6 col-md-2">
              <label for="reference_year" class="form-label">Ano <span class="text-danger">*</span></label>
              <input type="number" id="reference_year" name="reference_year" class="form-control" required min="2000" max="2100" value="<?= htmlspecialchars((string)$selectedYear) ?>" />
              <div class="invalid-feedback">Informe o ano.</div>
            </div>
          </div>
        </div>
      </div>

      <!-- Card: Valores -->
      <div class="card shadow-sm mb-4">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
          <strong>Valores</strong>
          <small class="text-muted">Os campos aceitam moeda (R$)</small>
        </div>
        <div class="card-body">
          <div class="row g-3">
            <div class="col-12 col-md-4">
              <label for="base_salary" class="form-label">Salário base</label>
              <div class="input-group">
                <span class="input-group-text">R$</span>
                <input type="text" id="base_salary" name="base_salary" class="form-control" inputmode="numeric" placeholder="0,00" oninput="formatCurrency(this);updateNet();" />
              </div>
            </div>
            <div class="col-12 col-md-4">
              <label for="total_discounts" class="form-label">Descontos</label>
              <div class="input-group">
                <span class="input-group-text">R$</span>
                <input type="text" id="total_discounts" name="total_discounts" class="form-control" inputmode="numeric" placeholder="0,00" oninput="formatCurrency(this);updateNet();" />
              </div>
            </div>
            <div class="col-12 col-md-4">
              <label for="net_salary" class="form-label">Líquido</label>
              <div class="input-group">
                <span class="input-group-text">R$</span>
                <input type="text" id="net_salary" name="net_salary" class="form-control" readonly placeholder="0,00" />
              </div>
              <div class="form-text">Calculado automaticamente: base - descontos.</div>
            </div>
          </div>
        </div>
      </div>

      <!-- Card: Observações (opcional) -->
      <div class="card shadow-sm mb-4">
        <div class="card-header bg-white"><strong>Observações</strong></div>
        <div class="card-body">
          <textarea name="notes" id="notes" rows="4" class="form-control" placeholder="Notas internas (opcional)"></textarea>
        </div>
      </div>
    </div>

    <!-- Sidebar (ações/resumo) -->
    <div class="col-lg-3">
      <div class="card shadow-sm position-sticky" style="top: 1rem;">
        <div class="card-body">
          <h6 class="text-uppercase text-muted small mb-3">Resumo</h6>
          <ul class="list-group list-group-flush mb-3">
            <li class="list-group-item d-flex justify-content-between align-items-center px-0">
              <span>Base</span>
              <strong id="sumBase">R$ 0,00</strong>
            </li>
            <li class="list-group-item d-flex justify-content-between align-items-center px-0">
              <span>Descontos</span>
              <strong id="sumDesc">R$ 0,00</strong>
            </li>
            <li class="list-group-item d-flex justify-content-between align-items-center px-0">
              <span>Líquido</span>
              <strong id="sumNet">R$ 0,00</strong>
            </li>
          </ul>
          <div class="d-grid gap-2">
            <button type="submit" class="btn btn-primary">
              <i class="bi bi-save me-1"></i> Salvar folha
            </button>
            <a href="<?= rtrim(BASE_URL,'/') ?>/payrolls" class="btn btn-outline-secondary">Cancelar</a>
          </div>
        </div>
      </div>
    </div>

  </div>
</form>
</div>





<script>
// ===== Funções globais (sem regex especiais para evitar conflitos) =====
window.parseBRL = function(v){
  if(!v) return 0;
  var s = String(v);
  // mantém apenas 0-9 , . -
  var cleaned = '';
  for (var i=0;i<s.length;i++) {
    var ch = s[i];
    if ((ch>='0' && ch<='9') || ch===',' || ch==='.' || ch==='-') cleaned += ch;
  }
  s = cleaned.split('.').join(''); // remove milhar
  s = s.replace(',', '.');         // vírgula -> ponto
  var n = parseFloat(s);
  return isNaN(n) ? 0 : n;
};

window.formatCurrency = function(input){
  if(!input) return;
  var s = String(input.value||'');
  var digits = '';
  for (var i=0;i<s.length;i++) { var c=s[i]; if (c>='0' && c<='9') digits += c; }
  var number = (parseInt(digits,10)||0)/100;
  input.value = number.toLocaleString('pt-BR',{minimumFractionDigits:2,maximumFractionDigits:2});
};

window.updateNet = function(){
  var baseEl = document.getElementById('base_salary') || document.querySelector('[name="base_salary"]');
  var descEl = document.getElementById('total_discounts') || document.querySelector('[name="total_discounts"]');
  var netEl  = document.getElementById('net_salary') || document.querySelector('[name="net_salary"]');
  var base = window.parseBRL(baseEl ? baseEl.value : '');
  var desc = window.parseBRL(descEl ? descEl.value : '');
  var net  = Math.max(0, base - desc);
  var fmt = function(n){return n.toLocaleString('pt-BR',{minimumFractionDigits:2,maximumFractionDigits:2});};
  if(netEl) netEl.value = fmt(net);
  var sb=document.getElementById('sumBase'); if(sb) sb.textContent = 'R$ ' + fmt(base);
  var sd=document.getElementById('sumDesc'); if(sd) sd.textContent = 'R$ ' + fmt(desc);
  var sn=document.getElementById('sumNet');  if(sn) sn.textContent  = 'R$ ' + fmt(net);
};

window.prefillSalary = function(){
  var emp = document.getElementById('employee_id') || document.querySelector('[name="employee_id"]');
  var baseEl = document.getElementById('base_salary') || document.querySelector('[name="base_salary"]');
  if(!emp || !baseEl){ window.updateNet(); return; }
  var opt = emp.options[emp.selectedIndex];
  if(!opt){ window.updateNet(); return; }
  var salary = opt.getAttribute('data-salary');
  if(salary!=null){
    var s = String(salary);
    s = s.split('.').join('');
    s = s.replace(',', '.');
    var n = parseFloat(s) || 0;
    baseEl.value = n.toLocaleString('pt-BR',{minimumFractionDigits:2,maximumFractionDigits:2});
  }
  window.updateNet();
};

(function bind(){
  function go(){
    var baseEl = document.getElementById('base_salary') || document.querySelector('[name="base_salary"]');
    var descEl = document.getElementById('total_discounts') || document.querySelector('[name="total_discounts"]');
    var emp    = document.getElementById('employee_id') || document.querySelector('[name="employee_id"]');
    if(baseEl){ baseEl.addEventListener('input', function(){ window.formatCurrency(baseEl); window.updateNet(); }); baseEl.addEventListener('change', window.updateNet); }
    if(descEl){ descEl.addEventListener('input', function(){ window.formatCurrency(descEl); window.updateNet(); }); descEl.addEventListener('change', window.updateNet); }
    if(emp){ emp.addEventListener('change', window.prefillSalary); }
    window.prefillSalary();
    window.updateNet();
  }
  if(document.readyState === 'loading') document.addEventListener('DOMContentLoaded', go); else go();
})();
</script>

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