<?php
$title='Series';
require_once __DIR__ . '/../inc/header.php';
require_once __DIR__ . '/../inc/docs.php';
ensure_part2_tables();
if(!is_admin()){ http_response_code(403); exit('Solo admin'); }

$pdo=db();
$year = (int)($_GET['year'] ?? date('Y'));

if($_SERVER['REQUEST_METHOD']==='POST'){
  csrf_check();
  $action = $_POST['action'] ?? '';
  if($action==='save'){
    $doc_type = $_POST['doc_type'] ?? 'invoice';
    $prefix = trim((string)($_POST['prefix'] ?? ''));
    $next_number = (int)($_POST['next_number'] ?? 1);
    $y = (int)($_POST['year'] ?? $year);
    if(!in_array($doc_type, ['invoice','quote'], true)) $doc_type='invoice';
    if($prefix===''){ flash_set('danger','El prefijo no puede estar vacío.'); redirect('settings/series.php?year='.$y); }
    if($next_number < 1) $next_number = 1;

    // doc_series usa doc_type ENUM('quote','invoice')
    $st=$pdo->prepare("SELECT id FROM doc_series WHERE doc_type=? AND year=? LIMIT 1");
    $st->execute([$doc_type,$y]);
    $row=$st->fetch();
    if($row){
      $pdo->prepare("UPDATE doc_series SET prefix=?, next_number=? WHERE id=?")
          ->execute([$prefix, $next_number, (int)$row['id']]);
    }else{
      $pdo->prepare("INSERT INTO doc_series(doc_type,year,prefix,next_number) VALUES(?,?,?,?)")
          ->execute([$doc_type,$y,$prefix,$next_number]);
    }
    flash_set('success','Serie guardada.');
    redirect('settings/series.php?year='.$y);
  }

  if($action==='reset'){
    $doc_type = $_POST['doc_type'] ?? 'invoice';
    $y = (int)($_POST['year'] ?? $year);
    if(!in_array($doc_type, ['invoice','quote'], true)) $doc_type='invoice';
    $prefix = default_prefix($doc_type, $y);
    $pdo->prepare("INSERT INTO doc_series(doc_type,year,prefix,next_number) VALUES(?,?,?,1)
                   ON DUPLICATE KEY UPDATE prefix=VALUES(prefix), next_number=1")
        ->execute([$doc_type,$y,$prefix]);
    flash_set('success','Serie reiniciada a 1.');
    redirect('settings/series.php?year='.$y);
  }
}

// Cargar series del año
$st=$pdo->prepare("SELECT * FROM doc_series WHERE year=? ORDER BY doc_type ASC");
$st->execute([$year]);
$rows=$st->fetchAll();
$byType=[];
foreach($rows as $r){ $byType[$r['doc_type']]=$r; }

function rowFor($type,$year,$byType){
  if(isset($byType[$type])) return $byType[$type];
  return ['doc_type'=>$type,'year'=>$year,'prefix'=>default_prefix($type,$year),'next_number'=>1];
}

$invoice = rowFor('invoice',$year,$byType);
$quote   = rowFor('quote',$year,$byType);
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="mb-0">Series de documentos</h4>
    <div class="text-muted">Controla el prefijo y el siguiente número para facturas y presupuestos.</div>
  </div>
  <div class="d-flex gap-2">
    <form method="get" class="d-flex gap-2">
      <input class="form-control" style="width:120px" name="year" value="<?= (int)$year ?>">
      <button class="btn btn-outline-secondary">Ir</button>
    </form>
    <a class="btn btn-outline-secondary" href="<?= url('settings/index.php') ?>">Volver</a>
  </div>
</div>

<div class="row g-3">
  <div class="col-lg-6">
    <div class="card shadow-sm"><div class="card-body">
      <h6 class="mb-3">Facturas (<?= (int)$year ?>)</h6>
      <form method="post" class="row g-2">
        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
        <input type="hidden" name="action" value="save">
        <input type="hidden" name="doc_type" value="invoice">
        <input type="hidden" name="year" value="<?= (int)$year ?>">
        <div class="col-12">
          <label class="form-label">Prefijo</label>
          <input class="form-control" name="prefix" value="<?= h($invoice['prefix']) ?>" required>
          <div class="form-text">Ej: F-<?= (int)$year ?>-</div>
        </div>
        <div class="col-12">
          <label class="form-label">Siguiente número</label>
          <input class="form-control" type="number" min="1" name="next_number" value="<?= (int)$invoice['next_number'] ?>" required>
        </div>
        <div class="col-12 d-flex gap-2">
          <button class="btn btn-primary">Guardar</button>
      </form>
          <form method="post" onsubmit="return confirm('¿Reiniciar la serie a 1?');">
            <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="action" value="reset">
            <input type="hidden" name="doc_type" value="invoice">
            <input type="hidden" name="year" value="<?= (int)$year ?>">
            <button class="btn btn-outline-danger">Reiniciar</button>
          </form>
        </div>
    </div></div>
  </div>

  <div class="col-lg-6">
    <div class="card shadow-sm"><div class="card-body">
      <h6 class="mb-3">Presupuestos (<?= (int)$year ?>)</h6>
      <form method="post" class="row g-2">
        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
        <input type="hidden" name="action" value="save">
        <input type="hidden" name="doc_type" value="quote">
        <input type="hidden" name="year" value="<?= (int)$year ?>">
        <div class="col-12">
          <label class="form-label">Prefijo</label>
          <input class="form-control" name="prefix" value="<?= h($quote['prefix']) ?>" required>
          <div class="form-text">Ej: P-<?= (int)$year ?>-</div>
        </div>
        <div class="col-12">
          <label class="form-label">Siguiente número</label>
          <input class="form-control" type="number" min="1" name="next_number" value="<?= (int)$quote['next_number'] ?>" required>
        </div>
        <div class="col-12 d-flex gap-2">
          <button class="btn btn-primary">Guardar</button>
      </form>
          <form method="post" onsubmit="return confirm('¿Reiniciar la serie a 1?');">
            <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="action" value="reset">
            <input type="hidden" name="doc_type" value="quote">
            <input type="hidden" name="year" value="<?= (int)$year ?>">
            <button class="btn btn-outline-danger">Reiniciar</button>
          </form>
        </div>
    </div></div>
  </div>
</div>

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