<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
auth_require_login();
$pdo = crm_pdo();

$vehicleId = (int)($_GET['vehicle_id'] ?? $_POST['vehicle_id'] ?? 0);
if ($vehicleId <= 0) die('Missing vehicle_id.');

$stmt = $pdo->prepare("SELECT * FROM vehicles WHERE id = :id LIMIT 1");
$stmt->execute([':id' => $vehicleId]);
$vehicle = $stmt->fetch();
if (!$vehicle) die('Vehicle not found.');

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $serviceType = trim((string)($_POST['service_type'] ?? ''));
    $serviceDate = trim((string)($_POST['service_date'] ?? ''));
    $odometer = trim((string)($_POST['odometer_km'] ?? ''));
    $cost = (float)($_POST['cost'] ?? 0);
    $nextServiceKm = trim((string)($_POST['next_service_km'] ?? ''));
    $nextServiceDate = trim((string)($_POST['next_service_date'] ?? ''));
    $notes = trim((string)($_POST['notes'] ?? ''));

    if ($serviceDate === '') $errors[] = 'Service date is required.';
    if (!$errors) {
        $stmt = $pdo->prepare("
            INSERT INTO vehicle_services
                (vehicle_id, service_type, service_date, odometer_km, cost, notes, next_service_km, next_service_date)
            VALUES
                (:vid, :typ, :dt, :odo, :cost, :notes, :nskm, :nsdt)
        ");
        $stmt->execute([
            ':vid' => $vehicleId,
            ':typ' => $serviceType !== '' ? $serviceType : null,
            ':dt' => $serviceDate,
            ':odo' => $odometer !== '' ? (int)$odometer : null,
            ':cost' => $cost > 0 ? $cost : null,
            ':notes' => $notes !== '' ? $notes : null,
            ':nskm' => $nextServiceKm !== '' ? (int)$nextServiceKm : null,
            ':nsdt' => $nextServiceDate !== '' ? $nextServiceDate : null,
        ]);

        $stmt = $pdo->prepare("
            UPDATE vehicles
            SET last_service_date = :lsd,
                odometer_km = COALESCE(:odo, odometer_km),
                next_service_km = COALESCE(:nskm, next_service_km),
                next_service_date = COALESCE(:nsdt, next_service_date)
            WHERE id = :vid
        ");
        $stmt->execute([
            ':lsd' => $serviceDate,
            ':odo' => $odometer !== '' ? (int)$odometer : null,
            ':nskm' => $nextServiceKm !== '' ? (int)$nextServiceKm : null,
            ':nsdt' => $nextServiceDate !== '' ? $nextServiceDate : null,
            ':vid' => $vehicleId,
        ]);

        redirect('/public/vehicles/services.php?vehicle_id=' . $vehicleId);
    }
}

$stmt = $pdo->prepare("SELECT * FROM vehicle_services WHERE vehicle_id = :vid ORDER BY service_date DESC, id DESC");
$stmt->execute([':vid' => $vehicleId]);
$rows = $stmt->fetchAll();

$totalCost = 0.0;
foreach ($rows as $r) $totalCost += (float)($r['cost'] ?? 0);

$page_title = 'Vehicle services';
include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Vehicle services · <?php echo h($vehicle['license_plate']); ?></h1>
    <span><?php echo h(($vehicle['brand'] ?? '') . ' ' . ($vehicle['model'] ?? '')); ?></span>
  </div>
  <div class="page-header-actions">
    <a class="btn btn-secondary btn-sm" href="/public/vehicles/edit.php?id=<?php echo (int)$vehicleId; ?>">Back to vehicle</a>
  </div>
</div>

<div class="grid-2" style="margin-bottom:14px">
  <div class="card"><div class="small">Total service cost</div><div style="font-size:2rem;font-weight:700">€ <?php echo h(number_format($totalCost, 2)); ?></div></div>
  <div class="card"><div class="small">Next service</div><div style="font-size:1.1rem;font-weight:700"><?php echo h($vehicle['next_service_date']); ?> / <?php echo h($vehicle['next_service_km']); ?> km</div></div>
</div>

<div class="grid-2">
  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1rem">Add service record</h1></div>
    <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>
    <form method="post">
      <input type="hidden" name="vehicle_id" value="<?php echo (int)$vehicleId; ?>">
      <div class="form-grid">
        <div class="form-group"><label>Service type</label><input type="text" name="service_type" placeholder="Oil / Filters / Brakes"></div>
        <div class="form-group"><label>Service date</label><input type="date" name="service_date" value="<?php echo date('Y-m-d'); ?>" required></div>
        <div class="form-group"><label>Odometer km</label><input type="number" name="odometer_km"></div>
        <div class="form-group"><label>Cost</label><input type="number" step="0.01" name="cost"></div>
        <div class="form-group"><label>Next service km</label><input type="number" name="next_service_km"></div>
        <div class="form-group"><label>Next service date</label><input type="date" name="next_service_date"></div>
        <div class="form-group" style="grid-column:1/-1"><label>Notes</label><textarea name="notes"></textarea></div>
      </div>
      <div class="form-actions"><button class="btn btn-primary" type="submit">Save service</button></div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1rem">Service history</h1></div>
    <div class="table-responsive">
      <table class="table">
        <thead><tr><th>Date</th><th>Type</th><th>Km</th><th>Cost</th><th>Next</th><th>Notes</th></tr></thead>
        <tbody>
        <?php foreach ($rows as $r): ?>
          <tr>
            <td><?php echo h($r['service_date']); ?></td>
            <td><?php echo h($r['service_type']); ?></td>
            <td><?php echo h($r['odometer_km']); ?></td>
            <td>€ <?php echo h(number_format((float)($r['cost'] ?? 0), 2)); ?></td>
            <td><?php echo h($r['next_service_date']); ?> / <?php echo h($r['next_service_km']); ?> km</td>
            <td><?php echo h($r['notes']); ?></td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
