<?php
// /htdocs/pages/vendor/rides-fleet.php — FLEET MANAGEMENT
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; }

$flash = null;
$errors = [];

// ============================================================
// POST HANDLERS
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $action = $_POST['action'] ?? '';
        $vehicleId = (int)($_POST['vehicle_id'] ?? 0);

        if ($action === 'delete') {
            $activeRides = $db->fetchOne(
                "SELECT COUNT(*) AS n FROM ride_bookings WHERE vehicle_id = ? AND status IN ('driver_assigned','driver_arriving','driver_arrived','in_progress')",
                [$vehicleId]
            );
            if ((int)($activeRides['n'] ?? 0) > 0) {
                throw new RuntimeException('Cannot delete: vehicle is assigned to active rides');
            }
            $db->query("UPDATE ride_vehicles SET is_active = 0 WHERE id = ? AND provider_id = ?", [$vehicleId, (int)$provider['id']]);
            $flash = 'Vehicle deactivated';
        } elseif ($action === 'reactivate') {
            $db->query("UPDATE ride_vehicles SET is_active = 1 WHERE id = ? AND provider_id = ?", [$vehicleId, (int)$provider['id']]);
            $flash = 'Vehicle reactivated';
        } elseif ($action === 'toggle_available') {
            $db->query("UPDATE ride_vehicles SET is_available = 1 - is_available WHERE id = ? AND provider_id = ?", [$vehicleId, (int)$provider['id']]);
            $flash = 'Availability toggled';
        }
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
    redirect('/?page=vendor-rides-fleet');
    exit;
}

// ============================================================
// LOAD DATA
// ============================================================
$filterType = $_GET['type'] ?? '';
$where = ['v.provider_id = ?'];
$params = [(int)$provider['id']];
if ($filterType !== '') {
    $where[] = 'v.asset_type = ?';
    $params[] = $filterType;
}

$vehicles = [];
try {
    $vehicles = $db->fetchAll(
        "SELECT v.*, 
                c.label AS class_label, 
                c.icon AS class_icon,
                (SELECT COUNT(*) FROM ride_bookings b WHERE b.vehicle_id = v.id) AS total_rides,
                (SELECT d.full_name FROM ride_driver_vehicles dv 
                 INNER JOIN ride_drivers d ON d.id = dv.driver_id 
                 WHERE dv.vehicle_id = v.id AND dv.is_current = 1 LIMIT 1) AS current_driver
         FROM ride_vehicles v
         LEFT JOIN ride_classes c ON c.id = v.class_id
         WHERE " . implode(' AND ', $where) . "
         ORDER BY v.is_active DESC, v.created_at DESC",
        $params
    ) ?: [];
} catch (Throwable $e) {
    error_log('rides-fleet load: ' . $e->getMessage());
    $errors[] = 'Could not load vehicles: ' . $e->getMessage();
}

$counts = [];
try {
    $rows = $db->fetchAll(
        "SELECT asset_type, COUNT(*) AS cnt 
         FROM ride_vehicles 
         WHERE provider_id = ? AND is_active = 1 
         GROUP BY asset_type",
        [(int)$provider['id']]
    ) ?: [];
    foreach ($rows as $r) {
        if (!empty($r['asset_type'])) $counts[$r['asset_type']] = (int)$r['cnt'];
    }
} catch (Throwable $e) {
    error_log('rides-fleet counts: ' . $e->getMessage());
}

$pageTitle = 'Fleet — ' . $provider['name'];
require_once __DIR__ . '/../../includes/header.php';
?>

<style>
.fm-page { background: #0f0c29; min-height: 100vh; padding: 100px 0 80px; color: white; }
.fm-page .container { max-width: 1400px; margin: 0 auto; padding: 0 20px; }
.fm-head { display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 16px; margin-bottom: 24px; }
.fm-head h1 { font-size: 28px; font-weight: 800; margin-bottom: 4px; }
.fm-head p { color: #a0aec0; font-size: 13px; }
.fm-nav { display: flex; gap: 6px; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 12px; padding: 4px; flex-wrap: wrap; }
.fm-nav a { padding: 8px 14px; border-radius: 8px; font-size: 12px; font-weight: 700; color: #a0aec0; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; }
.fm-nav a:hover { background: rgba(255,255,255,0.05); color: white; }
.fm-nav a.active { background: linear-gradient(135deg, #667eea, #764ba2); color: white; }
.fm-actions { display: flex; gap: 8px; margin-bottom: 20px; flex-wrap: wrap; align-items: center; }
.fm-btn { padding: 10px 18px; border-radius: 10px; font-size: 12px; font-weight: 700; cursor: pointer; border: none; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; }
.fm-btn-primary { background: linear-gradient(135deg, #667eea, #764ba2); color: white; }
.fm-btn-primary:hover { color: white; transform: translateY(-1px); box-shadow: 0 8px 20px rgba(102,126,234,0.4); }
.fm-btn-outline { background: rgba(255,255,255,0.05); color: #cbd5e0; border: 1px solid rgba(255,255,255,0.08); }
.fm-btn-outline:hover { background: rgba(255,255,255,0.1); color: white; }
.fm-flash { background: rgba(0,184,148,0.12); border: 1px solid rgba(0,184,148,0.3); color: #00b894; border-radius: 12px; padding: 14px 18px; margin-bottom: 20px; font-size: 13px; }
.fm-error { background: rgba(245,87,108,0.12); border: 1px solid rgba(245,87,108,0.3); color: #f5576c; border-radius: 12px; padding: 14px 18px; margin-bottom: 20px; font-size: 13px; }
.fm-tabs { display: flex; gap: 4px; margin-bottom: 20px; flex-wrap: wrap; }
.fm-tab { padding: 8px 16px; border-radius: 50px; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); color: #a0aec0; text-decoration: none; font-size: 12px; font-weight: 700; }
.fm-tab.active { background: linear-gradient(135deg, #667eea, #764ba2); color: white; border-color: transparent; }
.fm-tab .badge { margin-left: 6px; padding: 1px 8px; border-radius: 20px; background: rgba(0,0,0,0.3); font-size: 10px; }
.fm-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 16px; }
.fm-card { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 16px; overflow: hidden; display: flex; flex-direction: column; }
.fm-card.inactive { opacity: 0.6; }
.fm-card-hero { height: 160px; background: linear-gradient(135deg, rgba(102,126,234,0.2), rgba(118,75,162,0.2)); display: flex; align-items: center; justify-content: center; font-size: 56px; color: #a3bffa; position: relative; overflow: hidden; }
.fm-card-hero img { width: 100%; height: 100%; object-fit: cover; }
.fm-card-hero .type-badge { position: absolute; top: 10px; left: 10px; padding: 4px 10px; border-radius: 50px; background: rgba(0,0,0,0.6); font-size: 9px; font-weight: 800; text-transform: uppercase; color: white; }
.fm-card-hero .status-badge { position: absolute; top: 10px; right: 10px; padding: 4px 10px; border-radius: 50px; font-size: 9px; font-weight: 800; text-transform: uppercase; }
.fm-card-hero .status-badge.active { background: rgba(0,184,148,0.9); color: white; }
.fm-card-hero .status-badge.inactive { background: rgba(245,87,108,0.9); color: white; }
.fm-card-hero .status-badge.available { background: rgba(0,212,255,0.9); color: #0f0c29; }
.fm-card-body { padding: 16px; flex: 1; display: flex; flex-direction: column; }
.fm-card-title { font-size: 16px; font-weight: 800; margin-bottom: 4px; }
.fm-card-sub { font-size: 11px; color: #a0aec0; font-family: monospace; margin-bottom: 10px; }
.fm-card-meta { display: flex; gap: 12px; flex-wrap: wrap; font-size: 11px; color: #a0aec0; margin-bottom: 12px; }
.fm-card-meta span { display: inline-flex; align-items: center; gap: 4px; }
.fm-card-actions { display: flex; gap: 6px; padding-top: 12px; border-top: 1px solid rgba(255,255,255,0.06); margin-top: auto; }
.fm-card-actions a, .fm-card-actions button { flex: 1; padding: 8px; border-radius: 8px; font-size: 11px; font-weight: 700; text-decoration: none; text-align: center; cursor: pointer; border: none; display: inline-flex; align-items: center; justify-content: center; gap: 4px; }
.fm-card-actions .edit { background: rgba(102,126,234,0.15); color: #a3bffa; }
.fm-card-actions .toggle { background: rgba(0,184,148,0.15); color: #00b894; }
.fm-card-actions .delete { background: rgba(245,87,108,0.15); color: #f5576c; }
.fm-card-actions .reactivate { background: rgba(0,184,148,0.15); color: #00b894; }
.fm-empty { text-align: center; padding: 80px 20px; color: #a0aec0; }
.fm-empty i { font-size: 64px; opacity: 0.3; display: block; margin-bottom: 20px; color: #a3bffa; }
.fm-empty h3 { font-size: 20px; font-weight: 800; color: white; margin-bottom: 8px; }
.fm-debug { background: rgba(246,173,85,0.08); border: 1px solid rgba(246,173,85,0.3); border-radius: 10px; padding: 12px 16px; margin-bottom: 20px; font-size: 11px; color: #f6ad55; font-family: monospace; }
</style>

<div class="fm-page">
    <div class="container">

        <div class="fm-head">
            <div>
                <h1>🚗 Fleet Management</h1>
                <p><?= htmlspecialchars($provider['name']) ?> · <?= count($vehicles) ?> asset<?= count($vehicles) === 1 ? '' : 's' ?></p>
            </div>
            <div class="fm-nav">
                <a href="/?page=vendor-rides"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
                <a href="/?page=vendor-rides-bookings"><i class="fas fa-calendar-check"></i> Bookings</a>
                <a href="/?page=vendor-rides-fleet" class="active"><i class="fas fa-car"></i> Fleet</a>
                <a href="/?page=vendor-rides-drivers"><i class="fas fa-user-tie"></i> Drivers</a>
                <a href="/?page=vendor-rides-reports"><i class="fas fa-chart-line"></i> Reports</a>
                <a href="/?page=vendor-rides-settings"><i class="fas fa-cog"></i> Settings</a>
            </div>
        </div>

        <?php if ($flash): ?><div class="fm-flash"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($flash) ?></div><?php endif; ?>
        <?php foreach ($errors as $err): ?><div class="fm-error"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($err) ?></div><?php endforeach; ?>

        <div class="fm-actions">
            <a href="/?page=vendor-rides-fleet-edit" class="fm-btn fm-btn-primary">
                <i class="fas fa-plus"></i> Add new asset
            </a>
            <a href="/?page=vendor-rides-drivers" class="fm-btn fm-btn-outline">
                <i class="fas fa-user-tie"></i> Assign drivers
            </a>
        </div>

        <div class="fm-tabs">
            <a href="/?page=vendor-rides-fleet" class="fm-tab <?= $filterType === '' ? 'active' : '' ?>">All <span class="badge"><?= count($vehicles) ?></span></a>
            <a href="/?page=vendor-rides-fleet&type=car" class="fm-tab <?= $filterType === 'car' ? 'active' : '' ?>">🚗 Cars <span class="badge"><?= $counts['car'] ?? 0 ?></span></a>
            <a href="/?page=vendor-rides-fleet&type=suv" class="fm-tab <?= $filterType === 'suv' ? 'active' : '' ?>">🚙 SUVs <span class="badge"><?= $counts['suv'] ?? 0 ?></span></a>
            <a href="/?page=vendor-rides-fleet&type=van" class="fm-tab <?= $filterType === 'van' ? 'active' : '' ?>">🚐 Vans <span class="badge"><?= $counts['van'] ?? 0 ?></span></a>
            <a href="/?page=vendor-rides-fleet&type=boat" class="fm-tab <?= $filterType === 'boat' ? 'active' : '' ?>">🚤 Boats <span class="badge"><?= $counts['boat'] ?? 0 ?></span></a>
            <a href="/?page=vendor-rides-fleet&type=yacht" class="fm-tab <?= $filterType === 'yacht' ? 'active' : '' ?>">⛵ Yachts <span class="badge"><?= $counts['yacht'] ?? 0 ?></span></a>
            <a href="/?page=vendor-rides-fleet&type=helicopter" class="fm-tab <?= $filterType === 'helicopter' ? 'active' : '' ?>">🚁 Helicopters <span class="badge"><?= $counts['helicopter'] ?? 0 ?></span></a>
        </div>

        <?php if (empty($vehicles)): ?>
            <div class="fm-empty">
                <i class="fas fa-car"></i>
                <h3>No assets yet</h3>
                <p style="margin-bottom: 24px;">Add your first vehicle, boat, or aircraft to start accepting bookings.</p>
                <a href="/?page=vendor-rides-fleet-edit" class="fm-btn fm-btn-primary">
                    <i class="fas fa-plus"></i> Add your first asset
                </a>
            </div>
        <?php else: ?>
            <div class="fm-grid">
                <?php foreach ($vehicles as $v):
                    $icon = [
                        'car' => 'car', 'suv' => 'truck-pickup', 'van' => 'van-shuttle', 'bus' => 'bus',
                        'truck' => 'truck', 'motorcycle' => 'motorcycle', 'bicycle' => 'bicycle',
                        'boat' => 'ship', 'yacht' => 'sailboat', 'ferry' => 'ferry',
                        'helicopter' => 'helicopter', 'aircraft' => 'plane', 'other' => 'question',
                    ][$v['asset_type'] ?? 'car'] ?? 'car';
                    $photo = $v['photo'] ?? '';
                ?>
                    <div class="fm-card <?= empty($v['is_active']) ? 'inactive' : '' ?>">
                        <div class="fm-card-hero">
                            <?php if ($photo): ?>
                                <img src="<?= htmlspecialchars($photo) ?>" alt="">
                            <?php else: ?>
                                <i class="fas fa-<?= $icon ?>"></i>
                            <?php endif; ?>
                            <span class="type-badge"><?= strtoupper($v['asset_type'] ?? 'car') ?></span>
                            <?php if (empty($v['is_active'])): ?>
                                <span class="status-badge inactive">Inactive</span>
                            <?php elseif (!empty($v['is_available'])): ?>
                                <span class="status-badge available">Available</span>
                            <?php else: ?>
                                <span class="status-badge active">Active</span>
                            <?php endif; ?>
                        </div>
                        <div class="fm-card-body">
                            <div class="fm-card-title"><?= htmlspecialchars(trim(($v['make'] ?? '') . ' ' . ($v['model'] ?? ''))) ?: 'Unnamed asset' ?></div>
                            <div class="fm-card-sub"><?= htmlspecialchars($v['license_plate'] ?? $v['registration_number'] ?? '—') ?></div>
                            <div class="fm-card-meta">
                                <span><i class="fas fa-users"></i> <?= (int)($v['capacity'] ?? 0) ?></span>
                                <span><i class="fas fa-suitcase"></i> <?= (int)($v['luggage_capacity'] ?? 0) ?></span>
                                <?php if (!empty($v['class_label'])): ?><span><i class="fas fa-tag"></i> <?= htmlspecialchars($v['class_label']) ?></span><?php endif; ?>
                                <span><i class="fas fa-route"></i> <?= (int)($v['total_rides'] ?? 0) ?> rides</span>
                            </div>
                            <?php if (!empty($v['current_driver'])): ?>
                                <div style="font-size: 11px; color: #00d4ff; margin-bottom: 12px;"><i class="fas fa-user-check"></i> Assigned: <?= htmlspecialchars($v['current_driver']) ?></div>
                            <?php endif; ?>
                            <div class="fm-card-actions">
                                <?php if (!empty($v['is_active'])): ?>
                                    <a href="/?page=vendor-rides-fleet-edit&id=<?= (int)$v['id'] ?>" class="edit">
                                        <i class="fas fa-pen"></i> Edit
                                    </a>
                                    <form method="POST" style="flex: 1; display: flex;">
                                        <input type="hidden" name="action" value="toggle_available">
                                        <input type="hidden" name="vehicle_id" value="<?= (int)$v['id'] ?>">
                                        <button type="submit" class="toggle" style="width: 100%;">
                                            <i class="fas fa-<?= !empty($v['is_available']) ? 'toggle-on' : 'toggle-off' ?>"></i> <?= !empty($v['is_available']) ? 'Avail' : 'Off' ?>
                                        </button>
                                    </form>
                                    <form method="POST" style="flex: 1; display: flex;">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="vehicle_id" value="<?= (int)$v['id'] ?>">
                                        <button type="submit" class="delete" style="width: 100%;" onclick="return confirm('Deactivate this asset?')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                <?php else: ?>
                                    <form method="POST" style="flex: 1; display: flex;">
                                        <input type="hidden" name="action" value="reactivate">
                                        <input type="hidden" name="vehicle_id" value="<?= (int)$v['id'] ?>">
                                        <button type="submit" class="reactivate" style="width: 100%;">
                                            <i class="fas fa-redo"></i> Reactivate
                                        </button>
                                    </form>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

    </div>
</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>