<?php
// /htdocs/pages/driver-register.php — JOIN A PROVIDER AS A DRIVER
if (!defined('APP_START')) { define('APP_START', 1); }

$db = db();
if (!isLoggedIn()) {
    header('Location: /?page=login&redirect=' . urlencode('/?page=driver-register'));
    exit;
}
$userId = (int)($_SESSION['user_id'] ?? 0);

$flash = null;
$errors = [];
$selectedProviderId = (int)($_GET['provider_id'] ?? 0);

// Existing application check
$existingApplication = $db->fetchOne(
    "SELECT * FROM ride_driver_applications WHERE applicant_user_id = ? ORDER BY id DESC LIMIT 1",
    [$userId]
);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $providerId = (int)($_POST['provider_id'] ?? 0);
        $fullName = trim($_POST['full_name'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $licenseNumber = trim($_POST['license_number'] ?? '');
        $licenseExpiry = $_POST['license_expiry'] ?? null;
        $idNumber = trim($_POST['id_number'] ?? '');
        $dob = $_POST['date_of_birth'] ?? null;
        $languagesRaw = trim($_POST['languages'] ?? '');
        $hasOwnVehicle = !empty($_POST['has_own_vehicle']) ? 1 : 0;
        $vehicleMake = trim($_POST['vehicle_make'] ?? '');
        $vehicleModel = trim($_POST['vehicle_model'] ?? '');
        $vehicleYear = (int)($_POST['vehicle_year'] ?? 0) ?: null;
        $vehiclePlate = trim($_POST['vehicle_license_plate'] ?? '');
        $vehicleClassId = (int)($_POST['vehicle_class_id'] ?? 0) ?: null;

        if ($providerId <= 0) $errors[] = 'Select a provider';
        if ($fullName === '') $errors[] = 'Full name required';
        if ($phone === '') $errors[] = 'Phone required';
        if ($licenseNumber === '') $errors[] = 'Driver license number required';
        if ($licenseExpiry === null || $licenseExpiry === '') $errors[] = 'License expiry date required';
        if ($idNumber === '') $errors[] = 'ID number required';

        // Validate provider exists and is verified
        if (empty($errors)) {
            $prov = $db->fetchOne("SELECT id, name FROM ride_providers WHERE id = ? AND is_active = 1 AND is_verified = 1", [$providerId]);
            if (!$prov) $errors[] = 'Selected provider not available';
        }

        if ($existingApplication && in_array($existingApplication['status'], ['pending', 'needs_info'])) {
            $errors[] = 'You already have a pending driver application';
        }

        if (empty($errors)) {
            $languages = $languagesRaw !== '' ? array_map('trim', explode(',', $languagesRaw)) : [];

            $db->query(
                "INSERT INTO ride_driver_applications
                    (applicant_user_id, provider_id, full_name, phone, email,
                     license_number, license_expiry, id_number, date_of_birth, languages,
                     has_own_vehicle, vehicle_make, vehicle_model, vehicle_year,
                     vehicle_license_plate, vehicle_class_id)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                [
                    $userId, $providerId, $fullName, $phone, $email,
                    $licenseNumber, $licenseExpiry, $idNumber, $dob, json_encode($languages),
                    $hasOwnVehicle, $vehicleMake ?: null, $vehicleModel ?: null, $vehicleYear,
                    $vehiclePlate ?: null, $vehicleClassId,
                ]
            );
            $appId = (int)$db->lastInsertId();

            // Notify provider owner
            try {
                $owner = $db->fetchOne(
                    "SELECT u.id FROM users u
                     INNER JOIN vendors v ON v.user_id = u.id
                     INNER JOIN ride_providers rp ON rp.vendor_id = v.id
                     WHERE rp.id = ? LIMIT 1",
                    [$providerId]
                );
                if ($owner) {
                    $db->query(
                        "INSERT INTO notifications (user_id, vendor_id, type, title, message, link, icon, priority)
                         VALUES (?, ?, 'ride_driver_application', 'New driver application', ?, ?, 'id-card', 'high')",
                        [
                            (int)$owner['id'],
                            null,
                            $fullName . ' · ' . $phone,
                            '/?page=vendor-rides-drivers&application=' . $appId,
                        ]
                    );
                }
            } catch (Throwable $e) {
                error_log('Driver app notif failed: ' . $e->getMessage());
            }

            $flash = 'success';
            $existingApplication = $db->fetchOne("SELECT * FROM ride_driver_applications WHERE id = ?", [$appId]);
        }
    } catch (Throwable $e) {
        $errors[] = 'Error: ' . $e->getMessage();
    }
}

// Provider list
$providers = $db->fetchAll(
    "SELECT id, name, provider_type FROM ride_providers WHERE is_active = 1 AND is_verified = 1 ORDER BY name"
) ?: [];

// Vehicle classes
$classes = $db->fetchAll("SELECT id, label FROM ride_classes WHERE is_active = 1 ORDER BY display_order") ?: [];

$pageTitle = 'Drive with Revenda';
require_once __DIR__ . '/../includes/header.php';
?>

<style>
.dr-page { background: #0f0c29; min-height: 100vh; padding: 100px 0 80px; color: white; }
.dr-page .container { max-width: 800px; margin: 0 auto; padding: 0 20px; }
.dr-head { text-align: center; margin-bottom: 40px; }
.dr-head h1 { font-size: 36px; font-weight: 800; margin-bottom: 12px; }
.dr-head p { color: #a0aec0; font-size: 15px; max-width: 540px; margin: 0 auto; }
.dr-card {
    background: rgba(255,255,255,0.03);
    border: 1px solid rgba(255,255,255,0.08);
    border-radius: 20px;
    padding: 32px;
}
.dr-section-title {
    font-size: 13px;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    color: #a3bffa;
    margin: 24px 0 16px;
    padding-bottom: 10px;
    border-bottom: 1px solid rgba(255,255,255,0.08);
}
.dr-section-title:first-child { margin-top: 0; }
.dr-field { margin-bottom: 18px; }
.dr-field label {
    display: block;
    font-size: 12px;
    font-weight: 700;
    color: #a3bffa;
    margin-bottom: 8px;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}
.dr-field input, .dr-field select, .dr-field textarea {
    width: 100%;
    padding: 12px 16px;
    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;
}
.dr-field select option { background: #1a1a2e; }
.dr-row { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }
@media (max-width: 640px) { .dr-row { grid-template-columns: 1fr; } }
.dr-check {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 14px;
    background: rgba(102,126,234,0.08);
    border: 1px solid rgba(102,126,234,0.25);
    border-radius: 10px;
    margin-bottom: 18px;
}
.dr-check input { width: auto; transform: scale(1.3); }
.dr-check label { margin: 0; text-transform: none; color: white; font-size: 13px; font-weight: 600; letter-spacing: 0; }
.dr-submit {
    width: 100%;
    padding: 16px;
    background: linear-gradient(135deg, #667eea, #764ba2);
    border: none;
    border-radius: 12px;
    color: white;
    font-size: 14px;
    font-weight: 700;
    cursor: pointer;
    transition: all 0.2s;
    margin-top: 8px;
}
.dr-submit:hover { transform: translateY(-1px); box-shadow: 0 8px 24px rgba(102,126,234,0.4); }
.dr-alert-error {
    padding: 16px 20px;
    border-radius: 12px;
    margin-bottom: 24px;
    font-size: 14px;
    background: rgba(245,87,108,0.12);
    border: 1px solid rgba(245,87,108,0.3);
    color: #f5576c;
}
.dr-status {
    text-align: center;
    padding: 40px 20px;
}
.dr-status .icon {
    width: 80px; height: 80px;
    border-radius: 50%;
    margin: 0 auto 20px;
    display: flex; align-items: center; justify-content: center;
    font-size: 36px;
}
</style>

<div class="dr-page">
    <div class="container">

        <?php if ($flash === 'success' || ($existingApplication && in_array($existingApplication['status'], ['pending', 'needs_info', 'approved', 'rejected']))):
            $app = $existingApplication;
            $colors = ['pending' => '#f6ad55', 'needs_info' => '#f6ad55', 'approved' => '#00b894', 'rejected' => '#f5576c'];
            $icons = ['pending' => 'clock', 'needs_info' => 'info-circle', 'approved' => 'check-circle', 'rejected' => 'times-circle'];
            $labels = ['pending' => 'Under review', 'needs_info' => 'Action needed', 'approved' => 'Approved', 'rejected' => 'Rejected'];
            $color = $colors[$app['status']]; $icon = $icons[$app['status']]; $label = $labels[$app['status']];
        ?>
            <div class="dr-card">
                <div class="dr-status">
                    <div class="icon" style="background: <?= $color ?>22; color: <?= $color ?>; border: 2px solid <?= $color ?>55;">
                        <i class="fas fa-<?= $icon ?>"></i>
                    </div>
                    <h2 style="font-size: 24px; font-weight: 800; margin-bottom: 12px;"><?= $label ?></h2>
                    <?php if ($app['status'] === 'pending'): ?>
                        <p style="color: #a0aec0; max-width: 480px; margin: 0 auto;">Your driver application to <?= htmlspecialchars($app['full_name']) ?>'s provider is under review. You'll receive a notification once approved.</p>
                    <?php elseif ($app['status'] === 'approved'): ?>
                        <p style="color: #a0aec0; max-width: 480px; margin: 0 auto 24px;">Welcome aboard! You can now start your driver dashboard.</p>
                        <a href="/?page=driver-dashboard" style="display: inline-block; padding: 12px 24px; background: linear-gradient(135deg, #667eea, #764ba2); color: white; text-decoration: none; border-radius: 10px; font-weight: 700;">
                            <i class="fas fa-tachometer-alt"></i> Open driver dashboard
                        </a>
                    <?php elseif ($app['status'] === 'rejected'): ?>
                        <p style="color: #a0aec0; max-width: 480px; margin: 0 auto 16px;">Your application was not approved.</p>
                        <?php if (!empty($app['admin_notes'])): ?>
                            <div style="background: rgba(245,87,108,0.08); border: 1px solid rgba(245,87,108,0.3); border-radius: 10px; padding: 14px; margin: 20px auto; max-width: 480px; text-align: left; color: #f5576c; font-size: 13px;">
                                <?= nl2br(htmlspecialchars($app['admin_notes'])) ?>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>

        <?php else: ?>

            <div class="dr-head">
                <h1>Drive with Revenda</h1>
                <p>Join a fleet and start earning. Independent drivers and existing provider staff welcome.</p>
            </div>

            <?php if (!empty($errors)): ?>
                <div class="dr-alert-error">
                    <i class="fas fa-exclamation-circle"></i>
                    <?php foreach ($errors as $e): ?><div><?= htmlspecialchars($e) ?></div><?php endforeach; ?>
                </div>
            <?php endif; ?>

            <?php if (empty($providers)): ?>
                <div class="dr-card" style="text-align: center; padding: 60px 20px;">
                    <i class="fas fa-car" style="font-size: 48px; color: #a3bffa; opacity: 0.4; margin-bottom: 16px; display: block;"></i>
                    <h2 style="font-size: 20px; font-weight: 800; margin-bottom: 10px;">No providers yet</h2>
                    <p style="color: #a0aec0; margin-bottom: 20px;">There are no verified ride providers on the platform yet. Be the first!</p>
                    <a href="/?page=ride-register" style="display: inline-block; padding: 12px 24px; background: linear-gradient(135deg, #667eea, #764ba2); color: white; text-decoration: none; border-radius: 10px; font-weight: 700;">
                        Register your own fleet
                    </a>
                </div>
            <?php else: ?>

            <form method="POST" class="dr-card">
                <div class="dr-section-title">1 · Choose your fleet</div>
                <div class="dr-field">
                    <label>Provider *</label>
                    <select name="provider_id" required>
                        <option value="">— Select provider —</option>
                        <?php foreach ($providers as $p): ?>
                            <option value="<?= (int)$p['id'] ?>" <?= $selectedProviderId === (int)$p['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($p['name']) ?> · <?= ucfirst($p['provider_type']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="dr-section-title">2 · Your details</div>
                <div class="dr-row">
                                        <div class="dr-field">
                        <label>Full name *</label>
                        <input type="text" name="full_name" required value="<?= htmlspecialchars($_POST['full_name'] ?? ($_SESSION['first_name'] ?? '') . ' ' . ($_SESSION['last_name'] ?? '')) ?>">
                    </div>
                    <div class="dr-field">
                        <label>Phone *</label>
                        <input type="tel" name="phone" required placeholder="+255..." value="<?= htmlspecialchars($_POST['phone'] ?? '') ?>">
                    </div>
                </div>

                <div class="dr-field">
                    <label>Email</label>
                    <input type="email" name="email" value="<?= htmlspecialchars($_POST['email'] ?? ($_SESSION['email'] ?? '')) ?>">
                </div>

                <div class="dr-row">
                    <div class="dr-field">
                        <label>Date of birth</label>
                        <input type="date" name="date_of_birth" value="<?= htmlspecialchars($_POST['date_of_birth'] ?? '') ?>">
                    </div>
                    <div class="dr-field">
                        <label>Languages (comma-separated)</label>
                        <input type="text" name="languages" placeholder="English, Swahili" value="<?= htmlspecialchars($_POST['languages'] ?? '') ?>">
                    </div>
                </div>

                <div class="dr-section-title">3 · License & ID</div>
                <div class="dr-row">
                    <div class="dr-field">
                        <label>Driver license number *</label>
                        <input type="text" name="license_number" required value="<?= htmlspecialchars($_POST['license_number'] ?? '') ?>">
                    </div>
                    <div class="dr-field">
                        <label>License expiry *</label>
                        <input type="date" name="license_expiry" required value="<?= htmlspecialchars($_POST['license_expiry'] ?? '') ?>">
                    </div>
                </div>

                <div class="dr-field">
                    <label>National ID number *</label>
                    <input type="text" name="id_number" required value="<?= htmlspecialchars($_POST['id_number'] ?? '') ?>">
                </div>

                <div class="dr-section-title">4 · Do you have your own vehicle?</div>
                <div class="dr-check">
                    <input type="checkbox" name="has_own_vehicle" id="ownVehicleToggle" value="1" <?= !empty($_POST['has_own_vehicle']) ? 'checked' : '' ?>>
                    <label for="ownVehicleToggle">Yes — I'll use my own vehicle on this fleet</label>
                </div>

                <div id="vehicleFields" style="<?= !empty($_POST['has_own_vehicle']) ? '' : 'display:none;' ?>">
                    <div class="dr-row">
                        <div class="dr-field">
                            <label>Make</label>
                            <input type="text" name="vehicle_make" placeholder="Toyota" value="<?= htmlspecialchars($_POST['vehicle_make'] ?? '') ?>">
                        </div>
                        <div class="dr-field">
                            <label>Model</label>
                            <input type="text" name="vehicle_model" placeholder="Land Cruiser" value="<?= htmlspecialchars($_POST['vehicle_model'] ?? '') ?>">
                        </div>
                    </div>
                    <div class="dr-row">
                        <div class="dr-field">
                            <label>Year</label>
                            <input type="number" name="vehicle_year" min="1980" max="<?= date('Y') + 1 ?>" value="<?= htmlspecialchars($_POST['vehicle_year'] ?? '') ?>">
                        </div>
                        <div class="dr-field">
                            <label>License plate</label>
                            <input type="text" name="vehicle_license_plate" placeholder="ABC 123" value="<?= htmlspecialchars($_POST['vehicle_license_plate'] ?? '') ?>">
                        </div>
                    </div>
                    <div class="dr-field">
                        <label>Vehicle class</label>
                        <select name="vehicle_class_id">
                            <option value="">— Select class —</option>
                            <?php foreach ($classes as $c): ?>
                                <option value="<?= (int)$c['id'] ?>" <?= (($_POST['vehicle_class_id'] ?? '') == $c['id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($c['label']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <button type="submit" class="dr-submit">
                    <i class="fas fa-paper-plane"></i> Submit application
                </button>

                <p style="text-align: center; font-size: 12px; color: #718096; margin-top: 16px;">
                    Applications reviewed by the provider within 24 hours.
                </p>
            </form>

            <script>
            document.getElementById('ownVehicleToggle')?.addEventListener('change', function() {
                document.getElementById('vehicleFields').style.display = this.checked ? '' : 'none';
            });
            </script>

            <?php endif; ?>

        <?php endif; ?>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>