<?php
// /htdocs/pages/vendor/rides-fleet-edit.php — Add/Edit vehicle/asset
if (!defined('APP_START')) { http_response_code(403); exit('Direct access denied'); }
$vendor = getVendor();
if (!$vendor) { redirect('/?page=dashboard'); exit; }
$db = db();
$provider = $db->fetchOne("SELECT * FROM ride_providers WHERE vendor_id = ? LIMIT 1", [(int)$vendor['id']]);
if (!$provider) { redirect('/?page/vendor-rides'); exit; }

$vehicleId = (int)($_GET['id'] ?? 0);
$vehicle = null;
if ($vehicleId > 0) {
    $vehicle = $db->fetchOne(
        "SELECT * FROM ride_vehicles WHERE id = ? AND provider_id = ? LIMIT 1",
        [$vehicleId, (int)$provider['id']]
    );
    if (!$vehicle) { redirect('/?page=vendor-rides-fleet'); exit; }
}

$flash = null;
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $assetType = $_POST['asset_type'] ?? 'car';
        $classId = (int)($_POST['class_id'] ?? 0);
        $make = trim($_POST['make'] ?? '');
        $model = trim($_POST['model'] ?? '');
        $year = (int)($_POST['year'] ?? 0) ?: null;
        $color = trim($_POST['color'] ?? '');
        $licensePlate = trim($_POST['license_plate'] ?? '');
        $registrationNumber = trim($_POST['registration_number'] ?? '') ?: null;
        $registrationAuthority = trim($_POST['registration_authority'] ?? '') ?: null;
        $imoNumber = trim($_POST['imo_number'] ?? '') ?: null;
        $callsign = trim($_POST['callsign'] ?? '') ?: null;
        $capacity = max(1, (int)($_POST['capacity'] ?? 4));
        $luggage = max(0, (int)($_POST['luggage_capacity'] ?? 2));
        $photo = trim($_POST['photo'] ?? '') ?: null;
        $insuranceExpiry = $_POST['insurance_expiry'] ?? null;
        $registrationExpiry = $_POST['registration_expiry'] ?? null;
        $inspectionExpiry = $_POST['inspection_expiry'] ?? null;

        $engineType = trim($_POST['engine_type'] ?? '') ?: null;
        $hullMaterial = trim($_POST['hull_material'] ?? '') ?: null;
        $yearMfg = (int)($_POST['year_of_manufacture'] ?? 0) ?: null;
        $lengthM = (float)($_POST['length_meters'] ?? 0) ?: null;
        $beamM = (float)($_POST['beam_meters'] ?? 0) ?: null;
        $draftM = (float)($_POST['draft_meters'] ?? 0) ?: null;
        $maxSpeedKnots = (float)($_POST['max_speed_knots'] ?? 0) ?: null;
        $fuelCapacity = (float)($_POST['fuel_capacity_liters'] ?? 0) ?: null;
        $maxRange = (float)($_POST['max_range_km'] ?? 0) ?: null;
        $safetyEquipment = trim($_POST['safety_equipment'] ?? '') ?: null;
        $crewCount = (int)($_POST['crew_count'] ?? 0);
        $catering = !empty($_POST['catering_available']) ? 1 : 0;
        $wifi = !empty($_POST['wifi_available']) ? 1 : 0;
        $notes = trim($_POST['notes'] ?? '') ?: null;

        if ($classId <= 0) $errors[] = 'Vehicle class is required';
        if ($make === '') $errors[] = 'Make is required';
        if ($model === '') $errors[] = 'Model is required';
        if ($licensePlate === '') $errors[] = 'License plate / registration ID is required';

        if (empty($errors)) {
            $payload = [
                'asset_type' => $assetType,
                'class_id' => $classId,
                'make' => $make,
                'model' => $model,
                'year' => $year,
                'color' => $color,
                'license_plate' => $licensePlate,
                'registration_number' => $registrationNumber,
                'registration_authority' => $registrationAuthority,
                'imo_number' => $imoNumber,
                'callsign' => $callsign,
                'capacity' => $capacity,
                'luggage_capacity' => $luggage,
                'photo' => $photo,
                'insurance_expiry' => $insuranceExpiry ?: null,
                'registration_expiry' => $registrationExpiry ?: null,
                'inspection_expiry' => $inspectionExpiry ?: null,
                'engine_type' => $engineType,
                'hull_material' => $hullMaterial,
                'year_of_manufacture' => $yearMfg,
                'length_meters' => $lengthM,
                'beam_meters' => $beamM,
                'draft_meters' => $draftM,
                'max_speed_knots' => $maxSpeedKnots,
                'fuel_capacity_liters' => $fuelCapacity,
                'max_range_km' => $maxRange,
                'safety_equipment' => $safetyEquipment,
                'crew_count' => $crewCount,
                'catering_available' => $catering,
                'wifi_available' => $wifi,
                'notes' => $notes,
            ];

            if ($vehicleId > 0) {
                $sets = []; $params = [];
                foreach ($payload as $k => $v) { $sets[] = "$k = ?"; $params[] = $v; }
                $params[] = $vehicleId;
                $params[] = (int)$provider['id'];
                $db->query("UPDATE ride_vehicles SET " . implode(', ', $sets) . " WHERE id = ? AND provider_id = ?", $params);
                $flash = 'Asset updated';
            } else {
                $cols = array_keys($payload);
                $cols[] = 'provider_id';
                $cols[] = 'is_active';
                $payload['provider_id'] = (int)$provider['id'];
                $payload['is_active'] = 1;
                $placeholders = implode(',', array_fill(0, count($payload), '?'));
                                $db->query(
                    "INSERT INTO ride_vehicles (" . implode(', ', $cols) . ") VALUES ($placeholders)",
                    array_values($payload)
                );
                $vehicleId = (int)$db->lastInsertId();
                $flash = 'Asset added';
            }

            // Reload
            $vehicle = $db->fetchOne("SELECT * FROM ride_vehicles WHERE id = ?", [$vehicleId]);
        }
    } catch (Throwable $e) {
        if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
            $errors[] = 'A vehicle with this license plate already exists.';
        } else {
            $errors[] = $e->getMessage();
        }
    }
}

// Load classes
$classes = [];
try {
    $classes = $db->fetchAll("SELECT * FROM ride_classes WHERE is_active = 1 ORDER BY display_order") ?: [];
} catch (Throwable $e) {}

$pageTitle = ($vehicleId > 0 ? 'Edit Asset' : 'Add Asset') . ' — ' . $provider['name'];
require_once __DIR__ . '/../../includes/header.php';
?>

<style>
.fe-page { background: #0f0c29; min-height: 100vh; padding: 100px 0 80px; color: white; }
.fe-page .container { max-width: 900px; margin: 0 auto; padding: 0 20px; }
.fe-head { display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 16px; margin-bottom: 24px; }
.fe-head h1 { font-size: 28px; font-weight: 800; margin-bottom: 4px; }
.fe-head p { color: #a0aec0; font-size: 13px; }
.fe-card { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 16px; padding: 26px; }
.fe-flash { background: rgba(0,184,148,0.12); border: 1px solid rgba(0,184,148,0.3); color: #00b894; border-radius: 10px; padding: 14px 18px; margin-bottom: 20px; font-size: 13px; }
.fe-error { background: rgba(245,87,108,0.12); border: 1px solid rgba(245,87,108,0.3); color: #f5576c; border-radius: 10px; padding: 14px 18px; margin-bottom: 20px; font-size: 13px; }
.fe-section { padding: 20px 0; border-bottom: 1px solid rgba(255,255,255,0.08); }
.fe-section:first-of-type { padding-top: 0; }
.fe-section:last-of-type { border-bottom: none; padding-bottom: 0; }
.fe-section h2 { font-size: 15px; font-weight: 800; margin-bottom: 16px; display: flex; align-items: center; gap: 8px; }
.fe-field { margin-bottom: 16px; }
.fe-field label { display: block; font-size: 11px; font-weight: 800; color: #a3bffa; margin-bottom: 6px; text-transform: uppercase; letter-spacing: 0.05em; }
.fe-field input, .fe-field select, .fe-field textarea { width: 100%; padding: 11px 14px; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); border-radius: 10px; color: white; font-size: 14px; outline: none; font-family: inherit; transition: all 0.2s; }
.fe-field input:focus, .fe-field select:focus, .fe-field textarea:focus { border-color: rgba(102,126,234,0.6); box-shadow: 0 0 0 3px rgba(102,126,234,0.15); }
.fe-field select option { background: #1a1a2e; }
.fe-field textarea { min-height: 70px; resize: vertical; }
.fe-field .hint { font-size: 10.5px; color: #718096; margin-top: 4px; }
.fe-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.fe-row-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 16px; }
@media (max-width: 640px) { .fe-row, .fe-row-3 { grid-template-columns: 1fr; } }
.fe-types { display: grid; grid-template-columns: repeat(auto-fill, minmax(110px, 1fr)); gap: 8px; margin-bottom: 16px; }
.fe-type-opt { padding: 12px 8px; background: rgba(255,255,255,0.03); border: 2px solid rgba(255,255,255,0.08); border-radius: 10px; cursor: pointer; text-align: center; transition: all 0.15s; }
.fe-type-opt:hover { border-color: rgba(102,126,234,0.4); }
.fe-type-opt.selected { border-color: #667eea; background: rgba(102,126,234,0.12); }
.fe-type-opt i { font-size: 20px; color: #a3bffa; margin-bottom: 6px; display: block; }
.fe-type-opt .label { font-size: 11px; font-weight: 700; }
.fe-toggle { display: flex; align-items: center; gap: 10px; padding: 10px 0; }
.fe-toggle input { width: auto; transform: scale(1.3); accent-color: #667eea; }
.fe-toggle label { margin: 0; text-transform: none; letter-spacing: 0; font-size: 13px; color: #cbd5e0; font-weight: 500; }
.fe-actions { display: flex; gap: 10px; margin-top: 24px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.08); }
.fe-btn { padding: 12px 24px; border-radius: 10px; font-size: 13px; font-weight: 800; cursor: pointer; border: none; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; }
.fe-btn-primary { background: linear-gradient(135deg, #667eea, #764ba2); color: white; }
.fe-btn-outline { background: rgba(255,255,255,0.05); color: #cbd5e0; border: 1px solid rgba(255,255,255,0.08); }
.fe-conditional { display: none; }
.fe-conditional.active { display: block; }
</style>

<div class="fe-page">
    <div class="container">

        <div class="fe-head">
            <div>
                <h1><?= $vehicleId > 0 ? '✏️ Edit asset' : '➕ Add new asset' ?></h1>
                <p><?= htmlspecialchars($provider['name']) ?></p>
            </div>
            <a href="/?page=vendor-rides-fleet" class="fe-btn fe-btn-outline">
                <i class="fas fa-arrow-left"></i> Back to fleet
            </a>
        </div>

        <?php if ($flash): ?><div class="fe-flash"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($flash) ?></div><?php endif; ?>
        <?php foreach ($errors as $err): ?><div class="fe-error"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($err) ?></div><?php endforeach; ?>

        <form method="POST" class="fe-card">
            <?php
            $v = $vehicle ?: [];
            $currentType = $v['asset_type'] ?? 'car';
            ?>

            <div class="fe-section">
                <h2><i class="fas fa-tag" style="color: #a3bffa;"></i> Asset type</h2>
                <input type="hidden" name="asset_type" id="assetTypeInput" value="<?= htmlspecialchars($currentType) ?>">
                <div class="fe-types">
                    <?php foreach ([
                        ['car', 'car', 'Car'],
                        ['suv', 'truck-pickup', 'SUV'],
                        ['van', 'van-shuttle', 'Van'],
                        ['bus', 'bus', 'Bus'],
                        ['truck', 'truck', 'Truck'],
                        ['motorcycle', 'motorcycle', 'Motorcycle'],
                        ['bicycle', 'bicycle', 'Bicycle'],
                        ['boat', 'ship', 'Boat'],
                        ['yacht', 'sailboat', 'Yacht'],
                        ['ferry', 'ferry', 'Ferry'],
                        ['helicopter', 'helicopter', 'Helicopter'],
                        ['aircraft', 'plane', 'Aircraft'],
                        ['other', 'question', 'Other'],
                    ] as $opt): ?>
                        <div class="fe-type-opt <?= $currentType === $opt[0] ? 'selected' : '' ?>" data-type="<?= $opt[0] ?>" onclick="selectType('<?= $opt[0] ?>')">
                            <i class="fas fa-<?= $opt[1] ?>"></i>
                            <div class="label"><?= $opt[2] ?></div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="fe-section">
                <h2><i class="fas fa-info-circle" style="color: #a3bffa;"></i> Basic details</h2>
                <div class="fe-row">
                    <div class="fe-field">
                        <label>Make *</label>
                        <input type="text" name="make" required value="<?= htmlspecialchars($v['make'] ?? '') ?>" placeholder="e.g., Toyota / Sunseeker / Boeing">
                    </div>
                    <div class="fe-field">
                        <label>Model *</label>
                        <input type="text" name="model" required value="<?= htmlspecialchars($v['model'] ?? '') ?>" placeholder="e.g., Corolla / Manhattan 52 / 737">
                    </div>
                </div>
                <div class="fe-row-3">
                    <div class="fe-field">
                        <label>Year</label>
                        <input type="number" name="year" min="1900" max="<?= date('Y') + 1 ?>" value="<?= htmlspecialchars((string)($v['year'] ?? '')) ?>">
                    </div>
                    <div class="fe-field">
                        <label>Color</label>
                        <input type="text" name="color" value="<?= htmlspecialchars($v['color'] ?? '') ?>">
                    </div>
                    <div class="fe-field">
                        <label>Class *</label>
                        <select name="class_id" required>
                            <option value="">— Select —</option>
                            <?php foreach ($classes as $c): ?>
                                <option value="<?= (int)$c['id'] ?>" <?= (int)($v['class_id'] ?? 0) === (int)$c['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($c['label']) ?> · <?= ucfirst($c['asset_category'] ?? 'ground') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="fe-field">
                    <label>License plate / Registration ID *</label>
                    <input type="text" name="license_plate" required value="<?= htmlspecialchars($v['license_plate'] ?? '') ?>" placeholder="e.g., T123ABC / IMO 9876543">
                </div>
            </div>

            <!-- WATER / AIR SPECIFIC SECTION -->
            <div class="fe-section fe-conditional <?= in_array($currentType, ['boat','yacht','ferry','helicopter','aircraft']) ? 'active' : '' ?>" id="waterAirSection">
                <h2><i class="fas fa-anchor" style="color: #00d4ff;"></i> Maritime / Aviation details</h2>
                <div class="fe-row">
                    <div class="fe-field">
                        <label>Registration number</label>
                        <input type="text" name="registration_number" value="<?= htmlspecialchars($v['registration_number'] ?? '') ?>">
                    </div>
                    <div class="fe-field">
                        <label>Registration authority</label>
                        <input type="text" name="registration_authority" value="<?= htmlspecialchars($v['registration_authority'] ?? '') ?>" placeholder="e.g., TASAC / TCAA">
                    </div>
                </div>
                <div class="fe-row">
                    <div class="fe-field">
                        <label>IMO number (vessels)</label>
                        <input type="text" name="imo_number" value="<?= htmlspecialchars($v['imo_number'] ?? '') ?>">
                    </div>
                    <div class="fe-field">
                        <label>Callsign</label>
                        <input type="text" name="callsign" value="<?= htmlspecialchars($v['callsign'] ?? '') ?>">
                    </div>
                </div>
                <div class="fe-row-3">
                    <div class="fe-field">
                        <label>Length (m)</label>
                        <input type="number" step="0.01" name="length_meters" value="<?= htmlspecialchars((string)($v['length_meters'] ?? '')) ?>">
                    </div>
                    <div class="fe-field">
                        <label>Beam (m)</label>
                        <input type="number" step="0.01" name="beam_meters" value="<?= htmlspecialchars((string)($v['beam_meters'] ?? '')) ?>">
                    </div>
                    <div class="fe-field">
                        <label>Draft (m)</label>
                        <input type="number" step="0.01" name="draft_meters" value="<?= htmlspecialchars((string)($v['draft_meters'] ?? '')) ?>">
                    </div>
                </div>
                <div class="fe-row-3">
                    <div class="fe-field">
                        <label>Max speed (knots)</label>
                        <input type="number" step="0.1" name="max_speed_knots" value="<?= htmlspecialchars((string)($v['max_speed_knots'] ?? '')) ?>">
                    </div>
                    <div class="fe-field">
                        <label>Fuel capacity (L)</label>
                        <input type="number" step="0.01" name="fuel_capacity_liters" value="<?= htmlspecialchars((string)($v['fuel_capacity_liters'] ?? '')) ?>">
                    </div>
                    <div class="fe-field">
                        <label>Max range (km)</label>
                        <input type="number" step="0.01" name="max_range_km" value="<?= htmlspecialchars((string)($v['max_range_km'] ?? '')) ?>">
                    </div>
                </div>
                <div class="fe-row">
                    <div class="fe-field">
                        <label>Hull material</label>
                        <input type="text" name="hull_material" value="<?= htmlspecialchars($v['hull_material'] ?? '') ?>" placeholder="e.g., Fiberglass / Steel">
                    </div>
                    <div class="fe-field">
                        <label>Engine type</label>
                        <input type="text" name="engine_type" value="<?= htmlspecialchars($v['engine_type'] ?? '') ?>" placeholder="e.g., Twin Diesel / Turbofan">
                    </div>
                </div>
                <div class="fe-field">
                    <label>Safety equipment</label>
                    <textarea name="safety_equipment" placeholder="e.g., Life jackets x 20, EPIRB, VHF radio, First aid kit"><?= htmlspecialchars($v['safety_equipment'] ?? '') ?></textarea>
                </div>
                <div class="fe-row-3">
                    <div class="fe-field">
                        <label>Crew count</label>
                        <input type="number" name="crew_count" min="0" value="<?= htmlspecialchars((string)($v['crew_count'] ?? 0)) ?>">
                    </div>
                    <div class="fe-toggle">
                        <input type="checkbox" name="catering_available" id="catering" value="1" <?= !empty($v['catering_available']) ? 'checked' : '' ?>>
                        <label for="catering">Catering available</label>
                    </div>
                    <div class="fe-toggle">
                        <input type="checkbox" name="wifi_available" id="wifi" value="1" <?= !empty($v['wifi_available']) ? 'checked' : '' ?>>
                        <label for="wifi">WiFi available</label>
                    </div>
                </div>
            </div>

            <div class="fe-section">
                <h2><i class="fas fa-users" style="color: #00b894;"></i> Capacity</h2>
                <div class="fe-row">
                    <div class="fe-field">
                        <label>Passenger capacity *</label>
                        <input type="number" name="capacity" required min="1" value="<?= htmlspecialchars((string)($v['capacity'] ?? 4)) ?>">
                    </div>
                    <div class="fe-field">
                        <label>Luggage capacity</label>
                        <input type="number" name="luggage_capacity" min="0" value="<?= htmlspecialchars((string)($v['luggage_capacity'] ?? 2)) ?>">
                    </div>
                </div>
            </div>

            <div class="fe-section">
                <h2><i class="fas fa-image" style="color: #b794f4;"></i> Media</h2>
                <div class="fe-field">
                    <label>Photo URL</label>
                    <input type="url" name="photo" value="<?= htmlspecialchars($v['photo'] ?? '') ?>" placeholder="https://...">
                    <div class="hint">Recommended: 800×600px. Leave blank to use a default icon.</div>
                </div>
            </div>

            <div class="fe-section">
                <h2><i class="fas fa-calendar-times" style="color: #f6ad55;"></i> Compliance dates</h2>
                <div class="fe-row-3">
                    <div class="fe-field">
                        <label>Insurance expiry</label>
                        <input type="date" name="insurance_expiry" value="<?= htmlspecialchars($v['insurance_expiry'] ?? '') ?>">
                    </div>
                    <div class="fe-field">
                        <label>Registration expiry</label>
                        <input type="date" name="registration_expiry" value="<?= htmlspecialchars($v['registration_expiry'] ?? '') ?>">
                    </div>
                    <div class="fe-field">
                        <label>Inspection expiry</label>
                        <input type="date" name="inspection_expiry" value="<?= htmlspecialchars($v['inspection_expiry'] ?? '') ?>">
                    </div>
                </div>
            </div>

            <div class="fe-section">
                <h2><i class="fas fa-sticky-note" style="color: #a0aec0;"></i> Internal notes</h2>
                <div class="fe-field">
                    <textarea name="notes" placeholder="Any internal notes about this asset (visible only to staff)"><?= htmlspecialchars($v['notes'] ?? '') ?></textarea>
                </div>
            </div>

            <div class="fe-actions">
                <button type="submit" class="fe-btn fe-btn-primary">
                    <i class="fas fa-save"></i> <?= $vehicleId > 0 ? 'Save changes' : 'Add to fleet' ?>
                </button>
                <a href="/?page=vendor-rides-fleet" class="fe-btn fe-btn-outline">Cancel</a>
            </div>
        </form>

    </div>
</div>

<script>
function selectType(type) {
    document.getElementById('assetTypeInput').value = type;
    document.querySelectorAll('.fe-type-opt').forEach(el => el.classList.toggle('selected', el.dataset.type === type));

    const waterAir = ['boat', 'yacht', 'ferry', 'helicopter', 'aircraft'];
    const section = document.getElementById('waterAirSection');
    if (waterAir.includes(type)) {
        section.classList.add('active');
    } else {
        section.classList.remove('active');
    }
}
</script>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>