<?php
declare(strict_types=1);

/**
 * modules/payments/partners_bulk.php
 *
 * End-of-month (or range-based) BULK partner payments.
 * - Pick Partner + Period → list eligible bookings and their outstanding partner due.
 * - Select bookings (default all), enter one payment (paid_at, method, reference, notes).
 * - We allocate the single payment across selected bookings oldest-first (or accept per-row overrides).
 * - One accounting row in `transactions` (PARTNER_PAYOUT, segment='Chauffeur', expense).
 * - One row per booking in `partner_payouts` with common batch_ref.
 * - Printable receipt at partner_receipt.php?batch_ref=...
 * - “Bank” modal to preview partner profile + bank details before paying.
 */

require_once dirname(__DIR__, 2) . '/config/functions.php';
require_role(['MD','Accounts','Admin','Management']);

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

$errors = [];
$notice = null;

/* -----------------------------
   Helpers
------------------------------*/
function tbl_exists(string $t): bool {
  try { db()->query("SELECT 1 FROM `{$t}` LIMIT 1"); return true; }
  catch (Throwable) { return false; }
}

/** Parse bank details (JSON or "Label: value" lines). */
function parse_bank_details(?string $raw): array {
  $out = [
    'bank_name'      => '',
    'account_name'   => '',
    'account_number' => '',
    'sort_code'      => '',
    'iban'           => '',
    'swift'          => '',
    'notes'          => '',
    'raw'            => '',
  ];
  if (!$raw) return $out;
  $s = trim((string)$raw);

  // JSON?
  $j = json_decode($s, true);
  if (is_array($j)) {
    foreach (['bank_name','account_name','account_number','sort_code','iban','swift','notes'] as $k) {
      if (isset($j[$k]) && is_string($j[$k])) $out[$k] = trim((string)$j[$k]);
    }
    return $out;
  }

  // Label: value fallbacks (handles many synonyms)
  foreach (preg_split('/\r\n|\r|\n/', $s) as $line) {
    $line = trim($line);
    if ($line === '') continue;
    if (preg_match('/^(bank\s*name)\s*[:\-]\s*(.+)$/i', $line, $m))                     { $out['bank_name'] = trim($m[2]); continue; }
    if (preg_match('/^(account\s*name|account\s*holder)\s*[:\-]\s*(.+)$/i', $line, $m)) { $out['account_name'] = trim($m[2]); continue; }
    if (preg_match('/^(account\s*number|acc(?:ount)?\.?|acc)\s*[:\-]\s*(.+)$/i', $line, $m)) { $out['account_number'] = trim($m[2]); continue; }
    if (preg_match('/^(sort\s*code|sort)\s*[:\-]\s*([A-Za-z0-9\-\s]+)$/i', $line, $m))  { $out['sort_code'] = trim($m[2]); continue; }
    if (preg_match('/^(iban)\s*[:\-]\s*(.+)$/i', $line, $m))                            { $out['iban'] = trim($m[2]); continue; }
    if (preg_match('/^(swift|bic)\s*[:\-]\s*(.+)$/i', $line, $m))                       { $out['swift'] = trim($m[2]); continue; }
    $out['raw'] .= ($out['raw'] ? "\n" : "") . $line;
  }
  return $out;
}

/** Normalize datetime-local input to SQL DATETIME ("Y-m-d H:i:s"). */
function dt_local_to_sql(string $v): string {
  $v = trim($v);
  if ($v === '') return date('Y-m-d H:i:s');
  $v = str_replace('T', ' ', $v);
  // If seconds missing, append :00
  if (preg_match('/^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}$/', $v)) $v .= ':00';
  return $v;
}

/** Generate a batch reference for this company/partner/month. */
function gen_batch_ref(int $cid, int $partnerId): string {
  $yymm = date('Ym');
  return sprintf('PP-%d-%d-%s-%04d', $cid, $partnerId, $yymm, random_int(0, 9999));
}

/**
 * Return a safe SQL expression for partner due using only columns that exist in `bookings`.
 * We try common possibilities and COALESCE them. Aliased as $alias.
 */
function partner_due_expr(string $alias='partner_due'): string {
  static $have = null;
  if ($have === null) {
    $have = [];
    try {
      $rs = db()->query("SHOW COLUMNS FROM bookings");
      foreach ($rs->fetchAll() as $c) {
        $have[strtolower((string)$c['Field'])] = true;
      }
    } catch (Throwable) { $have = []; }
  }
  $cands = [
    'partner_due',
    'partner_amount',
    'partner_commission_amount',
    'partner_commission',
    'partner_fee',
    'partner_total',
    'total_partner_price',
  ];
  $cols = [];
  foreach ($cands as $c) if (isset($have[strtolower($c)])) $cols[] = "b.`{$c}`";
  if (!$cols) return "0 AS {$alias}";
  return 'COALESCE(' . implode(',', $cols) . ") AS {$alias}";
}

/* -----------------------------
   Inputs & defaults
------------------------------*/
$partners = [];
try {
  $q = db()->prepare("SELECT id, name FROM partners WHERE company_id=:cid ORDER BY name ASC");
  $q->execute([':cid'=>$cid]);
  $partners = $q->fetchAll() ?: [];
} catch (Throwable) {}

$today      = new DateTimeImmutable('today');
$firstPrev  = $today->modify('first day of previous month');
$lastPrev   = $today->modify('last day of previous month');

$partnerId  = (int)($_GET['partner_id'] ?? $_POST['partner_id'] ?? 0);
$from       = (string)($_GET['from'] ?? $_POST['from'] ?? $firstPrev->format('Y-m-01'));
$to         = (string)($_GET['to']   ?? $_POST['to']   ?? $lastPrev->format('Y-m-d'));

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $from)) $from = $firstPrev->format('Y-m-01');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $to))   $to   = $lastPrev->format('Y-m-d');

/* -----------------------------
   AJAX: Partner bank details (modal)
------------------------------*/
if (($_GET['fetch_bank'] ?? '') === '1' && isset($_GET['partner_id'])) {
  header('Content-Type: text/html; charset=utf-8');
  try {
    $pid = (int)$_GET['partner_id'];
    $q = db()->prepare("SELECT name, contact_name, phone, email, bank_details, address FROM partners WHERE company_id=:cid AND id=:id LIMIT 1");
    $q->execute([':cid'=>$cid, ':id'=>$pid]);
    if ($p = $q->fetch()) {
      $b = parse_bank_details((string)($p['bank_details'] ?? ''));
      ?>
      <div class="mb-2">
        <div class="fw-semibold" style="font-size:1.05rem"><?= e($p['name'] ?? '') ?></div>
        <div class="small text-muted">
          <?= e($p['contact_name'] ?? '—') ?> · <?= e($p['email'] ?? '—') ?><?php if(!empty($p['phone'])): ?> · <?= e($p['phone']) ?><?php endif; ?>
        </div>
        <?php if (!empty($p['address'])): ?>
          <div class="small text-muted"><?= nl2br(e((string)$p['address'])) ?></div>
        <?php endif; ?>
      </div>
      <table class="table table-sm align-middle mb-0">
        <tbody>
          <tr><th style="width:35%;">Bank</th><td><?= e($b['bank_name'] ?: '—') ?></td></tr>
          <tr><th>Account Holder</th><td><?= e($b['account_name'] ?: '—') ?></td></tr>
          <tr><th>Account Number</th><td><?= e($b['account_number'] ?: '—') ?></td></tr>
          <tr><th>Sort Code</th><td><?= e($b['sort_code'] ?: '—') ?></td></tr>
          <tr><th>IBAN</th><td><?= e($b['iban'] ?: '—') ?></td></tr>
          <tr><th>SWIFT</th><td><?= e($b['swift'] ?: '—') ?></td></tr>
          <?php if (!empty($b['raw'])): ?>
          <tr><th>Additional</th><td><pre class="mb-0" style="white-space:pre-wrap"><?= e($b['raw']) ?></pre></td></tr>
          <?php endif; ?>
          <?php if (!empty($b['notes'])): ?>
          <tr><th>Notes</th><td><?= nl2br(e($b['notes'])) ?></td></tr>
          <?php endif; ?>
        </tbody>
      </table>
      <?php
    } else {
      echo '<div class="text-muted">Not found.</div>';
    }
  } catch (Throwable $e) {
    http_response_code(500);
    echo (defined('APP_ENV') && APP_ENV==='dev') ? e($e->getMessage()) : 'Error';
  }
  exit;
}

/* -----------------------------
   Query eligible bookings
------------------------------*/
$rows = [];
$partner = null;
$hasPayouts = tbl_exists('partner_payouts');

if ($partnerId > 0) {
  try {
    $p = db()->prepare("SELECT id, name, bank_details, contact_name, phone, email FROM partners WHERE id=:id AND company_id=:cid LIMIT 1");
    $p->execute([':id'=>$partnerId, ':cid'=>$cid]);
    $partner = $p->fetch() ?: null;
    if (!$partner) $errors[] = 'Partner not found or access denied.';

    $paidSumSQL = $hasPayouts
      ? "(SELECT COALESCE(SUM(pp.amount),0) FROM partner_payouts pp WHERE pp.company_id=b.company_id AND pp.booking_id=b.id)"
      : "0";

    $sql = "
      SELECT
        b.id,
        b.booking_ref,
        b.client_name,
        b.pickup_date,
        b.pickup_time,
        b.partner_id,
        " . partner_due_expr('partner_due') . ",
        {$paidSumSQL} AS paid_sum
      FROM bookings b
      WHERE b.company_id=:cid
        AND b.partner_id=:pid
        AND b.status='Completed'
        AND b.pickup_date BETWEEN :f AND :t
      ORDER BY b.pickup_date ASC, b.pickup_time ASC, b.id ASC
      LIMIT 1000
    ";
    $q = db()->prepare($sql);
    $q->execute([':cid'=>$cid, ':pid'=>$partnerId, ':f'=>$from, ':t'=>$to]);
    $rows = $q->fetchAll() ?: [];
  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV==='dev') ? $e->getMessage() : 'Unable to load partner bookings.';
  }
}

/* -----------------------------
   POST: Bulk pay
------------------------------*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'bulk_pay' && $partnerId > 0 && !$errors) {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));

    if (!$hasPayouts) throw new RuntimeException('partner_payouts table is missing. Please create it before bulk paying.');

    $selected = array_map('intval', (array)($_POST['selected'] ?? []));
    if (!$selected) throw new RuntimeException('No bookings selected.');

    $allocRaw = (array)($_POST['alloc'] ?? []);
    $alloc    = [];
    foreach ($allocRaw as $bid => $v) {
      $bid = (int)$bid;
      $amt = (float)$v;
      if ($amt > 0) $alloc[$bid] = round($amt, 2);
    }

    $paidAt  = dt_local_to_sql((string)($_POST['paid_at'] ?? ''));
    $method  = trim((string)($_POST['method'] ?? 'Bank Transfer'));
    $ref     = trim((string)($_POST['reference'] ?? ''));
    $notes   = trim((string)($_POST['notes'] ?? ''));

    // Re-query selected bookings with safe partner_due
    $paidSumSQL = $hasPayouts
      ? "(SELECT COALESCE(SUM(pp.amount),0) FROM partner_payouts pp WHERE pp.company_id=b.company_id AND pp.booking_id=b.id)"
      : "0";

    $inPlaceholders = implode(',', array_fill(0, count($selected), '?'));
    $sql = "
      SELECT
        b.id,
        b.booking_ref,
        " . partner_due_expr('partner_due') . ",
        {$paidSumSQL} AS paid_sum
      FROM bookings b
      WHERE b.company_id=?
        AND b.partner_id=?
        AND b.status='Completed'
        AND b.pickup_date BETWEEN ? AND ?
        AND b.id IN ($inPlaceholders)
      ORDER BY b.pickup_date ASC, b.pickup_time ASC, b.id ASC
    ";
    $args = array_merge([$cid, $partnerId, $from, $to], $selected);
    $stmt = db()->prepare($sql);
    $stmt->execute($args);
    $books = $stmt->fetchAll();

    if (!$books) throw new RuntimeException('No valid bookings found for selection.');

    // Build outstanding list
    $items = [];
    $grandOutstanding = 0.0;
    foreach ($books as $b) {
      $due  = (float)$b['partner_due'];
      $paid = (float)$b['paid_sum'];
      $out  = max(0.0, round($due - $paid, 2));
      if ($out <= 0) continue;
      $items[] = ['id' => (int)$b['id'], 'ref' => (string)($b['booking_ref'] ?? ('#'.$b['id'])), 'out' => $out];
      $grandOutstanding += $out;
    }
    if (!$items) throw new RuntimeException('Nothing outstanding to pay for the selected bookings.');

    $totalInput = $_POST['total_pay'] ?? '';
    $useManual  = !empty($alloc);

    if ($useManual) {
      $sumManual = 0.0;
      $allowed   = [];
      $byId = [];
      foreach ($items as $it) $byId[$it['id']] = $it['out'];
      foreach ($alloc as $bid => $amt) {
        if (!isset($byId[$bid])) continue;
        $cap = $byId[$bid];
        if ($amt > $cap + 0.0001) throw new RuntimeException("Allocation for booking #$bid exceeds outstanding.");
        if ($amt > 0) {
          $allowed[$bid] = round($amt,2);
          $sumManual += $allowed[$bid];
        }
      }
      if ($sumManual <= 0) throw new RuntimeException('Allocation sum must be positive.');
      $finalAlloc = $allowed;
      $batchTotal = round($sumManual, 2);
    } else {
      $want = (float)$totalInput;
      if ($want <= 0 || $totalInput === '') $want = $grandOutstanding;
      $want = min($want, $grandOutstanding);
      $left = $want;
      $finalAlloc = [];
      foreach ($items as $it) {
        if ($left <= 0.0001) break;
        $take = min($it['out'], $left);
        if ($take > 0) {
          $finalAlloc[$it['id']] = round($take, 2);
          $left -= $take;
        }
      }
      $batchTotal = round($want - max(0.0,$left), 2);
      if ($batchTotal <= 0) throw new RuntimeException('Nothing to allocate.');
    }

    $batchRef = gen_batch_ref($cid, $partnerId);

    $pdo = db();
    $pdo->beginTransaction();

    // 1) transactions (single batch row) — segment ALWAYS 'Chauffeur'
    if (!tbl_exists('transactions')) throw new RuntimeException('transactions table missing.');
    $tx = $pdo->prepare("
      INSERT INTO transactions
        (company_id, `date`, account_code, segment, `type`, amount,
         booking_id, rental_id, invoice_id, reference, milestone, notes, attachment_url, created_at)
      VALUES
        (:cid, DATE(:paid_at), 'PARTNER_PAYOUT', 'Chauffeur', 'expense',
         :amt, NULL, NULL, NULL, :ref, NULL, :notes, NULL, NOW())
    ");
    $tx->execute([
      ':cid'     => $cid,
      ':paid_at' => $paidAt,
      ':amt'     => $batchTotal,
      ':ref'     => ($ref !== '' ? $ref.' ' : '').('['.$batchRef.'] Partner Payment'),
      ':notes'   => $notes !== '' ? $notes : null,
    ]);
    if ($tx->rowCount() !== 1) throw new RuntimeException('Accounting entry not recorded.');

    // 2) partner_payouts rows
    $pp = $pdo->prepare("
      INSERT INTO partner_payouts
        (company_id, partner_id, booking_id, amount, paid_at, method, reference, notes, batch_ref, created_at)
      VALUES
        (:cid, :pid, :bid, :amt, :paid_at, :method, :ref, :notes, :batch, NOW())
    ");

    // 3) pending_payments maintenance (optional)
    $hasPending = tbl_exists('pending_payments');
    $delPend = $hasPending ? $pdo->prepare("DELETE FROM pending_payments WHERE company_id=:cid AND booking_id=:bid AND `type`='partner'") : null;
    $insPend = $hasPending ? $pdo->prepare("
      INSERT INTO pending_payments
        (company_id, booking_id, booking_ref, `type`, total_due, amount_paid, balance_due, status, created_at)
      VALUES
        (:cid, :bid, :ref, 'partner', :total, :paid, :bal, 'pending', NOW())
    ") : null;

    // helper to recompute each booking's due/paid after each insertion
    $getOne = $pdo->prepare("
      SELECT
        " . partner_due_expr('partner_due') . ",
        " . ($hasPayouts
              ? "(SELECT COALESCE(SUM(pp.amount),0) FROM partner_payouts pp WHERE pp.company_id=b.company_id AND pp.booking_id=b.id)"
              : "0"
            ) . " AS paid_sum,
        b.booking_ref
      FROM bookings b
      WHERE b.company_id=:cid AND b.id=:bid
      LIMIT 1
    ");

    foreach ($finalAlloc as $bid => $amt) {
      if ($amt <= 0) continue;

      $pp->execute([
        ':cid'=>$cid, ':pid'=>$partnerId, ':bid'=>$bid,
        ':amt'=>$amt, ':paid_at'=>$paidAt,
        ':method'=>$method !== '' ? $method : null,
        ':ref'   =>$ref !== '' ? $ref : null,
        ':notes' =>$notes !== '' ? $notes : null,
        ':batch' =>$batchRef,
      ]);

      if ($hasPending) {
        $getOne->execute([':cid'=>$cid, ':bid'=>$bid]);
        $row = $getOne->fetch() ?: [];
        $due  = (float)($row['partner_due'] ?? 0);
        $paid = (float)($row['paid_sum'] ?? 0); // includes just-inserted amt
        $bal  = max(0.0, round($due - $paid, 2));
        $refB = (string)($row['booking_ref'] ?? ('#'.$bid));
        $delPend->execute([':cid'=>$cid, ':bid'=>$bid]);
        if ($bal > 0) {
          $insPend->execute([
            ':cid'=>$cid, ':bid'=>$bid, ':ref'=>$refB,
            ':total'=>round($due,2), ':paid'=>round($paid,2), ':bal'=>$bal
          ]);
        }
      }
    }

    audit_log('payout.partner.bulk','partner',$partnerId,[
      'batch_ref'=>$batchRef,'period'=>[$from,$to],
      'bookings_count'=>count($finalAlloc),'total_paid'=>$batchTotal,
      'paid_at'=>$paidAt,'method'=>$method,'reference'=>$ref
    ]);

    $pdo->commit();

    $qs = http_build_query(['batch_ref'=>$batchRef]);
    redirect(url_modules('payments/partner_receipt.php').'?'.$qs);

  } catch (Throwable $e) {
    if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
    $errors[] = (defined('APP_ENV') && APP_ENV==='dev') ? $e->getMessage() : 'Unable to record partner payment.';
  }
}

/* -----------------------------
   Totals for display
------------------------------*/
$totalDue = 0.0; $totalPaid = 0.0; $totalOut = 0.0;
foreach ($rows as $r) {
  $d = (float)$r['partner_due'];
  $p = (float)$r['paid_sum'];
  $o = max(0.0, $d - $p);
  $totalDue  += $d;
  $totalPaid += $p;
  $totalOut  += $o;
}

/* -----------------------------
   Render
------------------------------*/
include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h1 class="h4 mb-0">Partner Payments (Bulk)</h1>
    <div class="text-muted">Select a partner and period, then pay multiple bookings in one go.</div>
  </div>
  <div class="d-flex flex-wrap gap-2">
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('dashboard/md.php')) ?>">← MD Dashboard</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; ?>

<div class="card shadow-sm mb-3">
  <div class="card-body">
    <form class="row g-2 align-items-end" method="get">
      <div class="col-md-4">
        <label class="form-label">Partner</label>
        <select class="form-select" name="partner_id" required>
          <option value="0">— Select Partner —</option>
          <?php foreach($partners as $p): ?>
            <option value="<?= (int)$p['id'] ?>" <?= $partnerId===(int)$p['id']?'selected':'' ?>>
              <?= e($p['name'] ?? ('#'.$p['id'])) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">From</label>
        <input type="date" class="form-control" name="from" value="<?= e($from) ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">To</label>
        <input type="date" class="form-control" name="to" value="<?= e($to) ?>">
      </div>
      <div class="col-md-2 d-grid">
        <button class="btn btn-primary">Load</button>
      </div>
    </form>
  </div>
</div>

<?php if ($partnerId>0): ?>
  <form method="post" class="card shadow-sm mb-4">
    <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
    <input type="hidden" name="action" value="bulk_pay">
    <input type="hidden" name="partner_id" value="<?= (int)$partnerId ?>">
    <input type="hidden" name="from" value="<?= e($from) ?>">
    <input type="hidden" name="to" value="<?= e($to) ?>">

    <div class="card-body">
      <div class="d-flex justify-content-between align-items-start mb-3">
        <div>
          <div class="fw-semibold" style="font-size:1.05rem">
            <?= e($partner['name'] ?? '—') ?>
            <button type="button" class="btn btn-sm btn-outline-secondary ms-2 js-bank" data-partner-id="<?= (int)$partnerId ?>">Bank</button>
          </div>
          <div class="small text-muted">Period: <?= e($from) ?> → <?= e($to) ?></div>
        </div>
        <div class="text-end">
          <div class="small text-muted">Totals (filtered)</div>
          <div>Due: <strong>£<?= number_format($totalDue,2) ?></strong> · Already Paid: <strong>£<?= number_format($totalPaid,2) ?></strong></div>
          <div>Outstanding: <span class="badge text-bg-dark">£<?= number_format($totalOut,2) ?></span></div>
        </div>
      </div>

      <div class="alert alert-info">
        <div class="mb-1"><strong>Allocation:</strong> Leave per-row fields empty to auto-allocate oldest-first. Or fill any rows to force a manual allocation.</div>
        <div class="mb-0"><strong>Total to pay (optional):</strong> <input type="number" step="0.01" name="total_pay" class="form-control d-inline-block" style="width:160px" placeholder="e.g. <?= e(number_format($totalOut,2,'.','')) ?>"> If blank, we’ll pay the full outstanding of selected bookings.</div>
      </div>

      <div class="table-responsive">
        <table class="table align-middle">
          <thead class="table-light">
            <tr>
              <th style="width:38px"><input type="checkbox" id="sel_all" <?= $rows?'checked':'' ?>></th>
              <th>Booking</th>
              <th>Client</th>
              <th>Pickup</th>
              <th class="text-end">£ Due</th>
              <th class="text-end">£ Paid</th>
              <th class="text-end">£ Outstanding</th>
              <th class="text-end" style="width:180px">£ Allocate (optional)</th>
            </tr>
          </thead>
          <tbody>
          <?php if ($rows): foreach ($rows as $r):
            $due = (float)$r['partner_due']; $paid = (float)$r['paid_sum']; $out = max(0.0, $due-$paid);
            if ($out <= 0) continue;
          ?>
            <tr>
              <td><input type="checkbox" name="selected[]" value="<?= (int)$r['id'] ?>" class="js-row" checked></td>
              <td><div class="fw-semibold"><?= e($r['booking_ref'] ?? ('#'.$r['id'])) ?></div></td>
              <td><?= e($r['client_name'] ?? '—') ?></td>
              <td><?= e(trim(($r['pickup_date'] ?? '').' '.($r['pickup_time'] ?? ''))) ?></td>
              <td class="text-end">£<?= number_format($due,2) ?></td>
              <td class="text-end">£<?= number_format($paid,2) ?></td>
              <td class="text-end fw-semibold">£<?= number_format($out,2) ?></td>
              <td class="text-end">
                <input type="number" step="0.01" min="0.00" class="form-control text-end" name="alloc[<?= (int)$r['id'] ?>]" placeholder="">
              </td>
            </tr>
          <?php endforeach; else: ?>
            <tr><td colspan="8" class="text-center text-muted py-4">No outstanding partner dues in this period.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>

      <div class="row g-3 mt-2">
        <div class="col-md-3">
          <label class="form-label">Paid At</label>
          <input type="datetime-local" class="form-control" name="paid_at" value="<?= e(date('Y-m-d\TH:i')) ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label">Method</label>
          <input class="form-control" name="method" value="Bank Transfer">
        </div>
        <div class="col-md-3">
          <label class="form-label">Reference</label>
          <input class="form-control" name="reference" placeholder="Batch reference">
        </div>
        <div class="col-md-3">
          <label class="form-label">Notes</label>
          <input class="form-control" name="notes" placeholder="Optional">
        </div>
      </div>

    </div>
    <div class="card-footer d-flex justify-content-between align-items-center">
      <div class="small text-muted">Tip: If you leave “Total to pay” blank we’ll pay the full outstanding of the selected bookings.</div>
      <div class="d-flex gap-2">
        <a class="btn btn-outline-secondary" href="<?= e(url_modules('payments/partners.php')) ?>">Cancel</a>
        <button class="btn btn-dark">Pay Selected</button>
      </div>
    </div>
  </form>
<?php endif; ?>

<!-- Partner Bank Modal -->
<div class="modal fade" id="partnerBankModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-md">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Partner Bank Details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" id="partnerBankBody">Loading…</div>
    </div>
  </div>
</div>

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

<script>
(function(){
  // Select all
  const all = document.getElementById('sel_all');
  if (all) {
    all.addEventListener('change', function(){
      document.querySelectorAll('.js-row').forEach(cb => cb.checked = all.checked);
    });
  }

  // Bank modal
  const bankModal = new bootstrap.Modal(document.getElementById('partnerBankModal'));
  const bankBody  = document.getElementById('partnerBankBody');

  document.addEventListener('click', async function(e){
    const btn = e.target.closest('.js-bank'); if(!btn) return;
    const id = btn.getAttribute('data-partner-id');
    bankBody.textContent = 'Loading…';
    try{
      const res = await fetch('partners_bulk.php?fetch_bank=1&partner_id='+encodeURIComponent(id), {headers:{'X-Requested-With':'XMLHttpRequest'}});
      if(!res.ok) throw new Error('HTTP '+res.status);
      bankBody.innerHTML = await res.text();
    }catch(err){
      console.error(err);
      bankBody.innerHTML = '<div class="text-danger">Unable to load bank details.</div>';
    }
    bankModal.show();
  });
})();
</script>
