<?php
declare(strict_types=1);

/**
 * modules/payments/pending_sync.php
 *
 * Keep pending_payments in sync when a booking changes.
 * - Recomputes client `total_due` from booking:
 *     total_due = total_client_price + client_parking_fee + client_waiting_fee
 * - Preserves amount_paid on the pending row
 * - Updates balance_due (= total_due - amount_paid)
 * - If balance_due <= 0, deletes the pending row
 * - If booking not found, does nothing
 *
 * Usage (after you save/update a booking record):
 *   require_once dirname(__DIR__) . '/payments/pending_sync.php';
 *   pending_upsert_client((int)$companyId, (int)$bookingId);
 */

require_once dirname(__DIR__, 2) . '/config/functions.php';

/** Internal: fetch booking safely */
function _ps_load_booking(int $cid, int $bid): ?array {
  $q = db()->prepare("
    SELECT id, company_id, booking_ref,
           total_client_price, client_parking_fee, client_waiting_fee
      FROM bookings
     WHERE id=:bid AND company_id=:cid
     LIMIT 1
  ");
  $q->execute([':bid'=>$bid, ':cid'=>$cid]);
  $r = $q->fetch();
  return $r ?: null;
}

/** Internal: ensure a single client pending row exists (or removed) for a booking */
function pending_upsert_client(int $cid, int $bid): void {
  $bk = _ps_load_booking($cid, $bid);
  if (!$bk) return;

  // Compute the client total due from booking fields
  $total = (float)($bk['total_client_price'] ?? 0.00)
         + (float)($bk['client_parking_fee'] ?? 0.00)
         + (float)($bk['client_waiting_fee'] ?? 0.00);

  $bookingRef = (string)($bk['booking_ref'] ?? ('#'.$bid));

  // Load existing pending row (if any)
  $sel = db()->prepare("
    SELECT id, amount_paid
      FROM pending_payments
     WHERE company_id = :cid
       AND booking_id = :bid
       AND type = 'client'
     LIMIT 1
  ");
  $sel->execute([':cid'=>$cid, ':bid'=>$bid]);
  $row = $sel->fetch();

  $paid   = (float)($row['amount_paid'] ?? 0.00);
  $bal    = max(0.0, round($total - $paid, 2));

  // If nothing is due and no row exists, nothing to do
  if (!$row && $bal <= 0.0001) return;

  if ($bal <= 0.0001) {
    // Fully settled -> delete row if exists
    $del = db()->prepare("DELETE FROM pending_payments WHERE id=:id AND company_id=:cid");
    if ($row) $del->execute([':id'=>(int)$row['id'], ':cid'=>$cid]);
    return;
  }

  if ($row) {
    // Update existing row
    $upd = db()->prepare("
      UPDATE pending_payments
         SET booking_ref = :ref,
             total_due   = :tot,
             balance_due = :bal,
             status      = 'pending',
             updated_at  = NOW()
       WHERE id = :id AND company_id = :cid
    ");
    $upd->execute([
      ':ref'=>$bookingRef, ':tot'=>$total, ':bal'=>$bal,
      ':id'=>(int)$row['id'], ':cid'=>$cid
    ]);
  } else {
    // Insert new row
    $ins = db()->prepare("
      INSERT INTO pending_payments
        (company_id, booking_id, booking_ref, type, total_due, amount_paid, balance_due, status, created_at, updated_at)
      VALUES
        (:cid, :bid, :ref, 'client', :tot, 0.00, :bal, 'pending', NOW(), NOW())
    ");
    $ins->execute([
      ':cid'=>$cid, ':bid'=>$bid, ':ref'=>$bookingRef,
      ':tot'=>$total, ':bal'=>$bal
    ]);
  }
}
