<?php
declare(strict_types=1);

/**
 * modules/rentals/close.php
 *
 * Close a rental contract (set end date, status, and deposit handling).
 * Parts:
 *  1) Bootstrap & guards
 *  2) Fetch rental (+ helpers for balances)
 *  3) Handle POST (save & close)
 *  4) Render confirmation form
 */

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

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

$errors = [];
$notice = null;

////////////////////////////////////////////////////////////////
// 2) Fetch rental (+ helpers for balances)
////////////////////////////////////////////////////////////////
$sel = db()->prepare("
  SELECT r.*,
         v.reg_no, v.type, v.make, v.model
    FROM rentals r
    LEFT JOIN vehicles v ON v.id = r.vehicle_id
   WHERE r.id=:id AND r.company_id=:cid
   LIMIT 1
");
$sel->execute([':id' => $rentalId, ':cid' => $cid]);
$rent = $sel->fetch();
if (!$rent) redirect('list.php');

/**
 * Helper: calculate expected charge (very simple weekly projection).
 * weeks = max(1, ceil( days / 7 )), where days = (end - start) + 1
 */
function rental_expected_total(array $r): float {
  $rate  = (float)($r['weekly_rate'] ?? 0);
  $start = !empty($r['start_date']) ? new DateTimeImmutable((string)$r['start_date']) : null;
  $end   = !empty($r['end_date'])   ? new DateTimeImmutable((string)$r['end_date'])   : new DateTimeImmutable('today');
  if (!$start) return 0.0;
  if ($end < $start) $end = $start;
  $days  = (int)$end->diff($start)->format('%a') + 1;
  $weeks = (int)ceil($days / 7);
  if ($weeks < 1) $weeks = 1;
  return $weeks * $rate;
}

/**
 * Helper: total payments (if rental_payments table exists; otherwise 0).
 */
function rental_paid_total(int $companyId, int $rentalId): float {
  try {
    $q = db()->prepare("SELECT SUM(amount) AS s FROM rental_payments WHERE company_id=:cid AND rental_id=:rid");
    $q->execute([':cid' => $companyId, ':rid' => $rentalId]);
    $row = $q->fetch();
    return (float)($row['s'] ?? 0);
  } catch (Throwable $e) {
    // Table might not exist yet — ignore
    return 0.0;
  }
}

$expected = rental_expected_total($rent);
$paid     = rental_paid_total($cid, $rentalId);
$balance  = $expected - $paid;

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

    $endDate = trim((string)($_POST['end_date'] ?? ''));
    $depStat = trim((string)($_POST['deposit_status'] ?? 'Held'));
    $notes   = trim((string)($_POST['notes'] ?? ''));

    if ($endDate === '') $endDate = (new DateTimeImmutable('today'))->format('Y-m-d');
    if (!in_array($depStat, ['Held','Refunded','Forfeited'], true)) $depStat = 'Held';

    $append = "\n[Closed ".date('Y-m-d H:i')."]".
              ($notes !== '' ? (' '.$notes) : '');

    $upd = db()->prepare("
      UPDATE rentals
         SET end_date = :ed,
             status = 'Completed',
             deposit_status = :ds,
             payment_notes = CONCAT(IFNULL(payment_notes,''), :apnd),
             updated_at = NOW()
       WHERE id=:id AND company_id=:cid
       LIMIT 1
    ");
    $upd->execute([
      ':ed'   => $endDate,
      ':ds'   => $depStat,
      ':apnd' => $append,
      ':id'   => $rentalId,
      ':cid'  => $cid,
    ]);

    audit_log('rental.close', 'rental', $rentalId, [
      'end_date'       => $endDate,
      'deposit_status' => $depStat,
      'balance_at_close' => $balance,
    ]);

    // Redirect back to list
    redirect(url_modules('rentals/list.php').'?closed=1');
  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? $e->getMessage() : 'Unable to close the rental.';
  }
}

////////////////////////////////////////////////////////////////
// 4) Render confirmation form
////////////////////////////////////////////////////////////////
include dirname(__DIR__, 2) . '/includes/header.php';

$suggestEnd   = !empty($rent['end_date']) ? (string)$rent['end_date'] : (new DateTimeImmutable('today'))->format('Y-m-d');
$depStatusCur = $rent['deposit_status'] ?? ((isset($rent['deposit_refunded_flag']) && (int)$rent['deposit_refunded_flag']===1) ? 'Refunded' : 'Held');
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Close Rental</h1>
  <div class="d-flex gap-2">
    <a href="<?= e(url_modules('rentals/edit.php') . '?id=' . (int)$rent['id']) ?>" class="btn btn-outline-secondary">Edit Contract</a>
    <a href="<?= e(url_modules('rentals/list.php')) ?>" class="btn btn-outline-secondary">Back to List</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; ?>

<!-- Contract summary -->
<div class="card shadow-sm mb-3">
  <div class="card-body">
    <div class="row g-3">
      <div class="col-md-4">
        <div class="small text-muted">Renter</div>
        <div class="fw-semibold"><?= e($rent['renter_name'] ?? '—') ?></div>
        <div class="text-muted small"><?= e($rent['phone'] ?? '') ?></div>
      </div>
      <div class="col-md-4">
        <div class="small text-muted">Vehicle</div>
        <div class="fw-semibold"><?= e(($rent['reg_no'] ?? '—') . ' (' . ($rent['type'] ?? '—') . ')') ?></div>
        <div class="text-muted small"><?= e(trim(($rent['make'] ?? '') . ' ' . ($rent['model'] ?? ''))) ?></div>
      </div>
      <div class="col-md-4">
        <div class="small text-muted">Period</div>
        <div class="fw-semibold"><?= e($rent['start_date'] ?? '—') ?> → <?= e($rent['end_date'] ?? '—') ?></div>
        <div class="text-muted small">Status: <span class="badge text-bg-secondary"><?= e($rent['status'] ?? 'Active') ?></span></div>
      </div>

      <div class="col-md-3">
        <div class="small text-muted">Weekly Rate (£)</div>
        <div class="fw-semibold" id="wkRate"><?= number_format((float)($rent['weekly_rate'] ?? 0), 2) ?></div>
      </div>
      <div class="col-md-3">
        <div class="small text-muted">Deposit (£)</div>
        <div class="fw-semibold"><?= number_format((float)($rent['deposit_amount'] ?? 0), 2) ?></div>
        <div class="text-muted small">Status: <span class="badge text-bg-secondary"><?= e($depStatusCur) ?></span></div>
      </div>
      <div class="col-md-3">
        <div class="small text-muted">Expected @ current</div>
        <div class="fw-semibold" id="expNow"><?= number_format($expected, 2) ?></div>
        <div class="text-muted small">Paid so far: <span id="paidNow"><?= number_format($paid, 2) ?></span></div>
      </div>
      <div class="col-md-3">
        <div class="small text-muted">Balance snapshot</div>
        <?php
          $balCls = $balance > 0 ? 'danger' : ($balance < 0 ? 'success' : 'secondary');
        ?>
        <div class="fw-semibold text-<?= $balCls ?>" id="balNow"><?= number_format($balance, 2) ?></div>
        <div class="text-muted small">Will update on close</div>
      </div>
    </div>
  </div>
</div>

<!-- Close form -->
<div class="card shadow-sm">
  <div class="card-body">
    <form method="post">
      <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
      <input type="hidden" name="id" value="<?= (int)$rent['id'] ?>">

      <div class="row g-3">
        <div class="col-md-3">
          <label class="form-label">End Date</label>
          <input type="date" class="form-control" name="end_date" id="end_date" value="<?= e($suggestEnd) ?>" required>
        </div>
        <div class="col-md-3">
          <label class="form-label">Deposit Handling</label>
          <select class="form-select" name="deposit_status" id="deposit_status">
            <option <?= $depStatusCur==='Held' ? 'selected' : '' ?>>Held</option>
            <option <?= $depStatusCur==='Refunded' ? 'selected' : '' ?>>Refunded</option>
            <option <?= $depStatusCur==='Forfeited' ? 'selected' : '' ?>>Forfeited</option>
          </select>
        </div>
        <div class="col-md-6">
          <label class="form-label">Notes (optional)</label>
          <textarea class="form-control" name="notes" rows="2" placeholder="Any final notes to append to this contract"></textarea>
          <div class="form-text">A timestamp will be appended automatically.</div>
        </div>

        <div class="col-12">
          <div class="p-2 border rounded bg-light">
            <div class="small text-muted mb-1">Preview with chosen end date</div>
            <div class="d-flex flex-wrap gap-3">
              <div>Expected: <strong id="expPreview"><?= number_format($expected, 2) ?></strong></div>
              <div>Paid: <strong id="paidPreview"><?= number_format($paid, 2) ?></strong></div>
              <div>Balance: <strong id="balPreview"><?= number_format($balance, 2) ?></strong></div>
            </div>
          </div>
        </div>
      </div>

      <div class="mt-3 d-flex gap-2">
        <button class="btn btn-success">Save & Close Contract</button>
        <a class="btn btn-outline-secondary" href="<?= e(url_modules('rentals/list.php')) ?>">Cancel</a>
      </div>
    </form>
  </div>
</div>

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

<script>
(function(){
  const start = new Date('<?= e($rent['start_date']) ?>T00:00:00');
  const rate  = parseFloat('<?= (float)($rent['weekly_rate'] ?? 0) ?>') || 0;
  const paid  = parseFloat('<?= (float)$paid ?>') || 0;

  const endInput = document.getElementById('end_date');
  const expPrev  = document.getElementById('expPreview');
  const paidPrev = document.getElementById('paidPreview');
  const balPrev  = document.getElementById('balPreview');

  function ceilWeeks(days){
    const w = Math.ceil(days / 7);
    return Math.max(1, w);
  }
  function ymdToDate(ymd){
    const parts = (ymd||'').split('-');
    if (parts.length !== 3) return null;
    return new Date(parts[0] + '-' + parts[1] + '-' + parts[2] + 'T00:00:00');
  }
  function recalc(){
    const end = ymdToDate(endInput.value) || new Date();
    let days = Math.floor((end - start) / (1000*60*60*24)) + 1;
    if (days < 1) days = 1;
    const weeks = ceilWeeks(days);
    const expected = weeks * rate;
    const balance = expected - paid;

    expPrev.textContent = expected.toFixed(2);
    paidPrev.textContent = paid.toFixed(2);
    balPrev.textContent = balance.toFixed(2);
  }

  endInput.addEventListener('change', recalc);
  recalc();
})();
</script>
