<?php
declare(strict_types=1);
/**
 * modules/partners/list.php
 *
 * Partners CRM — grid with filters and inline Delete.
 *
 * Parts:
 *  1) Bootstrap & guards
 *  2) Handle POST actions (delete)
 *  3) Filters (GET)
 *  4) Fetch partners
 *  5) UI helpers
 *  6) Render: header, filters, table
 */

////////////////////////////////////////////////////////////////
// 1) Bootstrap & guards
////////////////////////////////////////////////////////////////
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;

////////////////////////////////////////////////////////////////
// 2) Handle POST actions (delete)
////////////////////////////////////////////////////////////////
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));

    if (($_POST['action'] ?? '') === 'delete') {
      $id = (int)($_POST['id'] ?? 0);
      if ($id <= 0) throw new RuntimeException('Invalid partner.');

      // If there is a FK with SET NULL we can delete safely.
      // If not, constraint will throw; we catch and show a friendly message.
      $del = db()->prepare("DELETE FROM partners WHERE id=:id AND company_id=:cid LIMIT 1");
      $del->execute([':id' => $id, ':cid' => $cid]);
      if ($del->rowCount() > 0) {
        audit_log('partner.delete', 'partner', $id, null);
        $notice = 'Partner deleted.';
      } else {
        $errors[] = 'Partner not found or already removed.';
      }
    }
  } catch (Throwable $e) {
    $msg = 'Unable to delete partner.';
    // Common FK error — provide hint
    if (str_contains(strtolower($e->getMessage()), 'foreign key') || str_contains(strtolower($e->getMessage()), 'constraint')) {
      $msg .= ' It is linked to existing records (e.g., bookings). Remove links first or deactivate instead.';
    }
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? ($msg . ' ['.$e->getMessage().']') : $msg;
  }
}

////////////////////////////////////////////////////////////////
// 3) Filters (GET)
////////////////////////////////////////////////////////////////
$q        = isset($_GET['q']) ? trim((string)$_GET['q']) : '';
$ctype    = isset($_GET['commission_type']) && $_GET['commission_type'] !== '' ? (string)$_GET['commission_type'] : '';
$hasNotes = isset($_GET['has_notes']) ? (string)$_GET['has_notes'] : ''; // '', 'yes', 'no'

////////////////////////////////////////////////////////////////
// 4) Fetch partners
////////////////////////////////////////////////////////////////
$where = ["p.company_id = :cid"];
$args  = [':cid' => $cid];

if ($q !== '') {
  $where[] = "(p.name LIKE :q OR p.contact_name LIKE :q OR p.phone LIKE :q OR p.email LIKE :q)";
  $args[':q'] = '%'.$q.'%';
}
if ($ctype !== '' && in_array($ctype, ['fixed','percent'], true)) {
  $where[] = "p.commission_type = :ct";
  $args[':ct'] = $ctype;
}
if ($hasNotes === 'yes') {
  $where[] = "p.notes IS NOT NULL AND p.notes <> ''";
} elseif ($hasNotes === 'no') {
  $where[] = "(p.notes IS NULL OR p.notes = '')";
}

$sql = "
  SELECT
    p.*,
    (
      SELECT COUNT(*) FROM bookings b
       WHERE b.company_id = p.company_id AND b.partner_id = p.id
    ) AS booking_count
  FROM partners p
  WHERE ".implode(' AND ', $where)."
  ORDER BY p.name ASC
  LIMIT 500
";
$stmt = db()->prepare($sql);
$stmt->execute($args);
$rows = $stmt->fetchAll();

////////////////////////////////////////////////////////////////
// 5) UI helpers
////////////////////////////////////////////////////////////////
function commission_label(?string $type, mixed $val): string {
  $type = $type ?? 'fixed';
  $num  = is_numeric($val) ? (float)$val : 0.0;
  if ($type === 'percent') return number_format($num, 2) . '%';
  return '£ ' . number_format($num, 2);
}
function safe_phone(?string $p): string {
  return $p ? '<a href="tel:'.e($p).'">'.e($p).'</a>' : '—';
}

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

<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Partners</h1>
  <div class="d-flex gap-2">
    <a href="<?= e(url_modules('partners/add.php')) ?>" class="btn btn-dark">Add Partner</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 $e) echo '<li>'.e($e).'</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-4">
        <label class="form-label">Search</label>
        <input class="form-control" name="q" placeholder="Name / Contact / Phone / Email" value="<?= e($q) ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">Commission Type</label>
        <select class="form-select" name="commission_type">
          <option value="">— All —</option>
          <option value="fixed"   <?= $ctype==='fixed'?'selected':'' ?>>Fixed amount</option>
          <option value="percent" <?= $ctype==='percent'?'selected':'' ?>>Percentage</option>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">Has Notes</label>
        <select class="form-select" name="has_notes">
          <option value="">— All —</option>
          <option value="yes" <?= $hasNotes==='yes'?'selected':'' ?>>Yes</option>
          <option value="no"  <?= $hasNotes==='no'?'selected':''  ?>>No</option>
        </select>
      </div>
      <div class="col-md-1 d-grid">
        <button class="btn btn-primary">Filter</button>
      </div>
      <div class="col-md-1 d-grid">
        <a href="list.php" class="btn btn-outline-secondary">Reset</a>
      </div>
    </form>
  </div>
</div>

<!-- Table -->
<div class="card shadow-sm">
  <div class="card-body">
    <div class="table-responsive">
      <table class="table align-middle">
        <thead class="table-light">
          <tr>
            <th>Name</th>
            <th>Contact</th>
            <th>Phone</th>
            <th>Email</th>
            <th class="text-end">Commission</th>
            <th class="text-center">Bookings</th>
            <th style="width:210px;" class="text-end">Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($rows): foreach ($rows as $r): ?>
            <tr>
              <td>
                <div class="fw-semibold"><?= e($r['name'] ?? '—') ?></div>
                <?php if (!empty($r['address'])): ?>
                  <div class="small text-muted"><?= e($r['address']) ?></div>
                <?php endif; ?>
              </td>
              <td>
                <?= e($r['contact_name'] ?: '—') ?>
              </td>
              <td><?= safe_phone($r['phone'] ?? null) ?></td>
              <td>
                <?php if (!empty($r['email'])): ?>
                  <a href="mailto:<?= e($r['email']) ?>"><?= e($r['email']) ?></a>
                <?php else: ?>—<?php endif; ?>
              </td>
              <td class="text-end">
                <span class="badge text-bg-dark">
                  <?= e(($r['commission_type'] === 'percent') ? 'Percent' : 'Fixed') ?>
                </span>
                <div><?= e(commission_label($r['commission_type'] ?? 'fixed', $r['commission_value'] ?? 0)) ?></div>
              </td>
              <td class="text-center">
                <span class="badge text-bg-secondary"><?= (int)($r['booking_count'] ?? 0) ?></span>
              </td>
              <td class="text-end">
                <div class="btn-group">
                  <a class="btn btn-sm btn-outline-secondary" href="<?= e(url_modules('partners/view.php')) . '?id=' . (int)$r['id'] ?>">View</a>
                  <a class="btn btn-sm btn-outline-primary" href="<?= e(url_modules('partners/edit.php')) . '?id=' . (int)$r['id'] ?>">Edit</a>
                  <form method="post" class="d-inline" onsubmit="return confirm('Delete this partner?');">
                    <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="7" class="text-center text-muted py-4">No partners found.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

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