<?php
declare(strict_types=1);
/**
 * modules/rentals/list.php
 *
 * Rentals grid with filters + inline Close & Delete actions.
 * Columns:
 *  - ID, Vehicle, Renter, Phone, Weekly, Deposit, Start, End, Status, Deposit Status, Actions
 */

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;

/* ---------------- Actions (POST) ---------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));

    // Close contract
    if (($_POST['action'] ?? '') === 'close') {
      $rid     = (int)($_POST['id'] ?? 0);
      $endDate = trim((string)($_POST['end_date'] ?? ''));
      $depStat = trim((string)($_POST['deposit_status'] ?? 'Held'));
      $notes   = trim((string)($_POST['notes'] ?? ''));

      if ($rid <= 0) throw new RuntimeException('Invalid rental ID.');
      if ($endDate === '') $endDate = (new DateTimeImmutable('today'))->format('Y-m-d');
      if (!in_array($depStat, ['Held','Refunded','Forfeited'], true)) $depStat = 'Held';

      $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
      ");
      $append = ($notes !== '' ? ("\n[Closed ".date('Y-m-d H:i')."] ".$notes) : ("\n[Closed ".date('Y-m-d H:i')."]"));
      $upd->execute([
        ':ed'   => $endDate,
        ':ds'   => $depStat,
        ':apnd' => $append,
        ':id'   => $rid,
        ':cid'  => $cid,
      ]);
      audit_log('rental.close', 'rental', $rid, ['end_date'=>$endDate,'deposit_status'=>$depStat]);
      $notice = 'Rental closed successfully.';
    }

    // Delete rental
    if (($_POST['action'] ?? '') === 'delete') {
      $rid = (int)($_POST['id'] ?? 0);
      if ($rid <= 0) throw new RuntimeException('Invalid rental ID.');
      // Remove agreement file if exists
      $sel = db()->prepare("SELECT agreement_url FROM rentals WHERE id=:id AND company_id=:cid LIMIT 1");
      $sel->execute([':id'=>$rid, ':cid'=>$cid]);
      if ($row = $sel->fetch()) {
        if (!empty($row['agreement_url'])) {
          $abs = project_root().'/public/'.$row['agreement_url'];
          if (is_file($abs)) @unlink($abs);
        }
      }
      $del = db()->prepare("DELETE FROM rentals WHERE id=:id AND company_id=:cid LIMIT 1");
      $del->execute([':id'=>$rid, ':cid'=>$cid]);
      audit_log('rental.delete','rental',$rid,null);
      $notice = 'Rental deleted.';
    }
  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? $e->getMessage() : 'Action failed.';
  }
}

/* ---------------- Filters (GET) ---------------- */
$vehicleId = isset($_GET['vehicle_id']) && $_GET['vehicle_id'] !== '' ? (int)$_GET['vehicle_id'] : null;
$status    = isset($_GET['status']) && $_GET['status'] !== '' ? (string)$_GET['status'] : null;
$from      = isset($_GET['from'])   && $_GET['from']   !== '' ? (string)$_GET['from']   : null;
$to        = isset($_GET['to'])     && $_GET['to']     !== '' ? (string)$_GET['to']     : null;
$q         = isset($_GET['q'])      && $_GET['q']      !== '' ? trim((string)$_GET['q']) : null;

/* Vehicles for filters */
$vehStmt = db()->prepare("SELECT id, reg_no, type FROM vehicles WHERE company_id=:cid ORDER BY reg_no");
$vehStmt->execute([':cid'=>$cid]);
$vehicles = $vehStmt->fetchAll();

/* ---------------- Query rentals ---------------- */
$where = ["r.company_id = :cid"];
$args  = [':cid' => $cid];

if ($vehicleId) { $where[] = "r.vehicle_id = :vid"; $args[':vid'] = $vehicleId; }
if ($status)    { $where[] = "r.status = :st";      $args[':st']  = $status; }
if ($from && $to) {
  // Overlap with window [from, to]
  $where[] = "(COALESCE(r.end_date,'9999-12-31') >= :from AND r.start_date <= :to)";
  $args[':from'] = $from;
  $args[':to']   = $to;
} elseif ($from) {
  $where[] = "COALESCE(r.end_date,'9999-12-31') >= :from";
  $args[':from'] = $from;
} elseif ($to) {
  $where[] = "r.start_date <= :to";
  $args[':to'] = $to;
}
if ($q) {
  $where[] = "(r.renter_name LIKE :q OR r.phone LIKE :q)";
  $args[':q'] = '%'.$q.'%';
}

$sql = "
  SELECT
    r.*,
    v.reg_no, v.type
  FROM rentals r
  LEFT JOIN vehicles v ON v.id = r.vehicle_id
  WHERE ".implode(' AND ', $where)."
  ORDER BY r.start_date DESC, r.id DESC
  LIMIT 300
";
$stmt = db()->prepare($sql);
$stmt->execute($args);
$rows = $stmt->fetchAll();

/* ---------------- UI helpers ---------------- */
function badge_status(string $s): string {
  $map = [
    'Active'    => 'success',
    'Completed' => 'secondary',
    'Overdue'   => 'danger',
    'Cancelled' => 'dark',
  ];
  $cls = $map[$s] ?? 'secondary';
  return '<span class="badge text-bg-'.$cls.'">'.e($s).'</span>';
}
function badge_deposit(?string $s): string {
  $map = [
    'Held'      => 'secondary',
    'Refunded'  => 'success',
    'Forfeited' => 'danger',
  ];
  $cls = $map[$s ?? 'Held'] ?? 'secondary';
  return '<span class="badge text-bg-'.$cls.'">'.e($s ?? 'Held').'</span>';
}

include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Rentals</h1>
  <div class="d-flex gap-2">
    <a href="<?= e(url_modules('rentals/calendar.php')) ?>" class="btn btn-outline-secondary">Availability Calendar</a>
    <a href="<?= e(url_modules('rentals/add.php')) ?>" class="btn btn-dark">Add Rental</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 $e) echo '<li>'.e($e).'</li>'; ?></ul></div><?php endif; ?>

<!-- Filters -->
<div class="card shadow-sm mb-3">
  <div class="card-body">
    <form method="get" class="row g-2 align-items-end">
      <div class="col-md-3">
        <label class="form-label">Vehicle</label>
        <select class="form-select" name="vehicle_id">
          <option value="">— All vehicles —</option>
          <?php foreach ($vehicles as $v): ?>
            <option value="<?= (int)$v['id'] ?>" <?= ($vehicleId===(int)$v['id'])?'selected':'' ?>>
              <?= e(($v['reg_no'] ?? '—').' ('.($v['type'] ?? '—').')') ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">Status</label>
        <select class="form-select" name="status">
          <option value="">— All —</option>
          <?php foreach (['Active','Completed','Overdue','Cancelled'] as $st): ?>
            <option value="<?= e($st) ?>" <?= ($status===$st)?'selected':'' ?>><?= e($st) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <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">Search</label>
        <input class="form-control" name="q" placeholder="Renter / Phone" value="<?= e($q ?? '') ?>">
      </div>
      <div class="col-md-1 d-grid">
        <button class="btn btn-primary">Filter</button>
      </div>
      <div class="col-md-1 d-grid">
        <a class="btn btn-outline-secondary" href="list.php">Reset</a>
      </div>
    </form>
  </div>
</div>

<!-- Grid -->
<div class="card shadow-sm">
  <div class="card-body">
    <div class="table-responsive">
      <table class="table align-middle">
        <thead class="table-light">
          <tr>
            <th>#</th>
            <th>Vehicle</th>
            <th>Renter</th>
            <th>Phone</th>
            <th class="text-end">£ Weekly</th>
            <th class="text-end">£ Deposit</th>
            <th>Start</th>
            <th>End</th>
            <th>Status</th>
            <th>Deposit</th>
            <th class="text-end">Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($rows): foreach ($rows as $r):
            $st  = ucfirst(strtolower((string)($r['status'] ?? 'Active')));
            $dep = $r['deposit_status'] ?? ((isset($r['deposit_refunded_flag']) && (int)$r['deposit_refunded_flag']===1) ? 'Refunded' : 'Held');
          ?>
          <tr>
            <td><?= (int)$r['id'] ?></td>
            <td>
              <div class="fw-semibold"><?= e($r['reg_no'] ?? '—') ?></div>
              <div class="text-muted small"><?= e($r['type'] ?? '—') ?></div>
            </td>
            <td><?= e($r['renter_name'] ?? '—') ?></td>
            <td><?= e($r['phone'] ?? '—') ?></td>
            <td class="text-end"><?= number_format((float)($r['weekly_rate'] ?? 0), 2) ?></td>
            <td class="text-end"><?= number_format((float)($r['deposit_amount'] ?? 0), 2) ?></td>
            <td><?= e($r['start_date'] ?? '—') ?></td>
            <td><?= e($r['end_date'] ?? '—') ?></td>
            <td><?= badge_status($st) ?></td>
            <td><?= badge_deposit($dep) ?></td>
            <td class="text-end">
              <div class="d-inline-flex gap-1">
                <a class="btn btn-sm btn-outline-primary" href="edit.php?id=<?= (int)$r['id'] ?>">Edit</a>
                <button
                  type="button"
                  class="btn btn-sm btn-outline-success js-open-close"
                  data-id="<?= (int)$r['id'] ?>"
                  data-renter="<?= e($r['renter_name'] ?? '') ?>"
                  data-vehicle="<?= e(($r['reg_no'] ?? '—').' ('.($r['type'] ?? '—').')') ?>"
                  data-end="<?= e($r['end_date'] ?? '') ?>"
                  data-dep="<?= e($dep) ?>"
                >Close</button>
                <form method="post" class="d-inline" onsubmit="return confirm('Delete this rental?');">
                  <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                  <input type="hidden" name="action" value="delete">
                  <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                  <button class="btn btn-sm btn-outline-danger">Delete</button>
                </form>
              </div>
            </td>
          </tr>
          <?php endforeach; else: ?>
            <tr><td colspan="11" class="text-center text-muted py-4">No rentals found.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Close Contract Modal -->
<div class="modal fade" id="closeModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Close Rental</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="action" value="close">
        <input type="hidden" name="id" id="close_id" value="">

        <div class="mb-2 small text-muted" id="close_summary"></div>

        <div class="row g-3">
          <div class="col-6">
            <label class="form-label">End Date</label>
            <input type="date" class="form-control" name="end_date" id="close_end_date" required>
          </div>
          <div class="col-6">
            <label class="form-label">Deposit Status</label>
            <select class="form-select" name="deposit_status" id="close_dep">
              <option>Held</option>
              <option>Refunded</option>
              <option>Forfeited</option>
            </select>
          </div>
          <div class="col-12">
            <label class="form-label">Notes</label>
            <textarea class="form-control" name="notes" rows="2" placeholder="Optional note to append to contract"></textarea>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-success">Save & Close</button>
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
      </div>
    </form>
  </div>
</div>

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

<script>
(function(){
  const modalEl = document.getElementById('closeModal');
  const idField = document.getElementById('close_id');
  const endField = document.getElementById('close_end_date');
  const depField = document.getElementById('close_dep');
  const summary = document.getElementById('close_summary');

  function todayYMD(){
    const d = new Date();
    const m = String(d.getMonth()+1).padStart(2,'0');
    const day = String(d.getDate()).padStart(2,'0');
    return d.getFullYear() + '-' + m + '-' + day;
  }

  document.addEventListener('click', function(e){
    const btn = e.target.closest('.js-open-close');
    if (!btn) return;
    const id = btn.getAttribute('data-id');
    const renter = btn.getAttribute('data-renter') || '';
    const vehicle = btn.getAttribute('data-vehicle') || '';
    const endDate = btn.getAttribute('data-end') || '';
    const dep = btn.getAttribute('data-dep') || 'Held';

    idField.value = id;
    endField.value = endDate || todayYMD();
    depField.value = dep;
    summary.textContent = `Renter: ${renter} • Vehicle: ${vehicle}`;

    const bsModal = new bootstrap.Modal(modalEl);
    bsModal.show();
  });
})();
</script>
