<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once __DIR__ . '/includes/settings_helpers.php';

session_start();
if (empty($_SESSION['authenticated'])) {
    header("Location: signin.php");
    exit();
}
require_once __DIR__ . '/db.php';

function employee_overview_has_organization_id(mysqli $conn): bool
{
    static $hasColumn = null;
    if ($hasColumn !== null) {
        return $hasColumn;
    }

    $result = $conn->query("SHOW COLUMNS FROM employees LIKE 'organization_id'");
    $hasColumn = (bool) ($result && $result->num_rows > 0);
    return $hasColumn;
}

function pick_field($row, $candidates) {
    foreach ($candidates as $field) {
        if (array_key_exists($field, $row) && $row[$field] !== null && $row[$field] !== '') {
            return $row[$field];
        }
    }
    return null;
}
function build_full_name($row) {
    $full = pick_field($row, ['full_name']);
    if ($full) {
        return $full;
    }
    $first = pick_field($row, ['first_name', 'firstname']);
    $middle = pick_field($row, ['middle_name', 'middlename']);
    $last = pick_field($row, ['last_name', 'lastname']);
    $parts = array_filter([$first, $middle, $last]);
    return $parts ? implode(' ', $parts) : 'Employee';
}
function build_emp_code($row) {
    return pick_field($row, ['employee_code', 'employee_id', 'emp_code']);
}
function is_profile_incomplete($row) {
    $required = [
        build_full_name($row),
        build_emp_code($row),
        pick_field($row, ['work_email', 'email']),
        pick_field($row, ['department']),
        pick_field($row, ['designation']),
        pick_field($row, ['work_location']),
        pick_field($row, ['date_of_joining', 'join_date'])
    ];
    foreach ($required as $value) {
        if ($value === null || $value === '') {
            return true;
        }
    }
    return false;
}

function ensure_employee_vehicle_table(mysqli $conn): void
{
    $conn->query(
        "CREATE TABLE IF NOT EXISTS employee_vehicle_details (
            id INT AUTO_INCREMENT PRIMARY KEY,
            employee_id INT NOT NULL,
            org_id VARCHAR(50) NOT NULL,
            owner_of_car VARCHAR(50) NOT NULL DEFAULT 'employer_owned',
            maintenance_cost_met_by VARCHAR(50) NOT NULL DEFAULT 'employer',
            cubic_capacity VARCHAR(50) NOT NULL DEFAULT 'upto_1600cc',
            driver_provided_by_company VARCHAR(10) NOT NULL DEFAULT 'no',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY uniq_employee_vehicle (employee_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"
    );
}

function pick_employee_vehicle(mysqli $conn, int $employeeId): array
{
    $defaults = [
        'owner_of_car' => 'employer_owned',
        'maintenance_cost_met_by' => 'employer',
        'cubic_capacity' => 'upto_1600cc',
        'driver_provided_by_company' => 'no',
    ];

    $stmt = $conn->prepare("SELECT * FROM employee_vehicle_details WHERE employee_id = ? LIMIT 1");
    if (!$stmt) {
        return $defaults;
    }
    $stmt->bind_param('i', $employeeId);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    return $row ? array_merge($defaults, $row) : $defaults;
}

$empId = isset($_GET['emp_id']) ? (int)$_GET['emp_id'] : 0;
$tab = $_GET['tab'] ?? 'overview';
$validTabs = ['overview', 'related'];
if (!in_array($tab, $validTabs, true)) {
    $tab = 'overview';
}
$employee = null;
$orgId = (int) ($_SESSION['org_id'] ?? 0);
settings_ensure_employee_organization_column($conn, $orgId);
if ($empId > 0) {
    $sql = employee_overview_has_organization_id($conn)
        ? "SELECT * FROM employees WHERE id = ? AND organization_id = ? AND COALESCE(is_deleted, 0) = 0"
        : "SELECT * FROM employees WHERE id = ? AND COALESCE(is_deleted, 0) = 0";
    $stmt = $conn->prepare($sql);
    if ($stmt) {
        if (employee_overview_has_organization_id($conn)) {
            $stmt->bind_param('ii', $empId, $orgId);
        } else {
            $stmt->bind_param('i', $empId);
        }
        $stmt->execute();
        $employee = $stmt->get_result()->fetch_assoc();
        $stmt->close();
    }
}
if (!$employee) {
    header("Location: employees.php?step=list");
    exit();
}

$showVehicleModal = isset($_GET['show_vehicle_details']) && $_GET['show_vehicle_details'] === 'true';
ensure_employee_vehicle_table($conn);

$orgName = $_SESSION['org_name'] ?? 'demo';
$bodyClasses = 'dash-page';
$empName = build_full_name($employee);
$empCode = build_emp_code($employee);
$isIncomplete = is_profile_incomplete($employee);
$isDirector = !empty(pick_field($employee, ['director', 'is_director', 'director_level', 'substantial_interest', 'is_director_person']));
$portalEnabled = !empty(pick_field($employee, ['portal_access', 'portal_enabled', 'employee_portal_access']));
$vehicleDetails = pick_employee_vehicle($conn, $empId);
$pageTitle = ($empName ?: 'Employee Overview') . ' | ' . $orgName;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_employee'])) {
    $deletedBy = trim((string) ($_SESSION['username'] ?? $_SESSION['user'] ?? 'system'));
    $deleteReason = 'Deleted from employee overview';
    $sql = employee_overview_has_organization_id($conn)
        ? "UPDATE employees
           SET is_deleted = 1,
               deleted_at = NOW(),
               deleted_by = ?,
               delete_reason = ?,
               status = 'inactive'
           WHERE id = ? AND organization_id = ? AND COALESCE(is_deleted, 0) = 0"
        : "UPDATE employees
           SET is_deleted = 1,
               deleted_at = NOW(),
               deleted_by = ?,
               delete_reason = ?,
               status = 'inactive'
           WHERE id = ? AND COALESCE(is_deleted, 0) = 0";
    $stmt = $conn->prepare($sql);

    if ($stmt) {
        if (employee_overview_has_organization_id($conn)) {
            $stmt->bind_param('ssii', $deletedBy, $deleteReason, $empId, $orgId);
        } else {
            $stmt->bind_param('ssi', $deletedBy, $deleteReason, $empId);
        }
        $stmt->execute();
        $deletedRows = $stmt->affected_rows;
        $stmt->close();

        if ($deletedRows > 0) {
            $_SESSION['flash_ok'] = 'Employee deleted successfully.';
        } else {
            $_SESSION['flash_err'] = 'Employee was already deleted or could not be found.';
        }
    } else {
        $_SESSION['flash_err'] = 'Unable to delete employee right now.';
    }

    header('Location: employees.php?step=list');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['vehicle_submit'])) {
    $ownerOfCar = trim((string) ($_POST['owner_of_car'] ?? 'employer_owned'));
    $maintenanceCostMetBy = trim((string) ($_POST['maintenance_cost_met_by'] ?? 'employer'));
    $cubicCapacity = trim((string) ($_POST['cubic_capacity'] ?? 'upto_1600cc'));
    $driverProvided = trim((string) ($_POST['driver_provided_by_company'] ?? 'no'));

    $allowedOwner = ['employer_owned', 'employee_owned'];
    $allowedMaintenance = ['employer', 'employee'];
    $allowedCapacity = ['upto_1600cc', 'greater_than_1600cc'];
    $allowedYesNo = ['yes', 'no'];

    if (!in_array($ownerOfCar, $allowedOwner, true)) {
        $ownerOfCar = 'employer_owned';
    }
    if (!in_array($maintenanceCostMetBy, $allowedMaintenance, true)) {
        $maintenanceCostMetBy = 'employer';
    }
    if (!in_array($cubicCapacity, $allowedCapacity, true)) {
        $cubicCapacity = 'upto_1600cc';
    }
    if (!in_array($driverProvided, $allowedYesNo, true)) {
        $driverProvided = 'no';
    }

    $stmt = $conn->prepare(
        "INSERT INTO employee_vehicle_details
            (employee_id, org_id, owner_of_car, maintenance_cost_met_by, cubic_capacity, driver_provided_by_company)
         VALUES (?, ?, ?, ?, ?, ?)
         ON DUPLICATE KEY UPDATE
            org_id = VALUES(org_id),
            owner_of_car = VALUES(owner_of_car),
            maintenance_cost_met_by = VALUES(maintenance_cost_met_by),
            cubic_capacity = VALUES(cubic_capacity),
            driver_provided_by_company = VALUES(driver_provided_by_company)"
    );
    if ($stmt) {
        $stmt->bind_param('isssss', $empId, $orgName, $ownerOfCar, $maintenanceCostMetBy, $cubicCapacity, $driverProvided);
        $stmt->execute();
        $stmt->close();
        $_SESSION['flash_ok'] = 'Vehicle details saved successfully.';
    } else {
        $_SESSION['flash_err'] = 'Unable to save vehicle details.';
    }

    header('Location: employee_overview.php?emp_id=' . urlencode((string) $empId) . '&tab=' . urlencode($tab) . '&show_vehicle_details=true');
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="<?php echo billing_escape(billing_base_href()); ?>">
    <title><?php echo htmlspecialchars($pageTitle); ?></title>
    <link rel="stylesheet" href="dashboard.css">
    <link rel="stylesheet" href="employees.css">
    <link rel="stylesheet" href="assets/font-inter.css">
    <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
    <style>
        .topbar-left{
            display:flex;
            flex-direction:column;
            gap:8px;
            min-width:0;
        }
        .topbar-context{
            display:flex;
            flex-direction:column;
            line-height:1.15;
            color:#334155;
            min-width:0;
        }
        .topbar-context__org{
            font-size:12px;
            color:#64748b;
            text-transform:uppercase;
            letter-spacing:.06em;
            font-weight:700;
        }
        .topbar-context__employee{
            font-size:18px;
            font-weight:800;
            color:#111827;
            white-space:nowrap;
            overflow:hidden;
            text-overflow:ellipsis;
        }
        .topbar-context__meta{
            font-size:12px;
            color:#64748b;
        }
        @media (max-width: 820px){
            .topbar-context__employee{
                font-size:16px;
                white-space:normal;
            }
        }
    </style>
</head>
<body class="<?php echo htmlspecialchars($bodyClasses); ?>">
<div class="dash-layout">
    <aside class="dash-sidebar">
        <div class="sidebar-brand">
            <img src="images/zoho-payroll-logo.svg" class="logo" alt="Zoho Payroll">
        </div>
        <div class="sidebar-scroll">
            <div class="sidebar-section">
                <div class="getting-started">
                    <div class="gs-top">
                        <i class="fa-solid fa-rocket-launch"></i>
                        <span>Getting Started</span>
                    </div>
                    <div class="progress-bar">
                        <div class="progress-fill"></div>
                    </div>
                </div>
            </div>
            <nav class="sidebar-nav">
                <a class="nav-item" href="dashboard.php"><i class="fa-solid fa-gauge-high"></i><span>Dashboard</span></a>
                <a class="nav-item active" href="employees.php"><i class="fa-solid fa-users"></i><span>Employees</span></a>
                <a class="nav-item" href="payruns.php"><i class="fa-solid fa-money-bill-wave"></i><span>Pay Runs</span></a>
                <div class="nav-group">
                    <button class="nav-item btn" type="button" data-nav-toggle><i class="fa-regular fa-square-check"></i><span>Approvals</span></button>
                    <div class="nav-sub">
                        <a class="nav-sub-item" href="reimbursements.php">Reimbursements</a>
                        <a class="nav-sub-item" href="proof_of_investments.php">Proof Of Investments</a>
                        <a class="nav-sub-item" href="salary_revision.php">Salary Revision</a>
                    </div>
                </div>
                <a class="nav-item" href="form16.php"><i class="fa-regular fa-file-lines"></i><span>Form 16</span></a>
                <a class="nav-item" href="loans.php"><i class="fa-solid fa-hand-holding-dollar"></i><span>Loans</span></a>
                <a class="nav-item" href="giving.php"><i class="fa-solid fa-gift"></i><span>Giving</span></a>
                <a class="nav-item" href="documents.php"><i class="fa-regular fa-folder-open"></i><span>Documents</span></a>
                <a class="nav-item" href="reports.php"><i class="fa-solid fa-chart-pie"></i><span>Reports</span></a>
                <a class="nav-item" href="settings.php"><i class="fa-solid fa-gear"></i><span>Settings</span></a>
            </nav>
        </div>
        <div class="sidebar-footer">
            <a class="support-link" href="#">Contact Support</a>
        </div>
        <div class="support-tile">
            <div class="support-title">Track TDS Liabilities and Generate Form 24Q</div>
            <a class="support-action" href="#">View Details</a>
        </div>
    </aside>

    <main class="dash-main">
        <header class="dash-topbar">
            <div class="topbar-left">
                <div class="search-box">
                    <i class="fa-solid fa-magnifying-glass search-icon"></i>
                    <input type="text" placeholder="Search in Employee">
                </div>
                <div class="topbar-context">
                    <span class="topbar-context__org"><?php echo htmlspecialchars($orgName); ?></span>
                    <span class="topbar-context__employee"><?php echo htmlspecialchars($empName ?: 'Employee Overview'); ?></span>
                    <?php if ($empCode): ?>
                        <span class="topbar-context__meta"><?php echo htmlspecialchars($empCode); ?></span>
                    <?php endif; ?>
                </div>
            </div>
            <div class="topbar-actions">
                <span class="trial">Your trial expires in 2 day(s). <a href="dashboard.php?modal=upgrade" class="upgrade-link">Upgrade</a></span>
                <a class="pill ghost org-toggle" href="dashboard.php?drawer=org"><span class="pill-label"><?php echo htmlspecialchars($orgName); ?></span><i class="fa-solid fa-angle-down"></i></a>
                <a class="top-icon icon-btn" href="#"><i class="fa-regular fa-bell"></i></a>
                <a class="top-icon top-link" href="settings.php"><i class="fa-solid fa-gear"></i></a>
                <a class="top-icon icon-btn"><i class="fa-solid fa-table-cells-large"></i></a>
                <span class="avatar"><?php echo strtoupper(substr($orgName, 0, 1)); ?></span>
            </div>
        </header>

        <section class="dash-content overview-page">
            <div class="emp-overview-head" id="employee-top">
                <div class="emp-overview-left">
                    <div class="emp-avatar"><?php echo strtoupper(substr($empName, 0, 1)); ?></div>
                    <div>
                        <div class="emp-overview-name"><?php echo htmlspecialchars($empCode ? ($empCode . ' - ' . $empName) : $empName); ?></div>
                        <div class="emp-overview-meta">
                            <?php if ($isDirector) { ?>
                                <span class="emp-badge emp-badge--soft">Director Level</span>
                            <?php } ?>
                            <span class="emp-badge emp-badge--green">Active</span>
                            <span class="emp-overview-meta__sub"><?php echo htmlspecialchars(pick_field($employee, ['designation']) ?? ''); ?></span>
                        </div>
                    </div>
                </div>
                <div class="emp-overview-actions">
                    <div class="overview-menu-wrap">
                        <button class="btn-icon" type="button" data-overview-menu-toggle aria-expanded="false" aria-haspopup="menu"><i class="fa-solid fa-ellipsis"></i></button>
                        <div class="overview-menu" id="overviewMenu" hidden>
                            <button type="button" class="overview-menu__primary" data-open-vehicle-modal>Add / Update Vehicle Details</button>
                            <a href="employees.php?step=basic&emp_id=<?php echo urlencode((string) $empId); ?>" class="overview-menu__item">Edit Employee</a>
                            <form method="POST" onsubmit="return confirm('Delete this employee from the Employees section?');">
                                <input type="hidden" name="delete_employee" value="1">
                                <button type="submit" class="overview-menu__item danger">Delete Employee</button>
                            </form>
                        </div>
                    </div>
                    <a class="btn-icon" href="employees.php?step=list"><i class="fa-solid fa-xmark"></i></a>
                </div>
            </div>

            <div class="overview-tabs">
                <a class="tab <?php echo $tab === 'overview' ? 'active' : ''; ?>" href="employee_overview.php?emp_id=<?php echo urlencode($empId); ?>&tab=overview">Overview</a>
                <a class="tab" href="employees.php?step=salary&emp_id=<?php echo urlencode($empId); ?>">Salary Details</a>
                <a class="tab <?php echo $tab === 'related' ? 'active' : ''; ?>" href="employee_overview.php?emp_id=<?php echo urlencode($empId); ?>&tab=related">Related Lists</a>
            </div>

            <?php if ($isIncomplete) { ?>
                <div class="overview-warn">
                    <i class="fa-solid fa-triangle-exclamation"></i>
                    This employee's profile is incomplete.
                    <a href="employees.php?step=basic&emp_id=<?php echo urlencode($empId); ?>">Complete now</a>
                </div>
            <?php } ?>

            <div class="overview-card overview-card--vehicle" id="vehicleCard" style="display:none;">
                <div class="overview-title">Vehicle Details</div>
                <div class="overview-grid">
                    <div><span>Owner of the Car</span><?php echo htmlspecialchars($vehicleDetails['owner_of_car'] === 'employee_owned' ? 'Employee-owned' : 'Employer-owned (or) Hired for Employee'); ?></div>
                    <div><span>Maintenance Cost Met By</span><?php echo htmlspecialchars($vehicleDetails['maintenance_cost_met_by'] === 'employee' ? 'Employee' : 'Employer'); ?></div>
                    <div><span>Cubic Capacity</span><?php echo htmlspecialchars($vehicleDetails['cubic_capacity'] === 'greater_than_1600cc' ? 'Greater than 1600CC' : 'Upto 1600CC'); ?></div>
                    <div><span>Driver Provided By Company</span><?php echo htmlspecialchars($vehicleDetails['driver_provided_by_company'] === 'yes' ? 'Yes' : 'No'); ?></div>
                </div>
            </div>

            <?php if ($tab === 'related') { ?>
                <div class="related-empty">
                    <div class="related-illus" aria-hidden="true">
                        <div class="illus-board">
                            <div class="illus-top"></div>
                            <div class="illus-lines">
                                <span></span>
                                <span></span>
                                <span></span>
                            </div>
                            <div class="illus-check"></div>
                        </div>
                        <div class="illus-person"></div>
                    </div>
                    <div class="related-text">You haven't created any related list yet.</div>
                </div>
            <?php } else { ?>
                <div class="overview-card">
                    <div class="overview-title">Basic Information</div>
                    <div class="overview-grid">
                        <div><span>Name</span><?php echo htmlspecialchars($empName); ?></div>
                        <div><span>Work Location</span><?php echo htmlspecialchars(pick_field($employee, ['work_location']) ?? '-'); ?></div>
                        <div><span>Email Address</span><?php echo htmlspecialchars(pick_field($employee, ['work_email', 'email']) ?? '-'); ?></div>
                        <div><span>Designation</span><?php echo htmlspecialchars(pick_field($employee, ['designation']) ?? '-'); ?></div>
                        <div><span>Mobile Number</span><?php echo htmlspecialchars(pick_field($employee, ['mobile_number', 'mobile_no', 'mobile']) ?? '-'); ?></div>
                        <div><span>Departments</span><?php echo htmlspecialchars(pick_field($employee, ['department']) ?? '-'); ?></div>
                        <div><span>Date of Joining</span><?php echo htmlspecialchars(pick_field($employee, ['date_of_joining', 'join_date']) ?? '-'); ?></div>
                        <div><span>Gender</span><?php echo htmlspecialchars(pick_field($employee, ['gender']) ?? '-'); ?></div>
                        <div><span>Portal Access</span><?php echo $portalEnabled ? 'Enabled' : 'Disabled'; ?></div>
                    </div>
                </div>

                <div class="overview-card">
                    <div class="overview-title">Statutory Information</div>
                    <div class="overview-grid">
                        <div><span>Professional Tax</span><?php echo (pick_field($employee, ['professional_tax']) ? '<span class="enabled-text">Enabled</span>' : '-'); ?></div>
                    </div>
                </div>

                <div class="overview-card">
                    <div class="overview-title">Personal Information</div>
                    <div class="overview-grid">
                        <div><span>Date of Birth</span><?php echo htmlspecialchars(pick_field($employee, ['dob', 'date_of_birth']) ?? '-'); ?></div>
                        <div><span>Email Address</span><?php echo htmlspecialchars(pick_field($employee, ['personal_email']) ?? '-'); ?></div>
                        <div><span>Father's Name</span><?php echo htmlspecialchars(pick_field($employee, ['father_name']) ?? '-'); ?></div>
                        <div><span>Residential Address</span><?php echo htmlspecialchars(pick_field($employee, ['addr1']) ?? '-'); ?></div>
                        <div><span>PAN</span><?php echo htmlspecialchars(pick_field($employee, ['pan']) ?? '-'); ?></div>
                        <div><span>Differently Abled Type</span><?php echo htmlspecialchars(pick_field($employee, ['abled_type']) ?? '-'); ?></div>
                    </div>
                </div>

                <div class="overview-card">
                    <div class="overview-title">Payment Information</div>
                    <div class="overview-grid">
                        <div><span>Payment Mode</span><?php echo htmlspecialchars(pick_field($employee, ['pay_method', 'payment_method']) ?? '-'); ?></div>
                    </div>
                </div>

                <div class="overview-card">
                    <div class="overview-title">Investments</div>
                    <div class="overview-grid">
                        <div>
                            <span>Proof Of Investments</span>
                            Submit and store employee POI details for approvals.
                        </div>
                    </div>
                    <div style="margin-top:18px;">
                        <a class="btn-primary" href="employee_poi_submission.php?emp_id=<?php echo urlencode((string)$empId); ?>">Open POI Submission</a>
                    </div>
                </div>
            <?php } ?>
        </section>
    </main>
</div>
<div class="master-modal" id="vehicleDetailsModal" aria-hidden="<?php echo $showVehicleModal ? 'false' : 'true'; ?>">
    <div class="master-backdrop" data-close-vehicle-modal></div>
    <div class="master-dialog master-dialog--wide vehicle-dialog">
        <div class="master-header">
            <h3>Employer Car Details for Perquisite Calculation</h3>
            <button class="modal-close" type="button" data-close-vehicle-modal aria-label="Close">Ã—</button>
        </div>
        <div class="vehicle-banner">
            Company-owned or hired cars used by employees for official or personal use are eligible to claim perquisite
        </div>
        <form method="POST" class="master-form vehicle-form" novalidate>
            <input type="hidden" name="vehicle_submit" value="1">
            <div class="vehicle-section">
                <label class="flabel">Owner of the Car<span class="req">*</span></label>
                <div class="vehicle-options">
                    <label class="vehicle-option">
                        <input type="radio" name="owner_of_car" value="employer_owned" <?php echo $vehicleDetails['owner_of_car'] === 'employer_owned' ? 'checked' : ''; ?>>
                        <span>Employer-owned (or) Hired for Employee</span>
                    </label>
                    <label class="vehicle-option">
                        <input type="radio" name="owner_of_car" value="employee_owned" <?php echo $vehicleDetails['owner_of_car'] === 'employee_owned' ? 'checked' : ''; ?>>
                        <span>Employee-owned</span>
                    </label>
                </div>
            </div>
            <div class="vehicle-section">
                <label class="flabel">Maintenance Cost Met By<span class="req">*</span></label>
                <div class="vehicle-options vehicle-options--inline">
                    <label class="vehicle-option">
                        <input type="radio" name="maintenance_cost_met_by" value="employer" <?php echo $vehicleDetails['maintenance_cost_met_by'] === 'employer' ? 'checked' : ''; ?>>
                        <span>Employer</span>
                    </label>
                    <label class="vehicle-option">
                        <input type="radio" name="maintenance_cost_met_by" value="employee" <?php echo $vehicleDetails['maintenance_cost_met_by'] === 'employee' ? 'checked' : ''; ?>>
                        <span>Employee</span>
                    </label>
                </div>
            </div>
            <div class="vehicle-section">
                <label class="flabel">Cubic Capacity of Company Owned Car<span class="req">*</span></label>
                <div class="vehicle-options vehicle-options--inline">
                    <label class="vehicle-option">
                        <input type="radio" name="cubic_capacity" value="upto_1600cc" <?php echo $vehicleDetails['cubic_capacity'] === 'upto_1600cc' ? 'checked' : ''; ?>>
                        <span>Upto 1600CC</span>
                    </label>
                    <label class="vehicle-option">
                        <input type="radio" name="cubic_capacity" value="greater_than_1600cc" <?php echo $vehicleDetails['cubic_capacity'] === 'greater_than_1600cc' ? 'checked' : ''; ?>>
                        <span>Greater than 1600CC</span>
                    </label>
                </div>
            </div>
            <div class="vehicle-section">
                <label class="flabel">Is driver provided by company?<span class="req">*</span></label>
                <div class="vehicle-options vehicle-options--inline">
                    <label class="vehicle-option">
                        <input type="radio" name="driver_provided_by_company" value="yes" <?php echo $vehicleDetails['driver_provided_by_company'] === 'yes' ? 'checked' : ''; ?>>
                        <span>Yes</span>
                    </label>
                    <label class="vehicle-option">
                        <input type="radio" name="driver_provided_by_company" value="no" <?php echo $vehicleDetails['driver_provided_by_company'] === 'no' ? 'checked' : ''; ?>>
                        <span>No</span>
                    </label>
                </div>
            </div>
            <div class="form-actions master-actions">
                <button class="btn-primary" type="submit">Save</button>
                <button class="btn-cancel-lnk" type="button" data-close-vehicle-modal>Cancel</button>
            </div>
        </form>
    </div>
</div>
<script>
  (function(){
    const toggles = document.querySelectorAll('[data-nav-toggle]');
    toggles.forEach(btn => {
      btn.addEventListener('click', () => {
        const group = btn.closest('.nav-group');
        if (!group) return;
        group.classList.toggle('open');
      });
    });
  })();
  (function(){
    const wrap = document.querySelector('.overview-menu-wrap');
    const toggle = document.querySelector('[data-overview-menu-toggle]');
    const menu = document.getElementById('overviewMenu');
    if (!wrap || !toggle || !menu) return;

    const closeMenu = () => {
      wrap.classList.remove('open');
      menu.hidden = true;
      toggle.setAttribute('aria-expanded', 'false');
    };

    toggle.addEventListener('click', function(event){
      event.stopPropagation();
      const willOpen = menu.hidden;
      if (willOpen) {
        menu.hidden = false;
        wrap.classList.add('open');
        toggle.setAttribute('aria-expanded', 'true');
      } else {
        closeMenu();
      }
    });

    document.addEventListener('click', function(event){
      if (!wrap.contains(event.target)) {
        closeMenu();
      }
    });

    document.addEventListener('keydown', function(event){
      if (event.key === 'Escape') {
        closeMenu();
      }
    });
  })();
  (function(){
    const modal = document.getElementById('vehicleDetailsModal');
    const openBtn = document.querySelector('[data-open-vehicle-modal]');
    if (!modal) return;
    const closeModal = () => {
      modal.classList.remove('open');
      modal.setAttribute('aria-hidden', 'true');
    };
    const openModal = () => {
      modal.classList.add('open');
      modal.setAttribute('aria-hidden', 'false');
      const first = modal.querySelector('input[type="radio"], button, input:not([type="hidden"])');
      if (first) {
        setTimeout(() => first.focus(), 0);
      }
    };
    if (openBtn) {
      openBtn.addEventListener('click', function(event){
        event.stopPropagation();
        openModal();
      });
    }
    modal.querySelectorAll('[data-close-vehicle-modal]').forEach(btn => {
      btn.addEventListener('click', closeModal);
    });
    modal.addEventListener('click', function(event){
      if (event.target === modal) {
        closeModal();
      }
    });
    document.addEventListener('keydown', function(event){
      if (event.key === 'Escape') {
        closeModal();
      }
    });
    <?php if ($showVehicleModal): ?>
    openModal();
    <?php endif; ?>
  })();
</script>
</body>
</html>


