<?php
declare(strict_types=1);
/**
 * modules/rentals/edit.php
 *
 * Edit a rental contract.
 * - Validates overlap for Active/Overdue rentals on same vehicle (excludes self)
 * - Replace/Delete agreement file
 * - User-friendly, sticky header actions, projected summary
 */

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'));

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

/* ---------- Load rental ---------- */
$sel = db()->prepare("
  SELECT *
  FROM rentals
  WHERE id = :id AND company_id = :cid
  LIMIT 1
");
$sel->execute([':id' => $id, ':cid' => $cid]);
$rental = $sel->fetch();
if (!$rental) redirect('list.php');

/* ---------- Lookups ---------- */
$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();

/* Vehicles currently rented today (excluding this rental) */
$today = (new DateTimeImmutable('today'))->format('Y-m-d');
$curRentedStmt = db()->prepare("
  SELECT DISTINCT vehicle_id
  FROM rentals
  WHERE company_id=:cid
    AND id <> :id
    AND status IN ('Active','Overdue')
    AND (COALESCE(end_date, '9999-12-31') >= :today)
");
$curRentedStmt->execute([':cid'=>$cid, ':id'=>$id, ':today'=>$today]);
$currentlyRented = array_map('intval', array_column($curRentedStmt->fetchAll(), 'vehicle_id'));
$curRentedMap = array_fill_keys($currentlyRented, true);

$errors = [];
$notice = null;

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

    $vehicle_id   = (int)($_POST['vehicle_id'] ?? 0);
    $renter_name  = trim((string)($_POST['renter_name'] ?? ''));
    $phone        = trim((string)($_POST['phone'] ?? ''));
    $renter_email = trim((string)($_POST['renter_email'] ?? ''));
    $renter_addr  = trim((string)($_POST['renter_address'] ?? ''));

    $weekly_rate  = ($_POST['weekly_rate']  ?? '') !== '' ? (float)$_POST['weekly_rate']  : 0.00;
    $deposit_amt  = ($_POST['deposit_amount'] ?? '') !== '' ? (float)$_POST['deposit_amount'] : 0.00;

    $start_date   = (string)($_POST['start_date'] ?? '');
    $end_date     = (string)($_POST['end_date']   ?? '');

    $status       = (string)($_POST['status'] ?? 'Active');
    $deposit_status    = (string)($_POST['deposit_status'] ?? 'Held');
    $payment_frequency = (string)($_POST['payment_frequency'] ?? 'Weekly');
    $payment_notes     = trim((string)($_POST['payment_notes'] ?? ''));

    $remove_agreement  = isset($_POST['remove_agreement']);

    if ($vehicle_id <= 0) $errors[] = 'Please select a vehicle.';
    if ($renter_name === '') $errors[] = 'Renter name is required.';
    if ($phone === '') $errors[] = 'Renter phone is required.';
    if ($weekly_rate <= 0) $errors[] = 'Weekly rent amount must be greater than 0.';
    if ($deposit_amt < 0)  $errors[] = 'Deposit cannot be negative.';
    if ($start_date === '') $errors[] = 'Start date is required.';

    // Overlap check (exclude current rental)
    if (!$errors) {
      $newStart = $start_date;
      $newEnd   = $end_date !== '' ? $end_date : '9999-12-31';
      $overlap = db()->prepare("
        SELECT id
        FROM rentals
        WHERE company_id = :cid
          AND id <> :id
          AND vehicle_id  = :vid
          AND status IN ('Active','Overdue')
          AND NOT (COALESCE(end_date,'9999-12-31') < :new_start OR :new_end < start_date)
        LIMIT 1
      ");
      $overlap->execute([
        ':cid' => $cid,
        ':id'  => $id,
        ':vid' => $vehicle_id,
        ':new_start' => $newStart,
        ':new_end'   => $newEnd,
      ]);
      if ($overlap->fetch()) {
        $errors[] = 'This vehicle already has an Active/Overdue rental overlapping the selected dates.';
      }
    }

    // Agreement file logic (replace or delete)
    $newAgreementUrl = $rental['agreement_url'] ?? null;
    $uploadProvided = (isset($_FILES['agreement']) && $_FILES['agreement']['error'] !== UPLOAD_ERR_NO_FILE);

    if ($remove_agreement && !$uploadProvided) {
      // remove existing
      if (!empty($newAgreementUrl)) {
        $abs = project_root().'/public/'.$newAgreementUrl;
        if (is_file($abs)) @unlink($abs);
      }
      $newAgreementUrl = null;
    }

    if ($uploadProvided) {
      $f = $_FILES['agreement'];
      if ($f['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
        $allowed = ['pdf','doc','docx'];
        if (!in_array($ext, $allowed, true)) {
          $errors[] = 'Agreement must be a PDF, DOC, or DOCX file.';
        } else {
          // delete old if any
          if (!empty($newAgreementUrl)) {
            $oldAbs = project_root().'/public/'.$newAgreementUrl;
            if (is_file($oldAbs)) @unlink($oldAbs);
          }
          // save new
          $dir = project_root() . '/public/uploads/rentals';
          if (!is_dir($dir)) @mkdir($dir, 0775, true);
          $name = 'rental_'.$id.'_'.time().'_'.bin2hex(random_bytes(4)).'.'.$ext;
          $path = $dir . '/' . $name;
          if (!move_uploaded_file($f['tmp_name'], $path)) {
            $errors[] = 'Failed to save the uploaded agreement.';
          } else {
            $newAgreementUrl = 'uploads/rentals/' . $name;
          }
        }
      } else {
        $errors[] = 'Agreement upload failed.';
      }
    }

    if (!$errors) {
      // Update
      $upd = db()->prepare("
        UPDATE rentals
           SET vehicle_id = :vid,
               renter_name = :rname,
               phone = :phone,
               renter_email = :email,
               renter_address = :addr,
               weekly_rate = :weekly,
               deposit_amount = :deposit,
               start_date = :sdate,
               end_date   = :edate,
               status = :status,
               deposit_status = :dstatus,
               payment_frequency = :pfreq,
               payment_notes = :pnotes,
               agreement_url = :aurl,
               updated_at = NOW()
         WHERE id=:id AND company_id=:cid
      ");
      $upd->execute([
        ':vid'    => $vehicle_id,
        ':rname'  => $renter_name,
        ':phone'  => $phone,
        ':email'  => ($renter_email !== '' ? $renter_email : null),
        ':addr'   => ($renter_addr  !== '' ? $renter_addr  : null),
        ':weekly' => $weekly_rate,
        ':deposit'=> $deposit_amt,
        ':sdate'  => $start_date,
        ':edate'  => ($end_date !== '' ? $end_date : null),
        ':status' => in_array($status, ['Active','Completed','Overdue','Cancelled'], true) ? $status : 'Active',
        ':dstatus'=> in_array($deposit_status, ['Held','Refunded','Forfeited'], true) ? $deposit_status : 'Held',
        ':pfreq'  => in_array($payment_frequency, ['Weekly','Monthly'], true) ? $payment_frequency : 'Weekly',
        ':pnotes' => ($payment_notes !== '' ? $payment_notes : null),
        ':aurl'   => $newAgreementUrl,
        ':id'     => $id,
        ':cid'    => $cid,
      ]);

      audit_log('rental.update', 'rental', $id, ['vehicle_id' => $vehicle_id, 'status' => $status]);
      $notice = 'Rental updated successfully.';

      // refresh
      $sel->execute([':id' => $id, ':cid' => $cid]);
      $rental = $sel->fetch();
    }
  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? $e->getMessage() : 'Unable to save changes.';
  }
}

/* ---------- View ---------- */
include dirname(__DIR__, 2) . '/includes/header.php';
function sel($a,$b){ return ((string)$a === (string)$b) ? 'selected' : ''; }
?>
<form method="post" enctype="multipart/form-data" id="rentalForm" autocomplete="off">
  <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
  <input type="hidden" name="action" value="save">

  <!-- Sticky actions -->
  <div class="position-sticky top-0 z-3 pb-2" style="background:#f8fafc;">
    <div class="d-flex justify-content-between align-items-center mb-2 pt-2">
      <h1 class="h4 mb-0">Edit Rental #<?= (int)$rental['id'] ?></h1>
      <div class="d-flex gap-2">
        <button type="submit" class="btn btn-dark" form="rentalForm">Save Changes</button>
        <a href="list.php" class="btn btn-outline-secondary">Back</a>
      </div>
    </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; ?>

  <div class="row g-4">
    <!-- Renter Details -->
    <div class="col-12 col-lg-6">
      <div class="border rounded p-3 h-100">
        <h2 class="h6 text-uppercase text-muted mb-3">Renter Details</h2>
        <div class="row g-3">
          <div class="col-md-12">
            <label class="form-label">Renter Name <span class="text-danger">*</span></label>
            <input class="form-control" name="renter_name" required
                   value="<?= e($_POST['renter_name'] ?? $rental['renter_name']) ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label">Phone <span class="text-danger">*</span></label>
            <input class="form-control" name="phone" required
                   value="<?= e($_POST['phone'] ?? $rental['phone']) ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label">Email</label>
            <input type="email" class="form-control" name="renter_email"
                   value="<?= e($_POST['renter_email'] ?? ($rental['renter_email'] ?? '')) ?>">
          </div>
          <div class="col-12">
            <label class="form-label">Address</label>
            <textarea class="form-control" rows="2" name="renter_address"><?= e($_POST['renter_address'] ?? ($rental['renter_address'] ?? '')) ?></textarea>
          </div>
        </div>
      </div>
    </div>

    <!-- Vehicle & Contract -->
    <div class="col-12 col-lg-6">
      <div class="border rounded p-3 h-100">
        <h2 class="h6 text-uppercase text-muted mb-3">Vehicle & Contract</h2>
        <div class="row g-3">
          <div class="col-md-12">
            <label class="form-label">Vehicle <span class="text-danger">*</span></label>
            <select class="form-select" name="vehicle_id" required>
              <option value="">— Select Vehicle —</option>
              <?php
              $curVid = (int)($_POST['vehicle_id'] ?? $rental['vehicle_id']);
              foreach ($vehicles as $v):
                $vid   = (int)$v['id'];
                $label = trim(($v['reg_no'] ?? '—') . ' (' . ($v['type'] ?? '—') . ')');
                $warn  = (isset($curRentedMap[$vid]) && $vid !== (int)$rental['vehicle_id']) ? ' — Currently Rented' : '';
              ?>
                <option value="<?= $vid ?>" <?= sel($curVid, $vid) ?>>
                  <?= e($label . $warn) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Weekly Rent Amount (£) <span class="text-danger">*</span></label>
            <input type="number" step="0.01" class="form-control js-calc" name="weekly_rate" required
                   value="<?= e($_POST['weekly_rate'] ?? (string)$rental['weekly_rate']) ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label">Deposit Amount (£) <span class="text-danger">*</span></label>
            <input type="number" step="0.01" class="form-control js-calc" name="deposit_amount" required
                   value="<?= e($_POST['deposit_amount'] ?? (string)$rental['deposit_amount']) ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label">Start Date <span class="text-danger">*</span></label>
            <input type="date" class="form-control js-calc" name="start_date" required
                   value="<?= e($_POST['start_date'] ?? (string)$rental['start_date']) ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label">End Date</label>
            <input type="date" class="form-control js-calc" name="end_date"
                   value="<?= e($_POST['end_date'] ?? (string)($rental['end_date'] ?? '')) ?>">
            <div class="form-text">Leave blank for open-ended contracts.</div>
          </div>
          <div class="col-md-6">
            <label class="form-label">Status</label>
            <?php $st = $_POST['status'] ?? (string)$rental['status']; ?>
            <select class="form-select" name="status">
              <option <?= $st==='Active'?'selected':'' ?>>Active</option>
              <option <?= $st==='Completed'?'selected':'' ?>>Completed</option>
              <option <?= $st==='Overdue'?'selected':'' ?>>Overdue</option>
              <option <?= $st==='Cancelled'?'selected':'' ?>>Cancelled</option>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Deposit Status</label>
            <?php $ds = $_POST['deposit_status'] ?? (string)($rental['deposit_status'] ?? 'Held'); ?>
            <select class="form-select" name="deposit_status">
              <option <?= $ds==='Held'?'selected':'' ?>>Held</option>
              <option <?= $ds==='Refunded'?'selected':'' ?>>Refunded</option>
              <option <?= $ds==='Forfeited'?'selected':'' ?>>Forfeited</option>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Payment Frequency</label>
            <?php $pf = $_POST['payment_frequency'] ?? (string)($rental['payment_frequency'] ?? 'Weekly'); ?>
            <select class="form-select js-calc" name="payment_frequency">
              <option <?= $pf==='Weekly'?'selected':'' ?>>Weekly</option>
              <option <?= $pf==='Monthly'?'selected':'' ?>>Monthly</option>
            </select>
          </div>
          <div class="col-12">
            <label class="form-label">Payment Notes</label>
            <textarea class="form-control" rows="2" name="payment_notes"><?= e($_POST['payment_notes'] ?? ($rental['payment_notes'] ?? '')) ?></textarea>
          </div>
        </div>
      </div>
    </div>

    <!-- Attachments / Tools -->
    <div class="col-12">
      <div class="border rounded p-3">
        <h2 class="h6 text-uppercase text-muted mb-3">Attachments & Tools</h2>

        <?php if (!empty($rental['agreement_url'])): ?>
          <div class="alert alert-secondary d-flex justify-content-between align-items-center">
            <div>
              Current Agreement:
              <a target="_blank" rel="noopener" href="<?= e(url_public($rental['agreement_url'])) ?>">View/Download</a>
            </div>
            <div class="form-check mb-0">
              <input class="form-check-input" type="checkbox" name="remove_agreement" id="remove_agreement">
              <label class="form-check-label" for="remove_agreement">Remove on save</label>
            </div>
          </div>
        <?php endif; ?>

        <div class="row g-3 align-items-end">
          <div class="col-md-6">
            <label class="form-label">Replace/Upload Agreement (PDF/DOC/DOCX)</label>
            <input type="file" class="form-control" name="agreement" accept=".pdf,.doc,.docx">
          </div>
          <div class="col-md-6">
            <label class="form-label d-block">Auto-Generate Agreement</label>
            <?php
              $genParams = [
                'renter' => $_POST['renter_name'] ?? $renter_name ?? $rental['renter_name'],
                'phone'  => $_POST['phone'] ?? $rental['phone'],
                'email'  => $_POST['renter_email'] ?? ($rental['renter_email'] ?? ''),
                'start'  => $_POST['start_date'] ?? (string)$rental['start_date'],
                'end'    => $_POST['end_date'] ?? (string)($rental['end_date'] ?? ''),
              ];
              $genHref = 'https://brandnova.site/?' . http_build_query($genParams);
            ?>
            <a class="btn btn-outline-primary" target="_blank" rel="noopener" href="<?= e($genHref) ?>">
              Open Agreement Generator
            </a>
          </div>
        </div>
      </div>
    </div>

    <!-- Live Summary -->
    <div class="col-12">
      <div class="border rounded p-3 bg-light">
        <h2 class="h6 text-uppercase text-muted mb-3">Projected Summary</h2>
        <div class="row g-3">
          <div class="col-md-3">
            <div class="p-2 border rounded bg-white h-100">
              <div class="small text-muted">Projected Period</div>
              <div class="fw-bold" id="jsPeriod">—</div>
            </div>
          </div>
          <div class="col-md-3">
            <div class="p-2 border rounded bg-white h-100">
              <div class="small text-muted">Charge Basis</div>
              <div class="fw-bold" id="jsBasis">Weekly</div>
            </div>
          </div>
          <div class="col-md-3">
            <div class="p-2 border rounded bg-white h-100">
              <div class="small text-muted">Projected Units</div>
              <div class="fw-bold" id="jsUnits">0</div>
            </div>
          </div>
          <div class="col-md-3">
            <div class="p-2 border rounded bg-white h-100">
              <div class="small text-muted">Projected Total (£)</div>
              <div class="fw-bold" id="jsTotal">0.00</div>
            </div>
          </div>
        </div>
        <div class="small text-muted mt-2">
          Note: This is a preview. Actual payments are recorded in <strong>Accounts → Rental Payments</strong>.
        </div>
      </div>
    </div>
  </div>

  <div class="mt-3 d-flex gap-2">
    <button class="btn btn-dark" type="submit">Save Changes</button>
    <a href="list.php" class="btn btn-outline-secondary">Cancel</a>
  </div>
</form>

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

<script>
(function(){
  const q  = (s,p=document) => p.querySelector(s);
  const gv = (s) => (q(s)?.value || '').trim();
  const nf = (n) => isFinite(n) ? Number(n) : 0;

  function parseDate(str){
    if(!str) return null;
    const [y,m,d] = str.split('-').map(Number);
    if(!y||!m||!d) return null;
    return new Date(y, m-1, d);
  }
  function diffDays(a,b){
    const ms = b.getTime() - a.getTime();
    return Math.ceil(ms / 86400000);
  }
  function calc(){
    const start = parseDate(gv('input[name="start_date"]'));
    const end   = parseDate(gv('input[name="end_date"]'));
    const weekly= nf(parseFloat(gv('input[name="weekly_rate"]')));
    const freq  = gv('select[name="payment_frequency"]') || 'Weekly';

    q('#jsBasis').textContent = freq || 'Weekly';

    let period = 'Open-ended';
    if(start && end){
      period = `${start.toISOString().slice(0,10)} → ${end.toISOString().slice(0,10)}`;
    } else if (start){
      period = `${start.toISOString().slice(0,10)} → …`;
    } else if (end) {
      period = `… → ${end.toISOString().slice(0,10)}`;
    }
    q('#jsPeriod').textContent = period;

    let units = 0;
    if (start && end) {
      const days = Math.max(0, diffDays(start, end) + 1); // inclusive
      if (freq === 'Monthly') {
        units = Math.ceil(days / 30);  // rough months
      } else {
        units = Math.ceil(days / 7);   // weeks
      }
    }
    q('#jsUnits').textContent = String(units);

    const total = (freq === 'Monthly')
      ? units * weekly * 4.0
      : units * weekly;

    q('#jsTotal').textContent = (isFinite(total) ? total : 0).toFixed(2);
  }

  document.addEventListener('input', (e)=>{
    if (e.target.closest('.js-calc')) calc();
  });
  // initial
  calc();
})();
</script>
