<?php
include "include/auth.php";
?>
<!doctype html>
<html class="fixed dark">

<head>
    <?php include "include/head.php"; 
    // Retrieve dynamic variables if passed
    $fleet_id = isset($_GET['fleet_id']) ? intval($_GET['fleet_id']) : 0;

    // Fetch vehicle details if fleet_id is provided
    $vehicle_data = [];
    if ($fleet_id > 0) {
        $vehicle_query = $db2->query("SELECT * FROM fleet WHERE fleet_id = $fleet_id");
        $vehicle_data = $vehicle_query->fetch_assoc();
    }

    // Fetch service groups
    $service_groups = $db2->query("SELECT * FROM service_groups ORDER BY service_groups_name ASC");

    // Fetch vehicle status and station details
    $vehicle_status_query = $db2->query(
        "SELECT vs.*, vstat.vehicle_status_name, s.station_name 
        FROM vehicle_status vs
        JOIN vehicle_statuses vstat ON vs.status_id = vstat.vehicle_status_id
        JOIN jostj_vikrentcar_stations s ON vs.location_id = s.station_id
        WHERE vs.veh_id = $fleet_id 
        ORDER BY vs.timestamp DESC LIMIT 1"
    );
    $vehicle_status = $vehicle_status_query ? $vehicle_status_query->fetch_assoc() : null;
// Preload rental status
$rental_status_query = $db2->query("
    SELECT 
        c.contract_id,
        IF(c.cont_extended = 1, FROM_UNIXTIME(ce.ext_new_date), FROM_UNIXTIME(c.cont_return)) AS return_date,
        c.vehfleet_id AS original_vehicle_id,
        vc.veh_id AS changed_vehicle_id,
        MAX(vc.change_from) AS latest_change,
        c.cont_veh_change
    FROM contracts c
    LEFT JOIN contract_extensions ce ON c.contract_num = ce.cont_ext_cid
    LEFT JOIN veh_change vc ON c.contract_id = vc.contract_id
    WHERE c.cont_cancelled = 0 
      AND c.returned = 0
      AND IF(c.cont_extended = 1, ce.ext_new_date, c.cont_return) > UNIX_TIMESTAMP()
    GROUP BY c.contract_id, vc.veh_id
    ORDER BY vc.change_from DESC
");

$rental_status_map = [];
while ($row = $rental_status_query->fetch_assoc()) {
    if ($row['cont_veh_change'] == 1 && !empty($row['changed_vehicle_id'])) {
        $rental_status_map[$row['changed_vehicle_id']] = [
            'status' => 'Out on Rental (Replaced)',
            'return_date' => $row['return_date']
        ];
    } elseif (!empty($row['original_vehicle_id'])) {
        $rental_status_map[$row['original_vehicle_id']] = [
            'status' => 'Out on Rental',
            'return_date' => $row['return_date']
        ];
    }
}

// Preload vehicle status
$vehicle_status_query = $db2->query("
    SELECT 
        f.fleet_id,
        f.active,
        vstat.vehicle_status_name AS latest_status,
        vstat.vehicle_status_color AS badge_color,
        MAX(vs.timestamp) AS status_timestamp
    FROM fleet f
    LEFT JOIN vehicle_status vs ON f.fleet_id = vs.veh_id
    LEFT JOIN vehicle_statuses vstat ON vs.status_id = vstat.vehicle_status_id
    WHERE f.fleet_id = $fleet_id
    GROUP BY f.fleet_id
    ORDER BY vs.timestamp DESC
");

$vehicle_status_map = [];
if ($vehicle_status_query) {
    while ($row = $vehicle_status_query->fetch_assoc()) {
        $vehicle_status_map[$row['fleet_id']] = [
            'status' => $row['latest_status'] ?? 'Available',
            'badge_color' => $row['badge_color'] ?? 'success'
        ];
    }
}
    ?>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
        .ecommerce-timeline:before {
            box-shadow: none !important;
        }

        .ecommerce-timeline:after {
            box-shadow: none !important;
        }

        .editbutton {
            position: absolute;
            right: 15px;
            top: 10px;
        }

        .editnotes {
            position: absolute;
            right: 15px;
            bottom: 10px;
        }

        .rd-container-attachment {
            z-index: 10002;
            zoom: 80%
        }

        .modal {
            max-width: 90%;
        }

        .posabs {
            position: absolute;
            right: 10px;
            top: 10px;
        }
    </style>
</head>

<body>
    <section class="body">
        <header class="header">
            <div class="logo-container">
                <a href="index.php" class="logo">
                    <img src="img/logo-light.png" width="75" height="35" alt="Web Voyage" />
                </a>
                <div class="d-md-none toggle-sidebar-left" data-toggle-class="sidebar-left-opened" data-target="html"
                    data-fire-event="sidebar-left-opened">
                    <i class="fas fa-bars" aria-label="Toggle sidebar"></i>
                </div>
            </div>
            <div class="header-right">
                <?php include "include/search.php"; ?>
                <span class="separator"></span>
                <?php include "include/notifications.php"; ?>
                <span class="separator"></span>
                <?php include "include/userbox.php"; ?>
            </div>
        </header>

        <div class="inner-wrapper">
            <?php include "include/nav.php"; ?>

            <section role="main" class="content-body">
                <header class="page-header">
                    <h2>Add Vehicle Service - <?php echo $row["lic_num"]; ?> </h2>
                    <div class="right-wrapper text-right">
                        <ol class="breadcrumbs">
                            <li>
                                <a href="index.php">
                                    <i class="fas fa-home"></i>
                                </a>
                            </li>
                            <li><span>WV Admin</span></li>
                            <li><span>Add Vehicle Service </span></li>
                        </ol>
                        <a class="sidebar-right-toggle" data-open="sidebar-right">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                    </div>
                </header>

                <form id="addServiceForm" class="order-details action-buttons-fixed" method="post" name="form1"
                    action="actions/add_service_log.php">
                    <div class="row">
                        <div class="col-xl-4 mb-3 ">
                            <div class="card">
                                <div class="card-header">
                                    <h2 class="card-title">Vehicle Information</h2>
                                </div>
                                <div class="card-body">
                                    <div class="form-row">
                                        <div class="form-group col-12 mb-3 pt-0" style="border-top:none;">
                                            <label for="license_number">License Number</label>
                                            <input type="text" class="form-control" id="license_number"
                                                name="license_number"
                                                value="<?php echo $vehicle_data['lic_num'] ?? ''; ?>"
                                                <?php echo $fleet_id > 0 ? 'readonly' : ''; ?>>
                                        </div>
                                    </div>
                                    <div class="form-row">
                                        <div class="form-group col-12 mb-3 pt-0" style="border-top:none;">
                                            <label for="current_km">Current KM</label>
                                            <input type="number" class="form-control" id="current_km" name="current_km"
                                                required>
                                        </div>
                                    </div>
                                    <div class="form-row">
                                        <div class="form-group col-6 mb-3 pt-0" style="border-top:none;">
                                            <label for="next_service_date">Next Service Date <i
                                                    class="fas fa-info-circle" data-bs-toggle="tooltip"
                                                    title="Suggested: <?php echo date('d/m/Y', strtotime('+6 months')); ?>"></i></label>
                                            <input type="date" class="form-control" id="next_service_date"
                                                name="next_service_date">
                                        </div>
                                        <div class="form-group col-6 mb-3 pt-0" style="border-top:none;">
                                            <label for="next_service_km">Next Service KM <i class="fas fa-info-circle"
                                                    data-bs-toggle="tooltip" title="Suggested: +10,000 KM"></i></label>
                                            <input type="number" class="form-control" id="next_service_km"
                                                name="next_service_km">
                                        </div>
                                    </div>

                                </div>
                            </div>


                        </div>

                        <div class="col-xl-4 mb-3 ">
                            <div class="card">
                                <div class="card-header">
                                    <h2 class="card-title">Current Vehicle Status</h2><?php
                                        if ($vehicle_data['active'] == "0") {
                                            // Inactive vehicle
                                            echo "<span class='badge badge-danger posabs'>Inactive</span>";
                                        } elseif (isset($rental_status_map[$fleet_id])) {
                                            // Vehicle on contract
                                            $status = $rental_status_map[$fleet_id]['status'];
                                            $return_date = $rental_status_map[$fleet_id]['return_date'] ?? null;

                                            echo "<span class='badge badge-warning posabs'>$status</span><br>";
                                            if ($return_date) {
                                                echo "<small>Return: " . date('d/m/Y H:i', strtotime($return_date)) . "</small>";
                                            }
                                        } else {
                                            // Available vehicle
                                            $status = $vehicle_status_map[$fleet_id]['status'] ?? 'Available';
                                            $badge_color = $vehicle_status_map[$fleet_id]['badge_color'] ?? 'success';

                                            echo "<span class='badge badge-$badge_color posabs'>$status</span>";
                                        }
                                        ?>
                                </div>
                                <div class="card-body">

                                    <?php if ($vehicle_status) { ?>
                                    <p><strong>Status:</strong> <?php echo $vehicle_status['vehicle_status_name']; ?>
                                    </p>
                                    <p><strong>Location:</strong> <?php echo $vehicle_status['station_name']; ?></p>
                                    <p><strong>Last Updated:</strong>
                                        <?php echo date('d/m/Y H:i', strtotime($vehicle_status['timestamp'])); ?></p>
                                    <?php } else { ?>
                                    <p>No status information available.</p>
                                    <?php } ?>

                                </div>
                            </div>
                        </div>
                        <div class="col-xl-4 mb-3 ">
                            <div class="card">
                                <div class="card-header">
                                    <h2 class="card-title">Update Vehicle Status</h2>
                                </div>
                                <div class="card-body">

                                    <form method="POST" action="actions/update_vehicle_status.php">
                                        <div class="form-group">
                                            <label for="new_status">Update Vehicle Status</label>
                                            <select class="form-control" id="new_status" name="new_status">
                                                <?php
                                                    $statuses = $db2->query("SELECT * FROM vehicle_statuses ORDER BY vehicle_status_name ASC");
                                                    while ($status = $statuses->fetch_assoc()) {
                                                        echo '<option value="' . $status['vehicle_status_id'] . '">' . $status['vehicle_status_name'] . '</option>';
                                                    }
                                                    ?>
                                            </select>
                                        </div>
                                        <input type="hidden" name="veh_id" value="<?php echo $fleet_id; ?>">
                                        <button type="submit" class="btn btn-primary mt-2">Update Status</button>
                                    </form>

                                </div>
                            </div>
                        </div>
                        <div class="col-xl-12 mb-3 ">
                            <div class="card">
                                <div class="card-header">
                                    <h2 class="card-title">Service Details</h2>
                                </div>
                                <div class="card-body">
                                    <div class="form-row">
                                        <label for="service_group col-12 mb-3 pt-0">Service Group</label>
                                        <select class="form-control" id="service_group" name="service_group" required>
                                            <option value="">-- Select Service Group --</option>
                                            <?php while ($group = $service_groups->fetch_assoc()) { ?>
                                            <option value="<?php echo $group['service_groups_id']; ?>">
                                                <?php echo $group['service_groups_name']; ?>
                                            </option>
                                            <?php } ?>
                                        </select>
                                    </div>

                                    <div class="form-row">
                                        <label>Service Tasks</label>
                                        <div  class="form-group col-12 mb-3 pt-0" id="service_tasks_container">
                                            <!-- Tasks will be dynamically loaded here -->
                                        </div>
                                    </div>
                                    <div class="form-row">
                                        <div class="form-group col-12 mb-3 pt-0" style="border-top:none;">
                                            <label for="damages">Damages (Optional)</label>
                                            <textarea class="form-control" id="damages" name="damages"
                                                rows="3"></textarea>
                                        </div>
                                        <div class="form-group col-12 mb-3 pt-0" style="border-top:none;">
                                            <label for="info">Additional Info (Optional)</label>
                                            <textarea class="form-control" id="info" name="info" rows="3"></textarea>
                                        </div>
                                    </div>

                                </div>
                            </div>
                        </div>
                        <div class="col-xl-12 text-right">
                            <button type="submit" class="btn btn-primary">Add Service</button>
                            <a href="vehicle.php?id=<?php echo $fleet_id; ?>" class="btn btn-secondary">Cancel</a>
                        </div>
                    </div>
                </form>
            </section>
        </div>
        <?php include "include/aside.php"; ?>
    </section>
    <!-- Vendor -->
    <script src="vendor/jquery/jquery.js"></script>
    <script src="vendor/jquery-browser-mobile/jquery.browser.mobile.js"></script>
    <script src="vendor/popper/umd/popper.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.js"></script>
    <script src="vendor/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
    <script src="vendor/common/common.js"></script>
    <script src="vendor/nanoscroller/nanoscroller.js"></script>
    <script src="vendor/magnific-popup/jquery.magnific-popup.js"></script>
    <script src="vendor/jquery-placeholder/jquery.placeholder.js"></script>
    <!-- Specific Page Vendor -->
    <script src="vendor/select2/js/select2.js"></script>
    <script src="vendor/pnotify/pnotify.custom.js"></script>
    <!--(remove-empty-lines-end)-->
    <!-- Theme Base, Components and Settings -->
    <script src="js/theme.js"></script>
    <!-- Theme Custom -->
    <script src="js/custom.js"></script>
    <!-- Theme Initialization Files -->
    <script src="js/theme.init.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />
    <!-- Examples -->
    <script src="js/examples/examples.header.menu.js"></script>
    <script src="js/examples/examples.ecommerce.orders.detail.js"></script>
    <script src="js/examples/examples.modals.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"
        integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ=="
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/rome/3.0.2/rome.standalone.min.js"
        integrity="sha512-cJ4aSZY0xBXrcH65MOwCloQAiTNCBm2F8/KlcBTlczgn4txZkT7h3YSXULN06pkUnsySMEg5BU4QCHAr97U7ng=="
        crossorigin="anonymous"></script>

    <script>
        // Load service tasks dynamically based on the selected service group
        $(document).ready(function () {
            $('[data-bs-toggle="tooltip"]').tooltip(); // Initialize tooltips

            $('#service_group').on('change', function () {
                const groupId = $(this).val();
                if (groupId) {
                    $.ajax({
                        url: 'actions/get_service_tasks.php',
                        method: 'GET',
                        data: {
                            group_id: groupId
                        },
                        success: function (response) {
                            $('#service_tasks_container').html(response);
                        },
                        error: function () {
                            alert('Failed to load service tasks. Please try again.');
                        }
                    });
                } else {
                    $('#service_tasks_container').empty();
                }
            });
        });
    </script>
</body>

</html>
<?php include "include/footer.php"; ?>