<?php
declare(strict_types=1);
/**
 * modules/invoices/generate_corporate.php
 *
 * Create ONE invoice for MULTIPLE bookings (corporate, pickup date range).
 * - Step 1: Criteria (corporate + pickup date range)
 * - Step 2: Review bookings (pre-ticked) with editable per-booking amounts
 * - Step 3: Create invoice (header fields + lines + invoice_bookings) in a single transaction
 *
 * This file is additive and does NOT modify your existing features.
 */

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

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

$errors = [];
$notice = null;

// -------------------------------
// Helpers
// -------------------------------
function n2($v): string { return number_format((float)$v, 2, '.', ''); }

/**
 * Generate invoice number like INV-YYYYMMDD-### (per day per company)
 */
function generate_invoice_no(int $companyId): string {
  $today   = date('Y-m-d');
  $prefixD = date('Ymd');
  $prefix  = "INV-{$prefixD}-";
  $stmt = db()->prepare("
    SELECT invoice_no
      FROM invoices
     WHERE company_id = :cid
       AND invoice_date = :d
       AND invoice_no LIKE :pref
  ");
  $stmt->execute([':cid'=>$companyId, ':d'=>$today, ':pref'=>$prefix.'%']);
  $max = 0;
  while ($row = $stmt->fetch()) {
    $no = (string)$row['invoice_no'];
    $parts = explode('-', $no);
    $last  = end($parts);
    if (ctype_digit($last)) $max = max($max, (int)$last);
  }
  $next = $max + 1;
  return $prefix . str_pad((string)$next, 3, '0', STR_PAD_LEFT);
}

/**
 * Fetch active corporates for dropdown
 */
function fetch_corporates(int $cid): array {
  $sql = "SELECT id, name, contact_person, email, billing_address
            FROM corporates
           WHERE company_id = :cid AND status = 'active'
           ORDER BY name";
  $st = db()->prepare($sql);
  $st->execute([':cid'=>$cid]);
  return $st->fetchAll() ?: [];
}

/**
 * Fetch bookings for a corporate within pickup date range.
 * Also annotate each with:
 *  - already_invoiced_total: SUM(amount_invoiced) from invoice_bookings
 */
function fetch_corporate_bookings(int $cid, int $corporateId, string $from, string $to): array {
  $sql = "
    SELECT
      b.id,
      b.booking_ref,
      b.pickup_date,
      b.pickup_time,
      b.pickup_address,
      b.dropoff_address,
      b.pax_count,
      b.luggage_count,
      b.notes,
      b.client_name,
      b.total_client_price,
      b.client_parking_fee,
      b.client_waiting_fee,
      (
        SELECT COALESCE(SUM(ib.amount_invoiced),0.00)
          FROM invoice_bookings ib
         WHERE ib.company_id = b.company_id
           AND ib.booking_id = b.id
      ) AS already_invoiced_total
    FROM bookings b
    WHERE b.company_id   = :cid
      AND b.corporate_id = :corp
      AND b.pickup_date BETWEEN :from AND :to
    ORDER BY COALESCE(b.pickup_date, b.created_at), b.id
  ";
  $st = db()->prepare($sql);
  $st->execute([
    ':cid'  => $cid,
    ':corp' => $corporateId,
    ':from' => $from,
    ':to'   => $to,
  ]);
  $rows = $st->fetchAll() ?: [];

  // Provide a sensible default amount per booking (editable in UI)
  foreach ($rows as &$r) {
    $base = (float)($r['total_client_price'] ?? 0);
    $pf   = (float)($r['client_parking_fee'] ?? 0);
    $wf   = (float)($r['client_waiting_fee'] ?? 0);
    $r['default_amount'] = (float)($base + $pf + $wf);
  }
  return $rows;
}

/**
 * Fetch corporate details for Bill To prefill
 */
function fetch_corporate_for_billto(int $cid, int $corporateId): ?array {
  $st = db()->prepare("
    SELECT id, name, email, billing_address
      FROM corporates
     WHERE company_id = :cid AND id = :id
     LIMIT 1
  ");
  $st->execute([':cid'=>$cid, ':id'=>$corporateId]);
  $row = $st->fetch();
  return $row ?: null;
}

// -------------------------------
// Routing state (step control)
// -------------------------------
$step = 1; // 1=criteria, 2=review, 3=create

$corporates = fetch_corporates($cid);

// Input retainers
$selected_corporate_id = isset($_REQUEST['corporate_id']) ? (int)$_REQUEST['corporate_id'] : 0;
$from = isset($_REQUEST['from']) ? (string)$_REQUEST['from'] : '';
$to   = isset($_REQUEST['to'])   ? (string)$_REQUEST['to']   : '';

$bookings = [];

// -------------------------------
// Handle Step 2: Fetch (POST action=fetch)
// -------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'fetch') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));
    if ($selected_corporate_id <= 0) $errors[] = 'Please select a corporate client.';
    if (!$from) $errors[] = 'From date is required.';
    if (!$to)   $errors[] = 'To date is required.';
    if (!$errors) {
      $bookings = fetch_corporate_bookings($cid, $selected_corporate_id, $from, $to);
      if (!$bookings) {
        $notice = 'No bookings found for that corporate and pickup date range.';
      } else {
        $step = 2;
      }
    }
  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV==='dev') ? $e->getMessage() : 'Unable to fetch bookings.';
  }
}

// -------------------------------
// Handle Step 3: Create invoice (POST action=create)
// -------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));

    $selected_corporate_id = (int)($_POST['corporate_id'] ?? 0);
    $from = (string)($_POST['from'] ?? '');
    $to   = (string)($_POST['to']   ?? '');

    // Selected bookings arrays
    $booking_ids = isset($_POST['booking_id']) ? (array)$_POST['booking_id'] : [];
    $booking_refs= isset($_POST['booking_ref'])? (array)$_POST['booking_ref']: [];
    $amounts     = isset($_POST['amount'])     ? (array)$_POST['amount']     : [];
    $checked     = isset($_POST['include'])    ? (array)$_POST['include']    : []; // ids that were checked

    // Invoice header
    $invoice_no   = trim((string)($_POST['invoice_no'] ?? ''));
    $invoice_date = trim((string)($_POST['invoice_date'] ?? date('Y-m-d')));
    $due_date     = trim((string)($_POST['due_date'] ?? date('Y-m-d', strtotime('+14 days'))));
    $bill_name    = trim((string)($_POST['bill_to_name'] ?? ''));
    $bill_email   = trim((string)($_POST['bill_to_email'] ?? ''));
    $bill_addr    = trim((string)($_POST['bill_to_address'] ?? ''));
    $discount     = (float)($_POST['discount_amount'] ?? 0);
    $vat_rate     = (float)($_POST['vat_rate'] ?? 0);
    $notes        = trim((string)($_POST['notes'] ?? ''));

    // Basic validations
    if ($selected_corporate_id <= 0) $errors[] = 'Corporate is required.';
    if ($invoice_no === '') $invoice_no = generate_invoice_no($cid);
    if ($invoice_date === '') $invoice_date = date('Y-m-d');
    if ($due_date === '')     $due_date     = date('Y-m-d', strtotime($invoice_date.' +14 days'));
    if ($bill_name === '') {
      // fallback to corporate name
      $corp = fetch_corporate_for_billto($cid, $selected_corporate_id);
      $bill_name = $corp['name'] ?? '';
    }
    if ($bill_name === '') $errors[] = 'Bill To (name) is required.';

    // Build selected rows
    $selected_rows = [];
    foreach ($booking_ids as $idx => $bidStr) {
      $bid = (int)$bidStr;
      $ref = (string)($booking_refs[$idx] ?? '');
      $amtRaw = (string)($amounts[$idx] ?? '0');
      $amt = (float)$amtRaw;

      // Include only if checkbox exists for this booking id
      if (!in_array((string)$bid, $checked, true)) continue;

      if ($bid <= 0 || $ref === '') continue;
      if ($amt <= 0) {
        $errors[] = "Amount must be > 0 for booking {$ref}.";
        break;
      }
      $selected_rows[] = ['booking_id'=>$bid, 'booking_ref'=>$ref, 'amount'=>$amt];
    }

    if (!$selected_rows) $errors[] = 'Select at least one booking to include.';

    // Duplicate invoice number check
    $dup = db()->prepare("SELECT id FROM invoices WHERE company_id=:cid AND invoice_no=:no LIMIT 1");
    $dup->execute([':cid'=>$cid, ':no'=>$invoice_no]);
    if ($dup->fetch()) $errors[] = 'Invoice number already exists.';

    if (!$errors) {
      // To enrich line descriptions, fetch fresh booking details for all selected IDs (and verify corporate)
      $inIds = implode(',', array_map('intval', array_column($selected_rows, 'booking_id')));
      $sqlB = "
        SELECT id, booking_ref, client_name, pickup_date, pickup_time, pickup_address, dropoff_address,
               pax_count, luggage_count, notes, client_parking_fee, client_waiting_fee
          FROM bookings
         WHERE company_id = :cid
           AND corporate_id = :corp
           AND id IN ($inIds)
      ";
      $stB = db()->prepare($sqlB);
      $stB->execute([':cid'=>$cid, ':corp'=>$selected_corporate_id]);
      $dbBookings = [];
      while ($row = $stB->fetch()) {
        $dbBookings[(int)$row['id']] = $row;
      }
      // Verify all selected are present
      foreach ($selected_rows as $sr) {
        if (!isset($dbBookings[$sr['booking_id']])) {
          $errors[] = "Booking not found or does not belong to the selected corporate: ".$sr['booking_ref'];
          break;
        }
      }
    }

    if (!$errors) {
      // Compute totals
      $subtotal = 0.00;
      foreach ($selected_rows as $sr) $subtotal += (float)$sr['amount'];
      $discount = max(0.0, $discount);
      $vat_rate = max(0.0, $vat_rate);
      $tax_base = max(0.0, $subtotal - $discount);
      $vat_amt  = round($tax_base * ($vat_rate/100), 2);
      $grand    = round($tax_base + $vat_amt, 2);

      db()->beginTransaction();

      // Prefill Bill To from corporate if empty fields
      $corp = fetch_corporate_for_billto($cid, $selected_corporate_id);
      if ($bill_name === '' && $corp) $bill_name = (string)$corp['name'];
      if ($bill_email === '' && $corp) $bill_email = (string)($corp['email'] ?? '');
      if ($bill_addr === '' && $corp) $bill_addr = (string)($corp['billing_address'] ?? '');

      // Insert invoice (multi-booking: booking_id = NULL, set corporate_id)
      $insI = db()->prepare("
        INSERT INTO invoices (
          company_id, invoice_no, booking_id, corporate_id,
          bill_to_name, bill_to_email, bill_to_address,
          invoice_date, due_date, currency,
          subtotal_amount, discount_amount, vat_rate, vat_amount, total_amount,
          paid_total, status, notes, created_at, updated_at
        ) VALUES (
          :cid, :no, NULL, :corp,
          :bn, :be, :ba,
          :idate, :ddate, 'GBP',
          :sub, :disc, :vr, :va, :grand,
          0.00, 'draft', :notes, NOW(), NOW()
        )
      ");
      $insI->execute([
        ':cid'   => $cid,
        ':no'    => $invoice_no,
        ':corp'  => $selected_corporate_id,
        ':bn'    => $bill_name !== '' ? $bill_name : null,
        ':be'    => $bill_email !== '' ? $bill_email : null,
        ':ba'    => $bill_addr  !== '' ? $bill_addr  : null,
        ':idate' => $invoice_date,
        ':ddate' => $due_date,
        ':sub'   => $subtotal,
        ':disc'  => $discount,
        ':vr'    => $vat_rate,
        ':va'    => $vat_amt,
        ':grand' => $grand,
        ':notes' => $notes !== '' ? $notes : null,
      ]);
      $invoiceId = (int)db()->lastInsertId();

      // Insert lines + junction rows
      $insL = db()->prepare("
        INSERT INTO invoice_lines (invoice_id, description, quantity, unit_price, line_total)
        VALUES (:iid, :d, 1, :u, :t)
      ");
      $insJ = db()->prepare("
        INSERT INTO invoice_bookings (company_id, invoice_id, booking_id, booking_ref, amount_invoiced, created_at, updated_at)
        VALUES (:cid, :iid, :bid, :bref, :amt, NOW(), NOW())
      ");

      foreach ($selected_rows as $sr) {
        $b  = $dbBookings[$sr['booking_id']];
        $ref = (string)$b['booking_ref'];
        $clientName = trim((string)($b['client_name'] ?? ''));
        $pickupDate = (string)($b['pickup_date'] ?? '');

        // Build compact description per your spec:
        // Example:
        // BHC-15102025-310983 — Client: Dere Pinnick — Pickup: 2025-10-17 — Extra Charges: Parking £7.50; Waiting £35.00 — Note: Wrong address given
        $parts = [];
        $parts[] = $ref;
        if ($clientName !== '') $parts[] = "Client: {$clientName}";
        if ($pickupDate !== '') $parts[] = "Pickup: {$pickupDate}";

        // Extra charges (if applicable)
        $extras = [];
        $pf = (float)($b['client_parking_fee'] ?? 0);
        $wf = (float)($b['client_waiting_fee'] ?? 0);
        if ($pf > 0) $extras[] = "Parking £".n2($pf);
        if ($wf > 0) $extras[] = "Waiting £".n2($wf);
        if ($extras) $parts[] = "Extra Charges: ".implode('; ', $extras);

        // Booking note (if applicable)
        $note = trim((string)($b['notes'] ?? ''));
        if ($note !== '') $parts[] = "Note: ".$note;

        $desc = implode(" — ", $parts);
        $amt  = (float)$sr['amount'];

        $insL->execute([
          ':iid' => $invoiceId,
          ':d'   => $desc,
          ':u'   => $amt,
          ':t'   => $amt,
        ]);

        $insJ->execute([
          ':cid'  => $cid,
          ':iid'  => $invoiceId,
          ':bid'  => (int)$sr['booking_id'],
          ':bref' => $ref,
          ':amt'  => $amt,
        ]);
      }

      db()->commit();
      audit_log('invoice.create_bulk', 'invoice', $invoiceId, [
        'invoice_no' => $invoice_no,
        'corporate_id' => $selected_corporate_id,
        'count' => count($selected_rows),
        'total' => $grand,
      ]);

      // Redirect to view
      redirect(url_modules('invoices/view.php').'?id='.$invoiceId);
    } else {
      // If errors, re-show the review step again with what user posted.
      if ($selected_corporate_id > 0 && $from && $to) {
        $bookings = fetch_corporate_bookings($cid, $selected_corporate_id, $from, $to);
        $step = 2;
      } else {
        $step = 1;
      }
    }
  } catch (Throwable $e) {
    if (db()->inTransaction()) db()->rollBack();
    $errors[] = (defined('APP_ENV') && APP_ENV==='dev') ? $e->getMessage() : 'Unable to create invoice.';
    if ($selected_corporate_id > 0 && $from && $to) {
      $bookings = fetch_corporate_bookings($cid, $selected_corporate_id, $from, $to);
      $step = 2;
    } else {
      $step = 1;
    }
  }
}

// -------------------------------
// View
// -------------------------------
include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Generate Corporate Invoice</h1>
  <div class="d-flex gap-2">
    <a href="<?= e(url_modules('invoices/list.php')) ?>" class="btn btn-outline-secondary">Invoices</a>
    <a href="<?= e(url_modules('invoices/add.php')) ?>" class="btn btn-outline-secondary">New Manual</a>
  </div>
</div>

<?php if ($notice): ?><div class="alert alert-info"><?= 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; ?>

<?php if ($step === 1): ?>
  <!-- Step 1: Criteria -->
  <div class="card shadow-sm">
    <div class="card-body">
      <form method="post" class="row g-3">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="action" value="fetch">

        <div class="col-md-5">
          <label class="form-label">Corporate Client <span class="text-danger">*</span></label>
          <select name="corporate_id" class="form-select" required>
            <option value="">— Select Corporate —</option>
            <?php foreach ($corporates as $c): ?>
              <option value="<?= (int)$c['id'] ?>" <?= $selected_corporate_id===(int)$c['id']?'selected':'' ?>>
                <?= e($c['name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-3">
          <label class="form-label">Pickup From <span class="text-danger">*</span></label>
          <input type="date" name="from" class="form-control" value="<?= e($from ?: date('Y-m-01')) ?>" required>
        </div>
        <div class="col-md-3">
          <label class="form-label">Pickup To <span class="text-danger">*</span></label>
          <input type="date" name="to" class="form-control" value="<?= e($to ?: date('Y-m-d')) ?>" required>
        </div>
        <div class="col-md-1 d-grid">
          <button class="btn btn-dark">Fetch</button>
        </div>
      </form>
    </div>
  </div>

<?php elseif ($step === 2): ?>
  <!-- Step 2: Review & Select -->
  <?php
    $corpRow = fetch_corporate_for_billto($cid, $selected_corporate_id) ?? ['name'=>'','email'=>'','billing_address'=>''];
    $def_invoice_no   = generate_invoice_no($cid);
    $def_invoice_date = date('Y-m-d');
    $def_due_date     = date('Y-m-d', strtotime('+14 days'));
  ?>

  <form method="post" id="bulkInvoiceForm" autocomplete="off">
    <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
    <input type="hidden" name="action" value="create">
    <input type="hidden" name="corporate_id" value="<?= (int)$selected_corporate_id ?>">
    <input type="hidden" name="from" value="<?= e($from) ?>">
    <input type="hidden" name="to" value="<?= e($to) ?>">

    <div class="row g-3">
      <!-- Left: bookings table -->
      <div class="col-12 col-lg-7">
        <div class="card shadow-sm">
          <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-2">
              <h2 class="h6 text-uppercase text-muted mb-0">Bookings (Pickup: <?= e($from) ?> → <?= e($to) ?>)</h2>
              <div>
                <button type="button" class="btn btn-sm btn-outline-secondary me-1" id="btnSelectAll">Select All</button>
                <button type="button" class="btn btn-sm btn-outline-secondary" id="btnUnselectAll">Unselect All</button>
              </div>
            </div>
            <div class="table-responsive">
              <table class="table align-middle">
                <thead class="table-light">
                  <tr>
                    <th style="width:48px;"><input type="checkbox" id="chkAll" checked></th>
                    <th>Booking</th>
                    <th>Route</th>
                    <th class="text-end" style="width:140px;">Amount £</th>
                    <th style="width:160px;">Flag</th>
                  </tr>
                </thead>
                <tbody>
                <?php foreach ($bookings as $b): 
                  $bid = (int)$b['id'];
                  $ref = (string)$b['booking_ref'];
                  $amt = (float)$b['default_amount'];
                  $ai  = (float)$b['already_invoiced_total'];
                  $pd  = (string)($b['pickup_date'] ?? '');
                  $pt  = (string)($b['pickup_time'] ?? '');
                  $fromAddr = trim((string)($b['pickup_address'] ?? ''));
                  $toAddr   = trim((string)($b['dropoff_address'] ?? ''));
                ?>
                  <tr>
                    <td>
                      <input type="checkbox" class="rowchk" name="include[]" value="<?= $bid ?>" checked>
                      <input type="hidden" name="booking_id[]" value="<?= $bid ?>">
                      <input type="hidden" name="booking_ref[]" value="<?= e($ref) ?>">
                    </td>
                    <td>
                      <div class="fw-semibold"><?= e($ref) ?></div>
                      <div class="small text-muted"><?= e($pd . ($pt ? " {$pt}" : '')) ?></div>
                      <?php if (!empty($b['notes'])): ?>
                        <div class="small text-muted">Notes: <?= e($b['notes']) ?></div>
                      <?php endif; ?>
                    </td>
                    <td>
                      <div class="small"><?= e($fromAddr ?: 'Unknown') ?> → <?= e($toAddr ?: 'Unknown') ?></div>
                      <div class="small text-muted">Pax <?= (int)$b['pax_count'] ?>, Luggage <?= (int)$b['luggage_count'] ?></div>
                    </td>
                    <td class="text-end">
                      <input type="number" step="0.01" min="0.01" class="form-control form-control-sm text-end amount"
                             name="amount[]" value="<?= e(n2($amt)) ?>">
                    </td>
                    <td>
                      <?php if ($ai > 0): ?>
                        <span class="badge text-bg-warning">Already invoiced £<?= e(n2($ai)) ?></span>
                      <?php else: ?>
                        <span class="badge text-bg-success">New</span>
                      <?php endif; ?>
                    </td>
                  </tr>
                <?php endforeach; ?>
                </tbody>
                <tfoot class="table-light">
                  <tr>
                    <th colspan="3" class="text-end">Selected Total</th>
                    <th class="text-end"><span id="selTotal">0.00</span></th>
                    <th></th>
                  </tr>
                </tfoot>
              </table>
            </div>
          </div>
        </div>
      </div>

      <!-- Right: invoice header -->
      <div class="col-12 col-lg-5">
        <div class="card shadow-sm">
          <div class="card-body">
            <h2 class="h6 text-uppercase text-muted mb-3">Invoice Details</h2>
            <div class="row g-3">
              <div class="col-md-6">
                <label class="form-label">Invoice #</label>
                <input class="form-control" name="invoice_no" value="<?= e($def_invoice_no) ?>">
                <div class="form-text">Auto-suggested; you can edit.</div>
              </div>
              <div class="col-md-3">
                <label class="form-label">Date</label>
                <input type="date" class="form-control" name="invoice_date" value="<?= e($def_invoice_date) ?>">
              </div>
              <div class="col-md-3">
                <label class="form-label">Due</label>
                <input type="date" class="form-control" name="due_date" value="<?= e($def_due_date) ?>">
              </div>

              <div class="col-12">
                <label class="form-label">Bill To (Name) <span class="text-danger">*</span></label>
                <input class="form-control" name="bill_to_name" value="<?= e((string)($corpRow['name'] ?? '')) ?>" required>
              </div>
              <div class="col-12">
                <label class="form-label">Bill To Email</label>
                <input type="email" class="form-control" name="bill_to_email" value="<?= e((string)($corpRow['email'] ?? '')) ?>">
              </div>
              <div class="col-12">
                <label class="form-label">Bill To Address</label>
                <textarea class="form-control" name="bill_to_address" rows="2"><?= e((string)($corpRow['billing_address'] ?? '')) ?></textarea>
              </div>

              <div class="col-md-5">
                <label class="form-label">Discount (£)</label>
                <input type="number" step="0.01" min="0" class="form-control js-calc" name="discount_amount" value="0.00">
              </div>
              <div class="col-md-4">
                <label class="form-label">VAT %</label>
                <input type="number" step="0.01" min="0" class="form-control js-calc" name="vat_rate" value="0.00">
              </div>
              <div class="col-12">
                <label class="form-label">Notes (optional)</label>
                <textarea class="form-control" name="notes" rows="2"></textarea>
              </div>

              <div class="col-12">
                <div class="p-2 border rounded bg-light">
                  <div class="d-flex justify-content-between small">
                    <div class="text-muted">Subtotal (Selected)</div>
                    <div id="sumSub">0.00</div>
                  </div>
                  <div class="d-flex justify-content-between small">
                    <div class="text-muted">Discount</div>
                    <div id="sumDisc">0.00</div>
                  </div>
                  <div class="d-flex justify-content-between small">
                    <div class="text-muted">VAT</div>
                    <div id="sumVat">0.00</div>
                  </div>
                  <div class="d-flex justify-content-between fw-bold">
                    <div>Total Due</div>
                    <div id="sumGrand">0.00</div>
                  </div>
                </div>
              </div>
            </div>

            <div class="alert alert-info mt-3 mb-0 small">
              This invoice will be created as <strong>Draft</strong>. You can email the PDF from the invoice page.
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="mt-3 d-flex gap-2">
      <button type="submit" class="btn btn-dark">Create Invoice</button>
      <a class="btn btn-outline-secondary" href="<?= e(url_modules('invoices/generate_corporate.php')) ?>">Start Over</a>
    </div>
  </form>

  <script>
  (function(){
    const chkAll= document.getElementById('chkAll');
    const btnSel= document.getElementById('btnSelectAll');
    const btnUn = document.getElementById('btnUnselectAll');

    function n(v){ const x = parseFloat(v); return isNaN(x) ? 0 : x; }

    function recalc() {
      let subtotal = 0.0;
      document.querySelectorAll('tbody tr').forEach(tr => {
        const checked = tr.querySelector('.rowchk')?.checked;
        const amtEl   = tr.querySelector('.amount');
        if (checked && amtEl) subtotal += n(amtEl.value);
      });
      const disc = n(document.querySelector('input[name="discount_amount"]').value);
      const vr   = n(document.querySelector('input[name="vat_rate"]').value);
      const base = Math.max(0, subtotal - disc);
      const vat  = base * (vr/100);
      const grand= base + vat;

      const fmt = (x)=>x.toFixed(2);
      const el = (id)=>document.getElementById(id);
      el('selTotal').textContent = fmt(subtotal);
      el('sumSub').textContent   = fmt(subtotal);
      el('sumDisc').textContent  = fmt(disc);
      el('sumVat').textContent   = fmt(vat);
      el('sumGrand').textContent = fmt(grand);
    }

    document.querySelectorAll('.rowchk').forEach(el => el.addEventListener('change', recalc));
    document.querySelectorAll('.amount').forEach(el => el.addEventListener('input', recalc));
    document.querySelectorAll('.js-calc').forEach(el => el.addEventListener('input', recalc));

    if (chkAll) chkAll.addEventListener('change', () => {
      document.querySelectorAll('.rowchk').forEach(el => el.checked = chkAll.checked);
      recalc();
    });

    if (btnSel) btnSel.addEventListener('click', () => {
      document.querySelectorAll('.rowchk').forEach(el => el.checked = true);
      if (chkAll) chkAll.checked = true;
      recalc();
    });
    if (btnUn) btnUn.addEventListener('click', () => {
      document.querySelectorAll('.rowchk').forEach(el => el.checked = false);
      if (chkAll) chkAll.checked = false;
      recalc();
    });

    // initial calc
    recalc();
  })();
  </script>

<?php endif; ?>

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