<?php
require_once __DIR__ . '/inc/header.php';
require_once __DIR__ . '/inc/docs.php';

ensure_part2_tables();
$pdo = db();

$clientes = $pdo->query("SELECT COUNT(*) FROM clients")->fetchColumn();

$presupuestos_total = $pdo->query("SELECT COUNT(*) FROM documents WHERE doc_type='quote'")->fetchColumn();
$presupuestos_ok = $pdo->query("SELECT COUNT(*) FROM documents WHERE doc_type='quote' AND status='accepted'")->fetchColumn();

$facturas_total = $pdo->query("SELECT COUNT(*) FROM documents WHERE doc_type='invoice'")->fetchColumn();
$facturas_pendientes = $pdo->query("SELECT COUNT(*) FROM documents WHERE doc_type='invoice' AND status!='paid'")->fetchColumn();

$facturado = $pdo->query("
  SELECT IFNULL(SUM(total),0)
  FROM documents
  WHERE doc_type='invoice'
    AND status='paid'
    AND YEAR(issue_date)=YEAR(CURDATE())
")->fetchColumn();
?>

<h4 class="mb-4">Resumen general</h4>

<div class="row g-3">
  <div class="col-md-3">
    <div class="card shadow-sm">
      <div class="card-body">
        <div class="text-muted small">Clientes</div>
        <div class="fs-3 fw-semibold"><?= $clientes ?></div>
      </div>
    </div>
  </div>

  <div class="col-md-3">
    <div class="card shadow-sm">
      <div class="card-body">
        <div class="text-muted small">Presupuestos</div>
        <div class="fw-semibold"><?= $presupuestos_total ?></div>
        <div class="small text-success"><?= $presupuestos_ok ?> aceptados</div>
      </div>
    </div>
  </div>

  <div class="col-md-3">
    <div class="card shadow-sm">
      <div class="card-body">
        <div class="text-muted small">Facturas</div>
        <div class="fw-semibold"><?= $facturas_total ?></div>
        <div class="small text-warning"><?= $facturas_pendientes ?> pendientes</div>
      </div>
    </div>
  </div>

  <div class="col-md-3">
    <div class="card shadow-sm">
      <div class="card-body">
        <div class="text-muted small">Facturado (<?= date('Y') ?>)</div>
        <div class="fs-5 fw-semibold">
          <?= number_format($facturado, 2, ',', '.') ?> €
        </div>
      </div>
    </div>
  </div>
</div>

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