<?php
declare(strict_types=1);

/**
 * modules/partners/delete.php
 *
 * Delete a Partner.
 *
 * Parts:
 *  1) Bootstrap & guards
 *  2) Fetch partner (+ usage counts for awareness)
 *  3) Handle POST (delete)
 *  4) Render confirmation
 */

////////////////////////////////////////////////////////////////
// 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'));

$pid = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
if ($pid <= 0) redirect(url_modules('partners/list.php'));

$errors = [];
$notice = null;

////////////////////////////////////////////////////////////////
// 2) Fetch partner (+ usage counts)
////////////////////////////////////////////////////////////////
$sel = db()->prepare("
  SELECT *
    FROM partners
   WHERE id=:id AND company_id=:cid
   LIMIT 1
");
$sel->execute([':id'=>$pid, ':cid'=>$cid]);
$partner = $sel->fetch();
if (!$partner) redirect(url_modules('partners/list.php'));

// Count references for awareness (won't block if FKs allow NULL/SET NULL)
$bookingCount = 0;
try {
  $qB = db()->prepare("SELECT COUNT(*) AS c FROM bookings WHERE company_id=:cid AND partner_id=:pid");
  $qB->execute([':cid'=>$cid, ':pid'=>$pid]);
  $bookingCount = (int)($qB->fetch()['c'] ?? 0);
} catch (Throwable $e) {
  // bookings table may vary — ignore
}

$quoteCount = 0;
try {
  $qQ = db()->prepare("SELECT COUNT(*) AS c FROM quotes WHERE company_id=:cid AND partner_id=:pid");
  $qQ->execute([':cid'=>$cid, ':pid'=>$pid]);
  $quoteCount = (int)($qQ->fetch()['c'] ?? 0);
} catch (Throwable $e) {
  // quotes table may not exist yet — ignore
}

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

    // Attempt delete
    $del = db()->prepare("DELETE FROM partners WHERE id=:id AND company_id=:cid LIMIT 1");
    $del->execute([':id'=>$pid, ':cid'=>$cid]);

    audit_log('partner.delete', 'partner', $pid, [
      'name'           => $partner['name'] ?? null,
      'booking_refs'   => $bookingCount,
      'quote_refs'     => $quoteCount,
    ]);

    // If bookings table has FK without SET NULL, this would fail at DB layer;
    // if you hit an integrity error, update your schema to ON DELETE SET NULL.
    redirect(url_modules('partners/list.php') . '?deleted=1');
  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev')
      ? $e->getMessage()
      : 'Unable to delete partner. It may be referenced by other records.';
  }
}

////////////////////////////////////////////////////////////////
// 4) Render confirmation
////////////////////////////////////////////////////////////////
include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Delete Partner</h1>
  <a href="<?= e(url_modules('partners/list.php')) ?>" class="btn btn-outline-secondary">Back to Partners</a>
</div>

<?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; ?>

<div class="card shadow-sm">
  <div class="card-body">
    <h2 class="h6 text-uppercase text-muted">Confirm Deletion</h2>
    <p class="mb-3">
      You are about to delete the partner:
      <strong><?= e($partner['name'] ?? '—') ?></strong>.
    </p>

    <div class="row g-3">
      <div class="col-md-4">
        <div class="p-3 border rounded bg-light h-100">
          <div class="small text-muted">Contact</div>
          <div><?= e($partner['contact_name'] ?? '—') ?></div>
          <div><?= e($partner['phone'] ?? '—') ?></div>
          <div><?= e($partner['email'] ?? '—') ?></div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="p-3 border rounded bg-light h-100">
          <div class="small text-muted">Commission</div>
          <div>
            <?php
              $ctype = $partner['commission_type'] ?? 'fixed';
              $cval  = (float)($partner['commission_value'] ?? 0);
              echo $ctype === 'percent'
                ? e(number_format($cval, 2)).'% of booking'
                : '£'.e(number_format($cval, 2)).' per booking';
            ?>
          </div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="p-3 border rounded bg-light h-100">
          <div class="small text-muted">References</div>
          <div>Bookings: <strong><?= (int)$bookingCount ?></strong></div>
          <div>Quotes:   <strong><?= (int)$quoteCount ?></strong></div>
          <div class="small text-muted mt-1">
            <?php if ($quoteCount > 0): ?>
              Quotes will retain history; depending on your schema they may auto-null partner.
            <?php else: ?>
              No quotes referencing this partner.
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>

    <hr>

    <div class="alert alert-warning">
      <strong>Warning:</strong> This action cannot be undone.
      <?php if ($bookingCount > 0): ?>
        If your <em>bookings</em> table enforces a foreign key without <code>ON DELETE SET NULL</code>,
        deletion may fail. Consider updating your schema.
      <?php endif; ?>
    </div>

    <form method="post" class="d-flex gap-2">
      <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
      <input type="hidden" name="id" value="<?= (int)$pid ?>">
      <button class="btn btn-danger">Delete Partner</button>
      <a class="btn btn-outline-secondary" href="<?= e(url_modules('partners/list.php')) ?>">Cancel</a>
    </form>
  </div>
</div>

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