<?php
declare(strict_types=1);
/**
 * modules/suppliers/list.php
 */
require_once dirname(__DIR__, 2) . '/config/functions.php';
require_role(['Sales','SalesManager','Admin','Management']);

$user = current_user();
$cid  = (int)($user['company_id'] ?? 0);
if ($cid <= 0) redirect(url_public('login.php'));

function tbl_exists(string $t): bool {
  try { db()->query("SELECT 1 FROM `{$t}` LIMIT 1"); return true; }
  catch (Throwable $e) { return false; }
}
if (!tbl_exists('suppliers')) {
  db()->exec("CREATE TABLE IF NOT EXISTS suppliers (
    id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    company_id INT(10) UNSIGNED NOT NULL,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) DEFAULT NULL,
    phone VARCHAR(50) DEFAULT NULL,
    notes TEXT DEFAULT NULL,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_company (company_id),
    KEY idx_active (is_active)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
}

$onlyActive = isset($_GET['active']) ? (int)$_GET['active'] : 1;

$sql = "SELECT * FROM suppliers WHERE company_id=:cid";
$args = [':cid'=>$cid];
if ($onlyActive === 1) { $sql .= " AND is_active=1"; }
$sql .= " ORDER BY name ASC";
$q = db()->prepare($sql);
$q->execute($args);
$rows = $q->fetchAll();

include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Suppliers</h1>
  <div class="d-flex gap-2">
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('suppliers/list.php')) ?>?active=1">Active</a>
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('suppliers/list.php')) ?>?active=0">All</a>
    <a class="btn btn-dark" href="<?= e(url_modules('suppliers/add.php')) ?>">+ New Supplier</a>
  </div>
</div>

<div class="card shadow-sm">
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead class="table-light">
        <tr>
          <th>Name</th>
          <th>Email</th>
          <th>Phone</th>
          <th>Status</th>
          <th style="width:220px;">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php if ($rows): foreach ($rows as $s): ?>
          <tr>
            <td class="fw-semibold"><?= e($s['name']) ?></td>
            <td><?= e($s['email'] ?? '—') ?></td>
            <td><?= e($s['phone'] ?? '—') ?></td>
            <td>
              <span class="badge text-bg-<?= ((int)$s['is_active']===1?'success':'secondary') ?>">
                <?= (int)$s['is_active']===1?'Active':'Inactive' ?>
              </span>
            </td>
            <td>
              <div class="d-flex flex-wrap gap-1">
                <a class="btn btn-sm btn-outline-secondary" href="<?= e(url_modules('suppliers/edit.php').'?id='.(int)$s['id']) ?>">Edit</a>
              </div>
            </td>
          </tr>
        <?php endforeach; else: ?>
          <tr><td colspan="5" class="text-center text-muted py-4">No suppliers yet.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php include dirname(__DIR__, 2) . '/includes/footer.php';
