<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
require_once __DIR__ . '/../../app/core/access_guards.php';
auth_require_login();

$pdo = crm_pdo();
gp_require_staff_access($pdo);
$page_title = 'Vehicle';

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$item = [
    'code' => '',
    'license_plate' => '',
    'brand' => '',
    'model' => '',
    'vehicle_type' => '',
    'year' => '',
    'color' => '',
    'fuel_type' => '',
    'vin' => '',
    'odometer_km' => '',
    'next_service_km' => '',
    'last_service_date' => '',
    'next_service_date' => '',
    'insurance_expiry' => '',
    'kteo_expiry' => '',
    'road_tax_expiry' => '',
    'notes' => '',
    'active' => 1,
];

$errors = [];

if ($id) {
    $st = $pdo->prepare("
        SELECT code, license_plate, brand, model, vehicle_type, year, color, fuel_type, vin,
               odometer_km, next_service_km, last_service_date, next_service_date,
               insurance_expiry, kteo_expiry, road_tax_expiry, notes, active
        FROM vehicles
        WHERE id = :id
        LIMIT 1
    ");
    $st->execute([':id' => $id]);
    $row = $st->fetch();
    if ($row) {
        $item = array_merge($item, $row);
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);

    foreach (array_keys($item) as $k) {
        if ($k === 'active') continue;
        $item[$k] = trim((string)($_POST[$k] ?? ''));
    }
    $item['active'] = isset($_POST['active']) ? 1 : 0;

    if ($item['license_plate'] === '') {
        $errors[] = 'License plate is required.';
    }
    if ($item['code'] === '') {
        $item['code'] = 'VEH-' . date('Ymd-His');
    }

    if (!$errors) {
        $params = [
            ':code' => $item['code'],
            ':license_plate' => $item['license_plate'],
            ':brand' => $item['brand'] !== '' ? $item['brand'] : null,
            ':model' => $item['model'] !== '' ? $item['model'] : null,
            ':vehicle_type' => $item['vehicle_type'] !== '' ? $item['vehicle_type'] : null,
            ':year' => $item['year'] !== '' ? $item['year'] : null,
            ':color' => $item['color'] !== '' ? $item['color'] : null,
            ':fuel_type' => $item['fuel_type'] !== '' ? $item['fuel_type'] : null,
            ':vin' => $item['vin'] !== '' ? $item['vin'] : null,
            ':odometer_km' => $item['odometer_km'] !== '' ? $item['odometer_km'] : null,
            ':next_service_km' => $item['next_service_km'] !== '' ? $item['next_service_km'] : null,
            ':last_service_date' => $item['last_service_date'] !== '' ? $item['last_service_date'] : null,
            ':next_service_date' => $item['next_service_date'] !== '' ? $item['next_service_date'] : null,
            ':insurance_expiry' => $item['insurance_expiry'] !== '' ? $item['insurance_expiry'] : null,
            ':kteo_expiry' => $item['kteo_expiry'] !== '' ? $item['kteo_expiry'] : null,
            ':road_tax_expiry' => $item['road_tax_expiry'] !== '' ? $item['road_tax_expiry'] : null,
            ':notes' => $item['notes'] !== '' ? $item['notes'] : null,
            ':active' => $item['active'],
        ];

        if ($id > 0) {
            $sql = "
                UPDATE vehicles
                SET
                    code = :code,
                    license_plate = :license_plate,
                    brand = :brand,
                    model = :model,
                    vehicle_type = :vehicle_type,
                    year = :year,
                    color = :color,
                    fuel_type = :fuel_type,
                    vin = :vin,
                    odometer_km = :odometer_km,
                    next_service_km = :next_service_km,
                    last_service_date = :last_service_date,
                    next_service_date = :next_service_date,
                    insurance_expiry = :insurance_expiry,
                    kteo_expiry = :kteo_expiry,
                    road_tax_expiry = :road_tax_expiry,
                    notes = :notes,
                    active = :active
                WHERE id = :id
            ";
            $params[':id'] = $id;
        } else {
            $sql = "
                INSERT INTO vehicles
                    (code, license_plate, brand, model, vehicle_type, year, color, fuel_type, vin,
                     odometer_km, next_service_km, last_service_date, next_service_date,
                     insurance_expiry, kteo_expiry, road_tax_expiry, notes, active)
                VALUES
                    (:code, :license_plate, :brand, :model, :vehicle_type, :year, :color, :fuel_type, :vin,
                     :odometer_km, :next_service_km, :last_service_date, :next_service_date,
                     :insurance_expiry, :kteo_expiry, :road_tax_expiry, :notes, :active)
            ";
        }

        $st = $pdo->prepare($sql);
        $st->execute($params);

        redirect('/public/vehicles/index.php');
    }
}

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
    <div class="page-header-title">
        <h1><?php echo $id ? 'Edit vehicle' : 'New vehicle'; ?></h1>
    </div>
</div>

<div class="card">
    <?php if ($errors): ?>
        <div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div>
    <?php endif; ?>

    <form method="post">
        <input type="hidden" name="id" value="<?php echo (int)$id; ?>">

        <div class="form-grid">
            <div class="form-group"><label>Code</label><input name="code" value="<?php echo h($item['code']); ?>"></div>
            <div class="form-group"><label>License plate</label><input name="license_plate" value="<?php echo h($item['license_plate']); ?>"></div>
            <div class="form-group"><label>Brand</label><input name="brand" value="<?php echo h($item['brand']); ?>"></div>
            <div class="form-group"><label>Model</label><input name="model" value="<?php echo h($item['model']); ?>"></div>
            <div class="form-group"><label>Type</label><input name="vehicle_type" value="<?php echo h($item['vehicle_type']); ?>"></div>
            <div class="form-group"><label>Year</label><input name="year" value="<?php echo h($item['year']); ?>"></div>
            <div class="form-group"><label>Color</label><input name="color" value="<?php echo h($item['color']); ?>"></div>
            <div class="form-group"><label>Fuel type</label><input name="fuel_type" value="<?php echo h($item['fuel_type']); ?>"></div>
            <div class="form-group"><label>VIN</label><input name="vin" value="<?php echo h($item['vin']); ?>"></div>
            <div class="form-group"><label>Odometer km</label><input name="odometer_km" value="<?php echo h($item['odometer_km']); ?>"></div>
            <div class="form-group"><label>Next service km</label><input name="next_service_km" value="<?php echo h($item['next_service_km']); ?>"></div>
            <div class="form-group"><label>Last service date</label><input type="date" name="last_service_date" value="<?php echo h($item['last_service_date']); ?>"></div>
            <div class="form-group"><label>Next service date</label><input type="date" name="next_service_date" value="<?php echo h($item['next_service_date']); ?>"></div>
            <div class="form-group"><label>Insurance expiry</label><input type="date" name="insurance_expiry" value="<?php echo h($item['insurance_expiry']); ?>"></div>
            <div class="form-group"><label>KTEO expiry</label><input type="date" name="kteo_expiry" value="<?php echo h($item['kteo_expiry']); ?>"></div>
            <div class="form-group"><label>Road tax expiry</label><input type="date" name="road_tax_expiry" value="<?php echo h($item['road_tax_expiry']); ?>"></div>
            <div class="form-group"><label>Active</label><div><input type="checkbox" name="active" <?php echo ((int)$item['active'] === 1) ? 'checked' : ''; ?>></div></div>
            <div class="form-group" style="grid-column:1/-1"><label>Notes</label><textarea name="notes"><?php echo h($item['notes']); ?></textarea></div>
        </div>

        <div class="form-actions">
            <button class="btn btn-primary" type="submit">Save</button>
            <a class="btn btn-secondary" href="/public/vehicles/index.php">Cancel</a>
        </div>
    </form>
</div>

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