<?php
declare(strict_types=1);

/**
 * modules/rentals/view.php
 *
 * View a rental contract with:
 *  - Contract summary & financial snapshot
 *  - Agreement (view / upload / remove)
 *  - Payments (read-only snapshot from rental_payments if table exists)
 *  - Vehicle maintenance log (add & list)
 *
 * Parts:
 *  1) Bootstrap & guards
 *  2) Fetch rental + helpers (expected/paid/balance)
 *  3) Handle POST (upload/remove agreement, add maintenance)
 *  4) Render view
 */

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

function weeks_between_dates(string $startYmd, string $endYmd): int {
  $start = new DateTimeImmutable($startYmd);
  $end   = new DateTimeImmutable($endYmd);
  if ($end < $start) $end = $start;
  $days  = (int)$end->diff($start)->format('%a') + 1;
  $weeks = (int)ceil($days / 7);
  return max(1, $weeks);
}
function rental_expected_total(array $r, ?string $asOf = null): float {
  $rate = (float)($r['weekly_rate'] ?? 0);
  $start = (string)$r['start_date'];
  $end   = $asOf ?: ((string)($r['end_date'] ?? '') ?: (new DateTimeImmutable('today'))->format('Y-m-d'));
  if ($start === '') return 0.0;
  return weeks_between_dates($start, $end) * $rate;
}
function rental_paid_total_safe(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) {
    // If the table doesn't exist yet, return 0
    return 0.0;
  }
}

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

// Try to fetch payments detail list (read-only)
$payments = [];
try {
  $p = db()->prepare("
    SELECT id, paid_at, amount, method, reference, notes
      FROM rental_payments
     WHERE company_id=:cid AND rental_id=:rid
     ORDER BY paid_at DESC, id DESC
  ");
  $p->execute([':cid'=>$cid, ':rid'=>$rentalId]);
  $payments = $p->fetchAll();
} catch (Throwable $e) {
  // table might not exist; ignore
}

// Fetch maintenance logs for this vehicle (if any)
$maintLogs = [];
if (!empty($rent['vehicle_id'])) {
  try {
    $m = db()->prepare("
      SELECT id, service_date, service_type, notes, cost
        FROM vehicle_maintenance
       WHERE company_id=:cid AND vehicle_id=:vid
       ORDER BY service_date DESC, id DESC
       LIMIT 200
    ");
    $m->execute([':cid'=>$cid, ':vid'=>(int)$rent['vehicle_id']]);
    $maintLogs = $m->fetchAll();
  } catch (Throwable $e) {
    // table may not exist
  }
}
////////////////////////////////////////////////////////////////
// 3) Handle POST (upload/remove agreement, add maintenance)
////////////////////////////////////////////////////////////////
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));
    $action = (string)($_POST['action'] ?? '');

    // Upload / replace agreement
    if ($action === 'upload_agreement') {
      if (!isset($_FILES['agreement']) || ($_FILES['agreement']['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
        throw new RuntimeException('Please choose a file to upload.');
      }
      $f = $_FILES['agreement'];
      if ($f['error'] !== UPLOAD_ERR_OK) throw new RuntimeException('Upload failed.');

      $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
      $allowed = ['pdf','doc','docx','jpg','jpeg','png'];
      if ($ext && !in_array($ext, $allowed, true)) {
        throw new RuntimeException('Unsupported file type.');
      }

      $dir = project_root() . '/public/uploads/rentals';
      if (!is_dir($dir)) @mkdir($dir, 0775, true);
      $safe = 'rent_'.$rentalId.'_'.date('Ymd_His').'_'.bin2hex(random_bytes(3)).($ext?'.'.$ext:'');
      $dest = $dir . '/' . $safe;

      if (!move_uploaded_file($f['tmp_name'], $dest)) {
        throw new RuntimeException('Failed to move uploaded file.');
      }

      // Remove previous file if exists
      if (!empty($rent['agreement_url'])) {
        $prev = project_root().'/public/'.$rent['agreement_url'];
        if (is_file($prev)) @unlink($prev);
      }

      // Save URL (relative to /public)
      $url = 'uploads/rentals/'.$safe;
      $upd = db()->prepare("UPDATE rentals SET agreement_url=:u, updated_at=NOW() WHERE id=:id AND company_id=:cid LIMIT 1");
      $upd->execute([':u'=>$url, ':id'=>$rentalId, ':cid'=>$cid]);

      audit_log('rental.agreement.upload','rental',$rentalId,['agreement_url'=>$url]);
      $notice = 'Agreement uploaded.';
      $rent['agreement_url'] = $url; // update in-memory

    } elseif ($action === 'remove_agreement') {
      if (!empty($rent['agreement_url'])) {
        $prev = project_root().'/public/'.$rent['agreement_url'];
        if (is_file($prev)) @unlink($prev);
      }
      $upd = db()->prepare("UPDATE rentals SET agreement_url=NULL, updated_at=NOW() WHERE id=:id AND company_id=:cid LIMIT 1");
      $upd->execute([':id'=>$rentalId, ':cid'=>$cid]);
      audit_log('rental.agreement.remove','rental',$rentalId,null);
      $notice = 'Agreement removed.';
      $rent['agreement_url'] = null;

    } elseif ($action === 'add_maintenance') {
      if (empty($rent['vehicle_id'])) throw new RuntimeException('No vehicle linked to this rental.');

      $service_date = trim((string)($_POST['service_date'] ?? ''));
      $service_type = trim((string)($_POST['service_type'] ?? 'Other'));
      $notesM       = trim((string)($_POST['notes'] ?? ''));
      $cost         = (float)($_POST['cost'] ?? 0);

      if ($service_date === '') throw new RuntimeException('Service date is required.');

      $ins = db()->prepare("
        INSERT INTO vehicle_maintenance (company_id, vehicle_id, service_date, service_type, notes, cost, created_at)
        VALUES (:cid, :vid, :sd, :st, :nt, :cost, NOW())
      ");
      $ins->execute([
        ':cid'=>$cid, ':vid'=>(int)$rent['vehicle_id'],
        ':sd'=>$service_date, ':st'=>$service_type ?: 'Other',
        ':nt'=>$notesM !== '' ? $notesM : null,
        ':cost'=>$cost,
      ]);
      audit_log('vehicle.maintenance.add','vehicle',(int)$rent['vehicle_id'],[
        'rental_id'=>$rentalId,'date'=>$service_date,'type'=>$service_type,'cost'=>$cost
      ]);
      $notice = 'Maintenance log added.';

      // refresh logs
      try {
        $m = db()->prepare("
          SELECT id, service_date, service_type, notes, cost
            FROM vehicle_maintenance
           WHERE company_id=:cid AND vehicle_id=:vid
           ORDER BY service_date DESC, id DESC
           LIMIT 200
        ");
        $m->execute([':cid'=>$cid, ':vid'=>(int)$rent['vehicle_id']]);
        $maintLogs = $m->fetchAll();
      } catch (Throwable $e) { /* ignore */ }
    }

    // Recompute snapshot after changes
    $expected = rental_expected_total($rent);
    $paid     = rental_paid_total_safe($cid, $rentalId);
    $balance  = $expected - $paid;

  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV==='dev') ? $e->getMessage() : 'Action failed.';
  }
}

////////////////////////////////////////////////////////////////
// 4) Render view
////////////////////////////////////////////////////////////////
include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h1 class="h4 mb-0">Rental #<?= (int)$rent['id'] ?> — <?= e($rent['renter_name'] ?? 'Renter') ?></h1>
    <div class="text-muted small">
      Vehicle: <strong><?= e(($rent['reg_no'] ?? '—').' ('.($rent['type'] ?? '—').')') ?></strong>
      <?php if (!empty($rent['make']) || !empty($rent['model'])): ?>
        • <?= e(trim(($rent['make'] ?? '').' '.($rent['model'] ?? ''))) ?>
      <?php endif; ?>
    </div>
  </div>
  <div class="d-flex gap-2">
    <a href="<?= e(url_modules('rentals/list.php')) ?>" class="btn btn-outline-secondary">Back</a>
    <a href="<?= e(url_modules('rentals/edit.php')).'?id='.(int)$rent['id'] ?>" class="btn btn-outline-primary">Edit</a>
    <a href="<?= e(url_modules('rentals/close.php')).'?id='.(int)$rent['id'] ?>" class="btn btn-success">Close Contract</a>
    <a target="_blank" rel="noopener" href="https://brandnova.site" class="btn btn-dark">Generate Agreement</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; ?>

<div class="row g-3">
  <!-- Contract summary -->
  <div class="col-12 col-lg-6">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-2">Contract</h2>
        <dl class="row mb-0">
          <dt class="col-5">Status</dt>
          <dd class="col-7">
            <?php
              $map = ['Active'=>'success','Completed'=>'secondary','Overdue'=>'danger','Cancelled'=>'dark'];
              $cls = $map[$rent['status'] ?? 'Active'] ?? 'secondary';
            ?>
            <span class="badge text-bg-<?= e($cls) ?>"><?= e($rent['status'] ?? 'Active') ?></span>
          </dd>
          <dt class="col-5">Start / End</dt>
          <dd class="col-7"><?= e($rent['start_date'] ?? '—') ?> → <?= e($rent['end_date'] ?? '—') ?></dd>
          <dt class="col-5">Weekly Rate</dt>
          <dd class="col-7">£ <?= number_format((float)($rent['weekly_rate'] ?? 0), 2) ?></dd>
          <dt class="col-5">Deposit</dt>
          <dd class="col-7">£ <?= number_format((float)($rent['deposit_amount'] ?? 0), 2) ?>
            <?php if (!empty($rent['deposit_status'])): ?>
              <span class="badge text-bg-<?= e(($rent['deposit_status']==='Refunded')?'success':(($rent['deposit_status']==='Forfeited')?'danger':'secondary')) ?> ms-1">
                <?= e($rent['deposit_status']) ?>
              </span>
            <?php endif; ?>
          </dd>
          <dt class="col-5">Payment Frequency</dt>
          <dd class="col-7"><?= e($rent['payment_frequency'] ?? 'Weekly') ?></dd>
          <?php if (!empty($rent['payment_notes'])): ?>
            <dt class="col-5">Notes</dt>
            <dd class="col-7"><div class="small text-muted" style="white-space:pre-wrap;"><?= e($rent['payment_notes']) ?></div></dd>
          <?php endif; ?>
        </dl>
        <hr>
        <h2 class="h6 text-uppercase text-muted mb-2">Renter</h2>
        <dl class="row mb-0">
          <dt class="col-5">Name</dt><dd class="col-7"><?= e($rent['renter_name'] ?? '—') ?></dd>
          <dt class="col-5">Phone</dt><dd class="col-7"><?= e($rent['phone'] ?? '—') ?></dd>
          <?php if (!empty($rent['renter_email'])): ?>
            <dt class="col-5">Email</dt><dd class="col-7"><?= e($rent['renter_email']) ?></dd>
          <?php endif; ?>
          <?php if (!empty($rent['renter_address'])): ?>
            <dt class="col-5">Address</dt><dd class="col-7"><div class="small text-muted" style="white-space:pre-wrap;"><?= e($rent['renter_address']) ?></div></dd>
          <?php endif; ?>
        </dl>
      </div>
    </div>
  </div>

  <!-- Financial snapshot + Agreement -->
  <div class="col-12 col-lg-6">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-2">Financial Snapshot</h2>
        <div class="row g-3">
          <div class="col-4">
            <div class="p-2 border rounded bg-light">
              <div class="small text-muted">Expected</div>
              <div class="fw-bold">£ <?= number_format($expected, 2) ?></div>
            </div>
          </div>
          <div class="col-4">
            <div class="p-2 border rounded bg-light">
              <div class="small text-muted">Paid</div>
              <div class="fw-bold">£ <?= number_format($paid, 2) ?></div>
            </div>
          </div>
          <div class="col-4">
            <div class="p-2 border rounded bg-light">
              <div class="small text-muted">Balance</div>
              <?php $balCls = $balance > 0 ? 'danger' : ($balance < 0 ? 'success' : 'secondary'); ?>
              <div class="fw-bold text-<?= e($balCls) ?>">£ <?= number_format($balance, 2) ?></div>
            </div>
          </div>
        </div>

        <hr>
        <h2 class="h6 text-uppercase text-muted mb-2">Agreement</h2>
        <?php if (!empty($rent['agreement_url'])): ?>
          <div class="d-flex align-items-center justify-content-between">
            <div>
              <a target="_blank" href="<?= e(url_public($rent['agreement_url'])) ?>" class="btn btn-outline-primary btn-sm">View Agreement</a>
              <span class="text-muted small ms-2"><?= e($rent['agreement_url']) ?></span>
            </div>
            <form method="post" class="ms-2" onsubmit="return confirm('Remove current agreement file?');">
              <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
              <input type="hidden" name="id" value="<?= (int)$rent['id'] ?>">
              <input type="hidden" name="action" value="remove_agreement">
              <button class="btn btn-outline-danger btn-sm">Remove</button>
            </form>
          </div>
          <div class="text-muted small mt-2">Upload to replace the current file:</div>
        <?php else: ?>
          <div class="text-muted small mb-2">No agreement uploaded yet.</div>
        <?php endif; ?>

        <form method="post" enctype="multipart/form-data" class="mt-2">
          <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
          <input type="hidden" name="id" value="<?= (int)$rent['id'] ?>">
          <input type="hidden" name="action" value="upload_agreement">
          <div class="row g-2 align-items-end">
            <div class="col-md-8">
              <label class="form-label">Upload Agreement (PDF/DOC/Image)</label>
              <input type="file" name="agreement" class="form-control" required>
            </div>
            <div class="col-md-4 d-grid">
              <button class="btn btn-dark">Upload</button>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- Payments (read-only) -->
  <div class="col-12">
    <div class="card shadow-sm">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-center mb-2">
          <h2 class="h6 text-uppercase text-muted mb-0">Payments</h2>
          <div class="text-muted small">*(Recorded in Accounts → Rental Payments)</div>
        </div>
        <div class="table-responsive">
          <table class="table table-sm align-middle">
            <thead class="table-light">
              <tr>
                <th style="width:140px;">Date</th>
                <th style="width:120px;" class="text-end">Amount</th>
                <th style="width:140px;">Method</th>
                <th>Reference</th>
                <th>Notes</th>
              </tr>
            </thead>
            <tbody>
              <?php if ($payments): foreach ($payments as $p): ?>
                <tr>
                  <td><?= e($p['paid_at'] ?? '') ?></td>
                  <td class="text-end">£ <?= number_format((float)($p['amount'] ?? 0), 2) ?></td>
                  <td><?= e($p['method'] ?? '—') ?></td>
                  <td><?= e($p['reference'] ?? '—') ?></td>
                  <td><span class="text-muted small"><?= e($p['notes'] ?? '') ?></span></td>
                </tr>
              <?php endforeach; else: ?>
                <tr><td colspan="5" class="text-center text-muted">No payments recorded.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <!-- Maintenance -->
  <div class="col-12 col-xl-5">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-2">Add Maintenance Log</h2>
        <form method="post" class="row g-2">
          <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
          <input type="hidden" name="id" value="<?= (int)$rent['id'] ?>">
          <input type="hidden" name="action" value="add_maintenance">

          <div class="col-6">
            <label class="form-label">Date</label>
            <input type="date" class="form-control" name="service_date" value="<?= e(date('Y-m-d')) ?>" required>
          </div>
          <div class="col-6">
            <label class="form-label">Type</label>
            <select class="form-select" name="service_type">
              <?php foreach (['MOT','Insurance','PHV','Repairs','Other'] as $t): ?>
                <option value="<?= e($t) ?>"><?= e($t) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-12">
            <label class="form-label">Notes</label>
            <input class="form-control" name="notes" placeholder="Optional">
          </div>
          <div class="col-6">
            <label class="form-label">Cost (£)</label>
            <input type="number" step="0.01" class="form-control" name="cost" value="0.00">
          </div>
          <div class="col-6 d-grid align-self-end">
            <button class="btn btn-primary">Add Log</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <div class="col-12 col-xl-7">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-2">Maintenance History — <?= e($rent['reg_no'] ?? '—') ?></h2>
        <div class="table-responsive">
          <table class="table table-sm align-middle">
            <thead class="table-light">
              <tr>
                <th style="width:120px;">Date</th>
                <th style="width:140px;">Type</th>
                <th>Notes</th>
                <th style="width:120px;" class="text-end">Cost</th>
              </tr>
            </thead>
            <tbody>
              <?php if ($maintLogs): foreach ($maintLogs as $m): ?>
                <tr>
                  <td><?= e($m['service_date'] ?? '') ?></td>
                  <td><?= e($m['service_type'] ?? '') ?></td>
                  <td><span class="text-muted small"><?= e($m['notes'] ?? '') ?></span></td>
                  <td class="text-end">£ <?= number_format((float)($m['cost'] ?? 0), 2) ?></td>
                </tr>
              <?php endforeach; else: ?>
                <tr><td colspan="4" class="text-center text-muted">No maintenance logs.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

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