<?php
declare(strict_types=1);

/**
 * modules/payments/partners.php
 *
 * Partner Commission Payouts — review & mark bookings as paid to partners.
 *
 * Rules:
 *  1) Show bookings with partner_id NOT NULL and status='Completed'
 *  2) Commission:
 *       - percent  -> (partners.commission_value / 100) * bookings.total_client_price
 *       - fixed    -> bookings.partner_commission_amount
 *  3) Paying:
 *       - Always insert into partner_payouts
 *       - Always insert into transactions (expense, account_code='PARTNER_PAYOUT', segment='Chauffeur')
 *       - If partial: upsert a pending_payments row (type='commission') for remaining balance
 *       - If fully paid: delete any pending row (type='commission')
 *
 * Notes:
 *  - pending_payments.type ENUM is ('client','driver','commission'), so we store 'commission'
 *    for partner commissions (using 'partner' would violate ENUM).
 */

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

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

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

  // Try JSON first
  $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;
  }

  // Fallback parse lines
  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*([0-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;
}

/** Best-effort ensure pending_payments exists (won't error if already there) */
if (!tbl_exists('pending_payments')) {
  try {
    db()->exec("
      CREATE TABLE IF NOT EXISTS pending_payments (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        company_id INT(10) UNSIGNED NOT NULL,
        booking_id BIGINT(20) UNSIGNED NOT NULL,
        booking_ref VARCHAR(128) NOT NULL,
        type ENUM('client','driver','commission') NOT NULL DEFAULT 'client',
        total_due DECIMAL(10,2) NOT NULL DEFAULT 0.00,
        amount_paid DECIMAL(10,2) NOT NULL DEFAULT 0.00,
        balance_due DECIMAL(10,2) NOT NULL DEFAULT 0.00,
        status VARCHAR(32) NOT NULL DEFAULT 'pending',
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        KEY idx_company_booking (company_id, booking_id),
        KEY idx_type (type)
      ) ENGINE=MyISAM DEFAULT CHARSET=latin1
    ");
  } catch (Throwable $e) { /* ignore */ }
}

//////////////////////////////////////////////////
// 3) AJAX: Partner Bank popup (single partner)
//////////////////////////////////////////////////
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, email, phone, commission_type, commission_value, bank_details, address, notes
      FROM partners
      WHERE id=:id AND company_id=:cid
      LIMIT 1
    ");
    $q->execute([':id'=>$pid, ':cid'=>$cid]);
    if ($p = $q->fetch()) {
      $b = parse_partner_bank((string)($p['bank_details'] ?? ''));
      ?>
      <div class="mb-2">
        <div class="fw-semibold" style="font-size:1.05rem"><?= e($p['name']) ?></div>
        <div class="text-muted small">
          <?php if (!empty($p['contact_name'])): ?>Contact: <?= e($p['contact_name']) ?> · <?php endif; ?>
          <?php if (!empty($p['email'])): ?><?= e($p['email']) ?> · <?php endif; ?>
          <?php if (!empty($p['phone'])): ?><?= e($p['phone']) ?><?php endif; ?>
        </div>
      </div>
      <div class="table-responsive">
        <table class="table table-sm align-middle">
          <tbody>
            <tr><th style="width:220px">Commission</th>
              <td><?= e(ucfirst((string)$p['commission_type'])) ?>
                 <?= ' — '.e(number_format((float)$p['commission_value'],2)).(($p['commission_type']??'')==='percent'?'%':'') ?>
              </td>
            </tr>
            <?php if (!empty($p['address'])): ?>
              <tr><th>Address</th><td><?= nl2br(e($p['address'])) ?></td></tr>
            <?php endif; ?>
            <tr><th>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($p['notes'])): ?>
              <tr><th>Notes</th><td><?= nl2br(e($p['notes'])) ?></td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
      <?php
    } else {
      echo '<div class="text-muted">Partner not found.</div>';
    }
  } catch (Throwable $e) {
    http_response_code(500);
    echo (defined('APP_ENV') && APP_ENV==='dev') ? e($e->getMessage()) : 'Error loading partner details.';
  }
  exit;
}

//////////////////////////////////////////////////
// 4) Filters
//////////////////////////////////////////////////
$today      = new DateTimeImmutable('today');
$monthStart = $today->modify('first day of this month');
$monthEnd   = $today->modify('last day of this month');

$from    = (string)($_GET['from'] ?? $monthStart->format('Y-m-01'));
$to      = (string)($_GET['to']   ?? $monthEnd->format('Y-m-d'));
$status  = (string)($_GET['status'] ?? 'unpaid'); // unpaid|paid|all
$q       = trim((string)($_GET['q'] ?? ''));
$partner = (int)($_GET['partner'] ?? 0);

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $from)) $from = $monthStart->format('Y-m-d');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $to))   $to   = $monthEnd->format('Y-m-d');
if (!in_array($status, ['unpaid','paid','all'], true)) $status = 'unpaid';

//////////////////////////////////////////////////
// 5) Query: Completed + Partner + Commission calc
//////////////////////////////////////////////////
$rows = [];
$summary = ['due'=>0.00,'paid'=>0.00,'outstanding'=>0.00];

try {
  $hasPayouts = tbl_exists('partner_payouts');

  $where = [
    "b.company_id = :cid",
    "b.pickup_date BETWEEN :from AND :to",
    "b.status = 'Completed'",
    "b.partner_id IS NOT NULL"
  ];
  $args = [':cid'=>$cid, ':from'=>$from, ':to'=>$to];

  if ($q !== '') {
    // unique placeholders (avoid HY093)
    $where[] = "(b.booking_ref LIKE :q1 OR b.client_name LIKE :q2 OR p.name LIKE :q3)";
    $like = '%'.$q.'%';
    $args[':q1'] = $like;
    $args[':q2'] = $like;
    $args[':q3'] = $like;
  }
  if ($partner > 0) {
    $where[] = "b.partner_id = :pid";
    $args[':pid'] = $partner;
  }

  // Inner: compute commission_due & paid_sum
  $inner = "
    SELECT
      b.id,
      b.booking_ref,
      b.client_name,
      b.pickup_date,
      b.pickup_time,
      p.id   AS partner_id,
      p.name AS partner_name,
      p.commission_type,
      p.commission_value,

      /* Commission rules */
      GREATEST(0.00,
        ROUND(
          CASE
            WHEN p.commission_type = 'percent'
              THEN (COALESCE(p.commission_value,0) / 100.0) * COALESCE(b.total_client_price,0)
            ELSE
              COALESCE(b.partner_commission_amount,0)
          END, 2
        )
      ) AS commission_due,

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

    FROM bookings b
    INNER JOIN partners p ON p.id = b.partner_id
    WHERE ".implode(' AND ', $where)."
  ";

  // Outer: compute outstanding and filter by status
  $outer = "
    SELECT t.*,
           GREATEST(t.commission_due - t.paid_sum, 0) AS outstanding
      FROM ( $inner ) t
  ";
  if ($status === 'unpaid')       $outer .= " HAVING outstanding > 0.0001 ";
  elseif ($status === 'paid')     $outer .= " HAVING outstanding < 0.0001 ";
  // 'all' -> no HAVING
  $outer .= " ORDER BY t.pickup_date DESC, t.pickup_time DESC, t.id DESC LIMIT 300 ";

  $stmt = db()->prepare($outer);
  $stmt->execute($args);
  $rows = $stmt->fetchAll();

  foreach ($rows as $r) {
    $summary['due']        += (float)$r['commission_due'];
    $summary['paid']       += (float)$r['paid_sum'];
    $summary['outstanding']+= max(0, (float)$r['commission_due'] - (float)$r['paid_sum']);
  }
} catch (Throwable $e) {
  $errors[] = (defined('APP_ENV') && APP_ENV==='dev') ? $e->getMessage() : 'Unable to load partner payouts.';
}

//////////////////////////////////////////////////
// 6) POST: mark as paid (transactions + pending)
//////////////////////////////////////////////////
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'mark_paid') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));

    $bid   = (int)($_POST['booking_id'] ?? 0);
    $pid   = (int)($_POST['partner_id'] ?? 0);
    $amt   = (float)($_POST['amount'] ?? 0);
    $when  = (string)($_POST['paid_at'] ?? '');
    $meth  = trim((string)($_POST['method'] ?? 'Bank Transfer'));
    $ref   = trim((string)($_POST['reference'] ?? ''));
    $notes = trim((string)($_POST['notes'] ?? ''));

    if ($bid <= 0 || $pid <= 0) throw new RuntimeException('Invalid booking/partner.');
    if ($amt <= 0)              throw new RuntimeException('Amount must be positive.');
    if ($when === '')           $when = date('Y-m-d H:i:s');

    // Recompute commission_due for this booking (same logic as list)
    $qc = db()->prepare("
      SELECT
        b.booking_ref,
        GREATEST(0.00,
          ROUND(
            CASE
              WHEN p.commission_type = 'percent'
                THEN (COALESCE(p.commission_value,0) / 100.0) * COALESCE(b.total_client_price,0)
              ELSE
                COALESCE(b.partner_commission_amount,0)
            END, 2
          )
        ) AS commission_due
      FROM bookings b
      INNER JOIN partners p ON p.id = b.partner_id
      WHERE b.id=:bid AND b.company_id=:cid AND p.id=:pid
      LIMIT 1
    ");
    $qc->execute([':bid'=>$bid, ':cid'=>$cid, ':pid'=>$pid]);
    $bk = $qc->fetch();
    if (!$bk) throw new RuntimeException('Booking not found or partner mismatch.');
    $bookingRef = (string)($bk['booking_ref'] ?? ('#'.$bid));
    $totalDue   = (float)$bk['commission_due'];

    // Paid so far
    $paidSum = 0.0;
    if (tbl_exists('partner_payouts')) {
      $sp = db()->prepare("SELECT COALESCE(SUM(amount),0) FROM partner_payouts WHERE company_id=:cid AND booking_id=:bid");
      $sp->execute([':cid'=>$cid, ':bid'=>$bid]);
      $paidSum = (float)$sp->fetchColumn();
    }

    $outstanding = max(0.0, round($totalDue - $paidSum, 2));
    if ($outstanding <= 0.0) throw new RuntimeException('Nothing outstanding for this booking.');
    if ($amt > $outstanding) throw new RuntimeException('Amount exceeds outstanding (£'.number_format($outstanding,2).').');

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

    // partner_payouts
    if (!tbl_exists('partner_payouts')) throw new RuntimeException('partner_payouts table missing.');
    $ins = $pdo->prepare("
      INSERT INTO partner_payouts
        (company_id, booking_id, partner_id, amount, paid_at, method, reference, notes, created_at)
      VALUES
        (:cid,:bid,:pid,:amt,:paid_at,:meth,:ref,:notes,NOW())
    ");
    $ins->execute([
      ':cid'=>$cid, ':bid'=>$bid, ':pid'=>$pid, ':amt'=>$amt, ':paid_at'=>$when,
      ':meth'=>$meth !== '' ? $meth : null,
      ':ref' =>$ref  !== '' ? $ref  : null,
      ':notes'=>$notes !== '' ? $notes : null,
    ]);

    // transactions — ALWAYS
    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, reference, notes, created_at)
      VALUES
        (:cid, DATE(:paid_at), 'PARTNER_PAYOUT', 'Chauffeur', 'expense',
         :amt, :bid, :ref, :notes, NOW())
    ");
    $tx->execute([
      ':cid'=>$cid,
      ':paid_at'=>$when,
      ':amt'=>$amt,
      ':bid'=>$bid,
      ':ref'=> $ref !== '' ? $ref : ('Partner payout for '.$bookingRef),
      ':notes'=>$notes !== '' ? $notes : null,
    ]);

    // pending_payments — remove and reinsert if balance remains (type='commission')
    $newPaidTotal = round($paidSum + $amt, 2);
    $newBalance   = max(0.0, round($totalDue - $newPaidTotal, 2));

    if (tbl_exists('pending_payments')) {
      $del = $pdo->prepare("DELETE FROM pending_payments WHERE company_id=:cid AND booking_id=:bid AND type='commission'");
      $del->execute([':cid'=>$cid, ':bid'=>$bid]);

      if ($newBalance > 0) {
        $insPend = $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,'commission',:total,:paid,:bal,'pending',NOW())
        ");
        $insPend->execute([
          ':cid'  => $cid,
          ':bid'  => $bid,
          ':ref'  => $bookingRef,
          ':total'=> round($totalDue,2),
          ':paid' => $newPaidTotal,
          ':bal'  => $newBalance,
        ]);
      }
    }

    audit_log('payout.partner.create','booking',$bid,[
      'partner_id'=>$pid,'amount'=>$amt,'paid_at'=>$when,'method'=>$meth,'reference'=>$ref,
      'commission_total'=>round($totalDue,2),'paid_after'=>$newPaidTotal,'balance_remaining'=>$newBalance,
    ]);

    $pdo->commit();

    $qs = http_build_query([
      'from'=>$from,'to'=>$to,'status'=>$status,'q'=>$q,'partner'=>$partner,'ok'=>1
    ]);
    redirect('partners.php?'.$qs);

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

if (isset($_GET['ok'])) $notice = 'Partner payout recorded.';

//////////////////////////////////////////////////
// 7) 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 Commission Payments</h1>
    <div class="text-muted">Completed bookings with partners. Use filters or search by Ref / Client / Partner.</div>
  </div>
  <div>
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('dashboard/md.php')) ?>">← Back to Dashboard</a>
  </div>
  <div>
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('/payments/partners_bulk.php')) ?>">← Bulk Payment</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(is_scalar($er)?(string)$er:json_encode($er)).'</li>'; ?></ul></div>
<?php endif; ?>

<!-- Summary -->
<div class="row mb-3">
  <div class="col-md-4"><div class="card shadow-sm border-success"><div class="card-body text-center"><div class="text-muted small">Total Commission Due</div><div class="h5 mb-0">£<?= number_format($summary['due'],2) ?></div></div></div></div>
  <div class="col-md-4"><div class="card shadow-sm border-primary"><div class="card-body text-center"><div class="text-muted small">Total Paid</div><div class="h5 mb-0">£<?= number_format($summary['paid'],2) ?></div></div></div></div>
  <div class="col-md-4"><div class="card shadow-sm border-danger"><div class="card-body text-center"><div class="text-muted small">Outstanding</div><div class="h5 mb-0">£<?= number_format($summary['outstanding'],2) ?></div></div></div></div>
</div>

<!-- Filters -->
<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-2">
        <label class="form-label">From</label>
        <input type="date" class="form-control" name="from" value="<?= e($from) ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label">To</label>
        <input type="date" class="form-control" name="to" value="<?= e($to) ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label">Status</label>
        <select class="form-select" name="status">
          <option value="unpaid" <?= $status==='unpaid'?'selected':'' ?>>Unpaid</option>
          <option value="paid"   <?= $status==='paid'  ?'selected':'' ?>>Paid</option>
          <option value="all"    <?= $status==='all'   ?'selected':'' ?>>All</option>
        </select>

      </div>
      <div class="col-md-3">
        <label class="form-label">Partner</label>
        <select class="form-select" name="partner">
          <option value="0">— All —</option>
          <?php
          $ps = db()->prepare("SELECT id,name FROM partners WHERE company_id=:cid ORDER BY name");
          $ps->execute([':cid'=>$cid]);
          foreach($ps as $p){
            $sel = $partner==$p['id'] ? 'selected' : '';
            echo '<option value="'.(int)$p['id'].'" '.$sel.'>'.e($p['name']).'</option>';
          }
          ?>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">Search</label>
        <input class="form-control" name="q" placeholder="Ref / Client / Partner" value="<?= e($q) ?>">
      </div>
      <div class="col-md-12 d-grid d-md-flex justify-content-md-end">
        <button class="btn btn-primary">Filter</button>
         
         
<a class="btn btn-outline-primary"
   href="<?= e(url_modules('payments/partner_report.php') . '?' . http_build_query(['from'=>$from,'to'=>$to,'partner'=>$partner,'status'=>$status,'q'=>$q])) ?>"
   target="_blank" rel="noopener">🖨️ Print Report</a>

 
    </form>
  </div>
</div>

<!-- Table -->
<div class="card shadow-sm">
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead class="table-light">
        <tr>
          <th>Ref</th>
          <th>Client</th>
          <th>Pickup</th>
          <th>Partner</th>
          <th class="text-end">£ Commission</th>
          <th class="text-end">£ Paid</th>
          <th class="text-end">£ Outstanding</th>
          <th class="text-end">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php if ($rows): foreach ($rows as $r):
          $due  = (float)$r['commission_due'];
          $paid = (float)$r['paid_sum'];
          $out  = max(0, $due - $paid);
          $badge= $out > 0 ? 'danger' : 'success';
          $pdt  = trim(($r['pickup_date'] ?? '').' '.($r['pickup_time'] ?? ''));
        ?>
        <tr class="<?= $out>0 ? '' : 'table-success' ?>">
          <td><strong><?= e($r['booking_ref']) ?></strong></td>
          <td><?= e($r['client_name'] ?? '—') ?></td>
          <td><?= e($pdt) ?></td>
          <td>
            <div class="d-flex align-items-center gap-2">
              <?= e($r['partner_name'] ?? '—') ?>
              <button type="button" class="btn btn-sm btn-outline-secondary js-bank" data-partner-id="<?= (int)$r['partner_id'] ?>">Bank</button>
            </div>
          </td>
          <td class="text-end">£<?= number_format($due, 2) ?></td>
          <td class="text-end">£<?= number_format($paid, 2) ?></td>
          <td class="text-end"><span class="badge text-bg-<?= e($badge) ?>">£<?= number_format($out, 2) ?></span></td>
          <td class="text-end">
            <?php if ($out > 0): ?>
              <button type="button" class="btn btn-sm btn-dark js-pay"
                data-booking-id="<?= (int)$r['id'] ?>"
                data-partner-id="<?= (int)$r['partner_id'] ?>"
                data-outstanding="<?= number_format($out,2,'.','') ?>"
                data-ref="<?= e($r['booking_ref']) ?>"
                data-commission="<?= number_format($due,2,'.','') ?>"
                data-paid="<?= number_format($paid,2,'.','') ?>">
                Mark Paid
              </button>
            <?php else: ?><span class="text-muted">—</span><?php endif; ?>
          </td>
        </tr>
        <?php endforeach; else: ?>
          <tr><td colspan="8" class="text-center text-muted py-4">No results.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Mark as Paid Modal -->
<div class="modal fade" id="payModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <form class="modal-content" method="post">
      <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
      <input type="hidden" name="action" value="mark_paid">
      <input type="hidden" name="booking_id" id="pay_booking_id">
      <input type="hidden" name="partner_id" id="pay_partner_id">
      <div class="modal-header">
        <h5 class="modal-title">Mark Partner Payout</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="mb-2 small text-muted" id="pay_ref"></div>

        <!-- Breakdown -->
        <div class="border rounded p-2 mb-3 bg-light">
          <div class="row g-2">
            <div class="col-4"><div class="small text-muted">Commission Due</div><div id="bd_due"  class="fw-semibold">£0.00</div></div>
            <div class="col-4"><div class="small text-muted">Paid So Far</div><div id="bd_paid" class="fw-semibold">£0.00</div></div>
            <div class="col-4"><div class="small text-muted">Outstanding</div><div id="bd_out"  class="fw-semibold">£0.00</div></div>
          </div>
          <div class="mt-1 small text-muted">Default Amount = Outstanding</div>
        </div>

        <div class="row g-3">
          <div class="col-6">
            <label class="form-label">Amount (£)</label>
            <input type="number" step="0.01" min="0.01" class="form-control" name="amount" id="pay_amount" required>
          </div>
          <div class="col-6">
            <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-6">
            <label class="form-label">Method</label>
            <input class="form-control" name="method" value="Bank Transfer">
          </div>
          <div class="col-6">
            <label class="form-label">Reference</label>
            <input class="form-control" name="reference">
          </div>
          <div class="col-12">
            <label class="form-label">Notes</label>
            <textarea class="form-control" name="notes" rows="2"></textarea>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-dark">Save Payout</button>
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
      </div>
    </form>
  </div>
</div>

<!-- Partner Bank Modal -->
<div class="modal fade" id="bankModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <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" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div id="bankBody" class="table-responsive"></div>
      </div>
    </div>
  </div>
</div>

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

<script>
(function(){
  const payModal  = new bootstrap.Modal(document.getElementById('payModal'));
  const bankModal = new bootstrap.Modal(document.getElementById('bankModal'));
  const bankBody  = document.getElementById('bankBody');

  // Open Mark Paid with breakdown & prefill outstanding
  document.addEventListener('click',function(e){
    const btn=e.target.closest('.js-pay'); if(!btn) return;
    const bookingId   = btn.dataset.bookingId;
    const partnerId   = btn.dataset.partnerId;
    const outstanding = btn.dataset.outstanding || '0.00';
    const ref         = btn.dataset.ref || '';
    const due         = btn.dataset.commission || '0.00';
    const paid        = btn.dataset.paid || '0.00';

    document.getElementById('pay_booking_id').value = bookingId;
    document.getElementById('pay_partner_id').value = partnerId;
    document.getElementById('pay_amount').value     = outstanding;
    document.getElementById('pay_amount').setAttribute('max', outstanding);
    document.getElementById('pay_ref').textContent  = 'Booking: ' + ref;

    document.getElementById('bd_due').textContent  = '£' + Number(due).toFixed(2);
    document.getElementById('bd_paid').textContent = '£' + Number(paid).toFixed(2);
    document.getElementById('bd_out').textContent  = '£' + Number(outstanding).toFixed(2);

    payModal.show();
  });

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