<?php
declare(strict_types=1);
/**
 * modules/corporates/list.php
 *
 * Corporate Accounts — list & manage
 * - Filters: status, search (name/contact/email)
 * - Actions: View / Edit / Delete / Toggle Active
 * - Safe CSRF for POST actions
 */

require_once dirname(__DIR__, 2) . '/config/functions.php';
require_role(['Admin','Ops','sales']);

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

$errors = [];
$notice = null;

/* ------------------------------------------------------------
 * POST actions: delete / toggle
 * ------------------------------------------------------------ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));

    $action = (string)($_POST['action'] ?? '');
    $id     = (int)($_POST['id'] ?? 0);
    if ($id <= 0) throw new RuntimeException('Invalid corporate ID.');

    if ($action === 'delete') {
      $del = db()->prepare("DELETE FROM corporates WHERE id=:id AND company_id=:cid LIMIT 1");
      $del->execute([':id'=>$id, ':cid'=>$cid]);
      audit_log('corporate.delete','corporate',$id,null);
      $notice = 'Corporate account deleted.';
    }

    if ($action === 'toggle_status') {
      $new = ($_POST['new_status'] ?? '') === 'inactive' ? 'inactive' : 'active';
      $upd = db()->prepare("UPDATE corporates SET status=:s, updated_at=NOW() WHERE id=:id AND company_id=:cid LIMIT 1");
      $upd->execute([':s'=>$new, ':id'=>$id, ':cid'=>$cid]);
      audit_log('corporate.toggle','corporate',$id,['status'=>$new]);
      $notice = 'Status updated.';
    }
  } catch (Throwable $e) {
    // FK or other DB error will be shown friendly in prod
    $errors[] = (defined('APP_ENV') && APP_ENV==='dev') ? $e->getMessage() : 'Action failed.';
  }
}

/* ------------------------------------------------------------
 * Filters
 * ------------------------------------------------------------ */
$status = isset($_GET['status']) && $_GET['status'] !== '' ? (string)$_GET['status'] : '';
$q      = isset($_GET['q']) ? trim((string)$_GET['q']) : '';

$where = ["c.company_id = :cid"];
$args  = [':cid' => $cid];

if ($status !== '') {
  $where[] = "c.status = :st";
  $args[':st'] = $status;
}
if ($q !== '') {
  $where[] = "(c.name LIKE :q OR c.contact_person LIKE :q OR c.email LIKE :q)";
  $args[':q'] = '%'.$q.'%';
}

/* ------------------------------------------------------------
 * Fetch corporates
 * ------------------------------------------------------------ */
$sql = "
  SELECT c.*
  FROM corporates c
  WHERE ".implode(' AND ', $where)."
  ORDER BY c.name ASC, c.id DESC
  LIMIT 500
";
$stmt = db()->prepare($sql);
$stmt->execute($args);
$rows = $stmt->fetchAll();

/* ------------------------------------------------------------
 * UI helpers
 * ------------------------------------------------------------ */
function badge_status_corp(string $s): string {
  $map = ['active'=>'success','inactive'=>'secondary'];
  $cls = $map[$s] ?? 'secondary';
  return '<span class="badge text-bg-'.e($cls).'">'.e(ucfirst($s)).'</span>';
}
function badge_cycle(string $s): string {
  $map = ['weekly'=>'info','monthly'=>'primary'];
  $cls = $map[$s] ?? 'secondary';
  return '<span class="badge text-bg-'.e($cls).'">'.e(ucfirst($s)).'</span>';
}

include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Corporate Accounts</h1>
  <div class="d-flex gap-2">
    <a href="<?= e(url_modules('corporates/add.php')) ?>" class="btn btn-dark">Add Corporate</a>
  </div>
</div>

<?php if ($notice): ?><div class="alert alert-success"><?= e($notice) ?></div><?php endif; ?>
<?php if ($errors): ?><div class="alert alert-danger"><ul class="mb-0"><?php foreach($errors as $er) echo '<li>'.e($er).'</li>'; ?></ul></div><?php endif; ?>

<!-- Filters -->
<div class="card shadow-sm mb-3">
  <div class="card-body">
    <form method="get" class="row g-2 align-items-end">
      <div class="col-md-3">
        <label class="form-label">Status</label>
        <select name="status" class="form-select">
          <option value="">— All —</option>
          <option value="active"   <?= $status==='active'?'selected':'' ?>>Active</option>
          <option value="inactive" <?= $status==='inactive'?'selected':'' ?>>Inactive</option>
        </select>
      </div>
      <div class="col-md-6">
        <label class="form-label">Search</label>
        <input class="form-control" name="q" placeholder="Name / Contact / Email" value="<?= e($q) ?>">
      </div>
      <div class="col-md-2 d-grid">
        <button class="btn btn-primary">Filter</button>
      </div>
      <div class="col-md-1 d-grid">
        <a class="btn btn-outline-secondary" href="list.php">Reset</a>
      </div>
    </form>
  </div>
</div>

<div class="card shadow-sm">
  <div class="card-body">
    <div class="table-responsive">
      <table class="table align-middle">
        <thead class="table-light">
          <tr>
            <th style="width:80px;">ID</th>
            <th>Company</th>
            <th>Contact</th>
            <th>Phone / Email</th>
            <th>Invoice Cycle</th>
            <th>Payment Terms</th>
            <th class="text-end" style="width:140px;">Credit Limit (£)</th>
            <th style="width:110px;">Status</th>
            <th style="width:260px;" class="text-end">Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($rows): foreach ($rows as $r): ?>
            <tr>
              <td>#<?= (int)$r['id'] ?></td>
              <td>
                <strong><?= e($r['name']) ?></strong>
                <?php if (!empty($r['billing_address'])): ?>
                  <div class="small text-muted"><?= nl2br(e($r['billing_address'])) ?></div>
                <?php endif; ?>
              </td>
              <td><?= e($r['contact_person'] ?? '—') ?></td>
              <td>
                <?php if (!empty($r['phone'])): ?><div><?= e($r['phone']) ?></div><?php endif; ?>
                <?php if (!empty($r['email'])): ?><div class="small text-muted"><?= e($r['email']) ?></div><?php endif; ?>
                <?php if (empty($r['phone']) && empty($r['email'])): ?>—<?php endif; ?>
              </td>
              <td><?= badge_cycle((string)($r['invoice_cycle'] ?? 'monthly')) ?></td>
              <td><?= e($r['payment_terms'] ?? '30 days') ?></td>
              <td class="text-end"><?= number_format((float)($r['credit_limit'] ?? 0), 2) ?></td>
              <td><?= badge_status_corp((string)($r['status'] ?? 'active')) ?></td>
              <td class="text-end">
                <div class="d-flex justify-content-end flex-wrap gap-1">
                  <a class="btn btn-sm btn-outline-secondary" href="<?= e(url_modules('corporates/view.php')).'?id='.(int)$r['id'] ?>">View</a>
                  <a class="btn btn-sm btn-outline-primary"   href="<?= e(url_modules('corporates/edit.php')).'?id='.(int)$r['id'] ?>">Edit</a>

                  <form method="post" class="d-inline">
                    <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                    <input type="hidden" name="action" value="toggle_status">
                    <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                    <input type="hidden" name="new_status" value="<?= ($r['status']==='active'?'inactive':'active') ?>">
                    <button class="btn btn-sm btn-outline-warning" title="Toggle Active">
                      <?= $r['status']==='active' ? 'Deactivate' : 'Activate' ?>
                    </button>
                  </form>

                  <form method="post" class="d-inline" onsubmit="return confirm('Delete this corporate account?');">
                    <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                    <button class="btn btn-sm btn-outline-danger">Delete</button>
                  </form>
                </div>
              </td>
            </tr>
          <?php endforeach; else: ?>
            <tr><td colspan="9" class="text-center text-muted py-4">No corporate accounts found.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php include dirname(__DIR__, 2) . '/includes/footer.php'; ?>
