<?php
declare(strict_types=1);
/**
 * modules/rentals/add.php
 *
 * Create a rental contract.
 * - Validates overlapping active/overdue rentals for same vehicle
 * - Optional agreement upload (PDF/DOC/DOCX) saved under /public/uploads/rentals/
 * - “Auto-Generate Agreement” link (brandnova.site) opens in a new tab
 * - Client-side projected total (based on date range & payment frequency)
 */

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

/* ---------- Lookups ---------- */

// Vehicles (show reg_no + type); also mark currently rented (Active/Overdue and end_date >= today OR NULL)
$vehStmt = db()->prepare("
  SELECT v.id, v.reg_no, v.type
  FROM vehicles v
  WHERE v.company_id = :cid
  ORDER BY v.reg_no
");
$vehStmt->execute([':cid' => $cid]);
$vehicles = $vehStmt->fetchAll();

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

$errors = [];
$okMsg  = null;

/* ---------- POST ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  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'] ?? ''));

    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 (only if we have a vehicle & start date)
    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 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,
        ':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.';
      }
    }

    if (!$errors) {
      // Insert rental
      $ins = db()->prepare("
        INSERT INTO rentals (
          company_id, vehicle_id, renter_name, phone, renter_email, renter_address,
          weekly_rate, deposit_amount, start_date, end_date,
          status, deposit_status, payment_frequency, payment_notes, agreement_url, created_at, updated_at
        ) VALUES (
          :cid, :vid, :rname, :phone, :email, :addr,
          :weekly, :deposit, :sdate, :edate,
          :status, :dstatus, :pfreq, :pnotes, NULL, NOW(), NOW()
        )
      ");
      $ins->execute([
        ':cid'    => $cid,
        ':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),
      ]);
      $rid = (int)db()->lastInsertId();

      // Agreement upload (optional)
      if (isset($_FILES['agreement']) && $_FILES['agreement']['error'] !== UPLOAD_ERR_NO_FILE) {
        $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 {
            $dir = project_root() . '/public/uploads/rentals';
            if (!is_dir($dir)) @mkdir($dir, 0775, true);
            $name = 'rental_'.$rid.'_'.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 {
              $relUrl = 'uploads/rentals/' . $name;
              db()->prepare("UPDATE rentals SET agreement_url=:u WHERE id=:id")->execute([
                ':u' => $relUrl, ':id' => $rid
              ]);
            }
          }
        } else {
          $errors[] = 'Agreement upload failed.';
        }
      }

      if (!$errors) {
        audit_log('rental.create', 'rental', $rid, ['vehicle_id' => $vehicle_id, 'renter_name' => $renter_name]);
        redirect('list.php');
      }
    }
  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? $e->getMessage() : 'Unexpected error while creating rental.';
  }
}

/* ---------- View ---------- */
include dirname(__DIR__, 2) . '/includes/header.php';

// Pre-fill helpers
function sel($a, $b) { return ((string)$a === (string)$b) ? 'selected' : ''; }
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Add Rental Contract</h1>
  <a href="list.php" class="btn btn-outline-secondary">Back</a>
</div>

<div class="card shadow-sm">
  <div class="card-body">
    <?php if (!empty($okMsg)): ?><div class="alert alert-success"><?= e($okMsg) ?></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; ?>

    <form method="post" enctype="multipart/form-data" id="rentalForm" autocomplete="off">
      <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">

      <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'] ?? '') ?>">
              </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'] ?? '') ?>">
              </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'] ?? '') ?>">
              </div>
              <div class="col-12">
                <label class="form-label">Address</label>
                <textarea class="form-control" rows="2" name="renter_address"><?= e($_POST['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 foreach ($vehicles as $v):
                    $vid = (int)$v['id'];
                    $label = trim(($v['reg_no'] ?? '—') . ' (' . ($v['type'] ?? '—') . ')');
                    $warn  = isset($curRentedMap[$vid]) ? ' — Currently Rented' : '';
                  ?>
                    <option value="<?= $vid ?>" <?= sel($_POST['vehicle_id'] ?? '', $vid) ?>>
                      <?= e($label . $warn) ?>
                    </option>
                  <?php endforeach; ?>
                </select>
                <div class="form-text">Vehicles marked “Currently Rented” may still be available for a future start date.</div>
              </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'] ?? '') ?>">
              </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'] ?? '') ?>">
              </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'] ?? '') ?>">
              </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'] ?? '') ?>">
                <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'] ?? 'Active'; ?>
                <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'] ?? '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'] ?? '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'] ?? '') ?></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>
            <div class="row g-3 align-items-end">
              <div class="col-md-6">
                <label class="form-label">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
                  // Build a sensible link with current form inputs
                  $genParams = [
                    'renter' => $_POST['renter_name'] ?? '',
                    'phone'  => $_POST['phone'] ?? '',
                    'email'  => $_POST['renter_email'] ?? '',
                    'start'  => $_POST['start_date'] ?? '',
                    'end'    => $_POST['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">Create Rental</button>
        <a href="list.php" class="btn btn-outline-secondary">Cancel</a>
      </div>
    </form>
  </div>
</div>

<?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') {
        // rough months: 30-day buckets
        units = Math.ceil(days / 30);
      } else {
        // weekly
        units = Math.ceil(days / 7);
      }
    }
    q('#jsUnits').textContent = String(units);

    const total = (freq === 'Monthly')
      ? units * weekly * 4.0 / 1.0   // assume weekly rate *4 per “month”
      : units * weekly;

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

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