<?php
session_start();
include_once 'config/db.php';

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}

$profile_link = $_SESSION['profile_link'];
$sql = "SELECT * FROM users WHERE profile_link = :profile_link";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':profile_link', $profile_link, PDO::PARAM_STR);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$fields = [
    'battery', 'horn', 'washer_nipples', 'wiper_blades', 'head_lights', 'parking_lights', 
    'signal_lights', 'reverse_lights', 'fog_lamp', 'fender_light', 'hood_light', 'stop_light', 
    'inside_mirror', 'power_mirror', 'retractable_mirror', 'radio', 'dvd_screen', 'speakers', 
    'ash_tray', 'inner_door_locks', 'fuse_box_cover', 'sun_visor', 'remote_key', 'smart_key', 
    'cigar_lighter', 'velvet_carpets', 'mats', 'model_make_badges', 'fuel_tank_cap', 'alloy_wheels', 
    'rim_cup', 'wheel_center_cup', 'mud_flaps', 'body_moldings', 'dicky_board', 'hydraulic_jack', 
    'mechanical_jack', 'wheel_handles', 'spare_wheels', 'reverse_sensors', 'antenna', 'dashboard_warning_lights'
];

$old_values = [
    'battery' => $user['battery'],
    'horn' => $user['horn'],
    'washer_nipples' => $user['washer_nipples'],
    'wiper_blades' => $user['wiper_blades'],
    'head_lights' => $user['head_lights'],
    'parking_lights' => $user['parking_lights'],
    'signal_lights' => $user['signal_lights'],
    'reverse_lights' => $user['reverse_lights'],
    'fog_lamp' => $user['fog_lamp'],
    'fender_light' => $user['fender_light'],
    'hood_light' => $user['hood_light'],
    'stop_light' => $user['stop_light'],
    'inside_mirror' => $user['inside_mirror'],
    'power_mirror' => $user['power_mirror'],
    'retractable_mirror' => $user['retractable_mirror'],
    'radio' => $user['radio'],
    'dvd_screen' => $user['dvd_screen'],
    'speakers' => $user['speakers'],
    'ash_tray' => $user['ash_tray'],
    'inner_door_locks' => $user['inner_door_locks'],
    'fuse_box_cover' => $user['fuse_box_cover'],
    'sun_visor' => $user['sun_visor'],
    'remote_key' => $user['remote_key'],
    'smart_key' => $user['smart_key'],
    'cigar_lighter' => $user['cigar_lighter'],
    'velvet_carpets' => $user['velvet_carpets'],
    'mats' => $user['mats'],
    'model_make_badges' => $user['model_make_badges'],
    'fuel_tank_cap' => $user['fuel_tank_cap'],
    'alloy_wheels' => $user['alloy_wheels'],
    'rim_cup' => $user['rim_cup'],
    'wheel_center_cup' => $user['wheel_center_cup'],
    'mud_flaps' => $user['mud_flaps'],
    'body_moldings' => $user['body_moldings'],
    'dicky_board' => $user['dicky_board'],
    'hydraulic_jack' => $user['hydraulic_jack'],
    'mechanical_jack' => $user['mechanical_jack'],
    'wheel_handles' => $user['wheel_handles'],
    'spare_wheels' => $user['spare_wheels'],
    'reverse_sensors' => $user['reverse_sensors'],
    'antenna' => $user['antenna'],
    'dashboard_warning_lights' => $user['dashboard_warning_lights'],
    'markers' => json_decode($user['markers'], true),

];
$old_values['fuel_level'] = $user['fuel_level'];
$old_values['remarks'] = $user['remarks'];
$old_values['damages_noted'] = $user['damages_noted'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $updates = [];
    foreach ($fields as $field) {
        $updates[] = "$field = :$field";
    }
 $markers = isset($_POST['markers']) ? $_POST['markers'] : '[]';
    $sql = "UPDATE users SET markers = :markers WHERE profile_link = :profile_link";
    $stmt = $pdo->prepare($sql);

    foreach ($fields as $field) {
        if (isset($_POST[$field])) {
            $stmt->bindValue(":$field", $_POST[$field], PDO::PARAM_STR);
        } else {
            $stmt->bindValue(":$field", null, PDO::PARAM_NULL);
        }
    }

    $image_fields = ['front_image', 'back_image', 'left_image', 'right_image', 'top_image', 'bottom_image'];

    foreach ($image_fields as $image_field) {
        if (isset($_FILES[$image_field]) && $_FILES[$image_field]['error'] == UPLOAD_ERR_OK) {
            $image_tmp_name = $_FILES[$image_field]['tmp_name'];
            $image_name = uniqid($image_field . '_') . '.' . pathinfo($_FILES[$image_field]['name'], PATHINFO_EXTENSION);

            $valid_image_types = ['image/jpeg', 'image/png', 'image/gif'];
            if (!in_array($_FILES[$image_field]['type'], $valid_image_types)) {
                die("Error: Invalid file type for $image_field. Only JPG, PNG, or GIF files are allowed.");
            }

            if ($_FILES[$image_field]['size'] > 2 * 1024 * 1024) {
                die("Error: $image_field file size exceeds the limit of 2MB.");
            }

            $upload_dir = 'uploads/images/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }

            $target_file = $upload_dir . $image_name;
            move_uploaded_file($image_tmp_name, $target_file);

            $stmt->bindValue(":$image_field", $target_file, PDO::PARAM_STR);
        }
    }

    $stmt->bindValue(':profile_link', $profile_link, PDO::PARAM_STR);
   $stmt->bindValue(':markers', $markers, PDO::PARAM_STR);
    try {
        $stmt->execute();
        echo "User profile updated successfully! Profile link: <a href='profile.php?link=$profile_link'>View Profile</a>";
    } catch (PDOException $e) {
        die("Error: " . $e->getMessage());
    }
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('partials/head.php'); ?>
    <script src="/assets/edit_script/script.js"></script>
        <style>
        @media only screen and (max-width: 600px) {
            td.col-6.col-md-4 {
                min-width: 10px;
                max-width: 200px;
            }
            label.col-form-label {
                display: block;
                width: 110%;
                overflow-wrap: break-word;
                white-space: normal;
            }
            td.col-6.col-md-3 {
                width: 200px !important;
                max-width: 200px !important;
                min-width: 100px;
            }
        }
    </style>
</head>
<body>
    <div id="global-loader">
        <div class="whirly-loader"></div>
    </div>

    <div class="main-wrapper">
        <?php include('partials/header.php'); ?>
        <?php include('partials/sidebar.php'); ?>

        <div class="page-wrapper" style="max-height: 100vh; overflow-y: auto;">
            <div class="content">
                <div class="page-header mb-3">
                    <div class="page-title">
                        <h4>Vehicle Report Form</h4>
                        <h6>Fill in the details for the vehicle inspection and upload the images</h6>
                    </div>
                </div>

                <div class="row mb-5" style="margin-bottom: 100px;">
                    <div class="col-xl-8 d-flex">
                        <div class="card flex-fill">
                            <div class="card-body">
                                <form method="POST" action="" enctype="multipart/form-data" class="form-horizontal">
                                    <div class="form-section">
                                        <h5 class="mb-3">Vehicle Features</h5>
<div class="table-responsive">
    <table class="table table-striped">
        <tbody>
            <?php
            $fields = [
                'battery', 'horn', 'washer_nipples', 'wiper_blades', 'head_lights',
                'parking_lights', 'signal_lights', 'reverse_lights', 'fog_lamp', 'fender_light', 'hood_light', 'stop_light',
                'inside_mirror', 'power_mirror', 'retractable_mirror', 'radio', 'dvd_screen', 'speakers', 'ash_tray',
                'inner_door_locks', 'fuse_box_cover', 'sun_visor', 'remote_key', 'smart_key', 'cigar_lighter', 'velvet_carpets',
                'mats', 'model_make_badges', 'fuel_tank_cap', 'alloy_wheels', 'rim_cup', 'wheel_center_cup', 'mud_flaps',
                'body_moldings', 'dicky_board', 'hydraulic_jack', 'mechanical_jack', 'wheel_handles', 'spare_wheels',
                'reverse_sensors', 'antenna', 'dashboard_warning_lights'
            ];

            for ($i = 0; $i < count($fields); $i += 2) {
                $field1 = $fields[$i];
                $label1 = ucwords(str_replace('_', ' ', $field1));
                $field_name1 = strtolower(str_replace([' ', '–', '&'], ['_', '', ''], $field1));
                $old_value1 = isset($old_values[$field_name1]) ? $old_values[$field_name1] : 'No';

                $field2 = isset($fields[$i + 1]) ? $fields[$i + 1] : null;
                $label2 = $field2 ? ucwords(str_replace('_', ' ', $field2)) : '';
                $field_name2 = $field2 ? strtolower(str_replace([' ', '–', '&'], ['_', '', ''], $field2)) : '';
                $old_value2 = $field2 && isset($old_values[$field_name2]) ? $old_values[$field_name2] : 'No';

                echo "<tr>";
                echo "<td class='col-6 col-md-3'>$label1</td>";
                echo "<td class='col-6 col-md-3'>
                        <select name='$field_name1' id='$field_name1' class='form-control'>
                            <option value='Yes' " . ($old_value1 == 'Yes' ? 'selected' : '') . ">Yes</option>
                            <option value='No' " . ($old_value1 == 'No' ? 'selected' : '') . ">No</option>
                        </select>
                      </td>";

                if ($field2) {
                    echo "<td class='col-6 col-md-3'>$label2</td>";
                    echo "<td class='col-6 col-md-3'>
                            <select name='$field_name2' id='$field_name2' class='form-control'>
                                <option value='Yes' " . ($old_value2 == 'Yes' ? 'selected' : '') . ">Yes</option>
                                <option value='No' " . ($old_value2 == 'No' ? 'selected' : '') . ">No</option>
                            </select>
                          </td>";
                } else {
                    echo "<td colspan='2'></td>";
                }
                echo "</tr>";
            }
            ?>
        </tbody>
    </table>
</div>

                                    </div>

                                    <div class="form-section mt-4">
                                        <h5 class="mb-3">Fuel Level</h5>
                                        <div class="form-group">
                                            <label for="fuel_level" class="col-form-label">Fuel Level:</label>
                                            <select name="fuel_level" id="fuel_level" class="form-control">
                                                <option value="Empty" <?php echo (isset($old_values['fuel_level']) && $old_values['fuel_level'] == 'Empty') ? 'selected' : ''; ?>>Empty</option>
                                                <option value="4/1" <?php echo (isset($old_values['fuel_level']) && $old_values['fuel_level'] == '4/1') ? 'selected' : ''; ?>>4/1</option>
                                                <option value="2/1" <?php echo (isset($old_values['fuel_level']) && $old_values['fuel_level'] == '2/1') ? 'selected' : ''; ?>>2/1</option>
                                                <option value="4/3" <?php echo (isset($old_values['fuel_level']) && $old_values['fuel_level'] == '4/3') ? 'selected' : ''; ?>>4/3</option>
                                                <option value="Full" <?php echo (isset($old_values['fuel_level']) && $old_values['fuel_level'] == 'Full') ? 'selected' : ''; ?>>Full</option>
                                            </select>
                                        </div>
                                    </div>

<!-- Remarks Section -->
<div class="form-section mt-4">
    <h5 class="mb-3">Remarks</h5>
    <div class="form-group">
        <label for="remarks" class="col-form-label">Remarks:</label>
        <textarea name="remarks" id="remarks" class="form-control" rows="4" placeholder="Enter any remarks here..."><?php echo isset($old_values['remarks']) ? htmlspecialchars($old_values['remarks']) : ''; ?></textarea>
    </div>
</div>
<!-- Damages Noted Section -->
<div class="form-section mt-4">
    <h5 class="mb-3">Damages Noted</h5>
    <div class="form-group">
        <label for="damages_noted" class="col-form-label">Damages Noted:</label>
        <textarea name="damages_noted" id="damages_noted" class="form-control" rows="4" placeholder="Enter any damages here..."><?php echo isset($old_values['damages_noted']) ? htmlspecialchars($old_values['damages_noted']) : ''; ?></textarea>
    </div>
</div>
<!--<div class="form-section mt-4">-->
<!--    <div class="col-md-4">-->
<!--        <h5>Markers</h5>-->
<!--        <ul id="markerList" class="list-group">-->
<!--            <?php if (!empty($old_values['markers'])): ?>-->
<!--                <?php foreach ($old_values['markers'] as $index => $marker): ?>-->
<!--                    <li class="list-group-item" data-index="<?php echo $index; ?>">-->
<!--                        Marker <?php echo $index + 1; ?> - X: <?php echo $marker['x']; ?>, Y: <?php echo $marker['y']; ?>-->
<!--                        <button class="btn btn-sm btn-danger remove-marker" data-index="<?php echo $index; ?>">Remove</button>-->
<!--                    </li>-->
<!--                <?php endforeach; ?>-->
<!--            <?php endif; ?>-->
<!--        </ul>-->
<!--    </div>-->
<!--    <div class="col-md-8">-->
<!--        <h5>Click on the image to add markers</h5>-->
<!--        <div class="position-relative">-->
<!--            <img src="https://img.freepik.com/premium-vector/car-line-draw-insurance-rent-damage-condition-report-form_510486-111.jpg" id="mapImage" class="border img-fluid" style="background-color: #e0e0e0; cursor: pointer;"/>-->
<!--            <svg id="svgOverlay" class="position-absolute top-0 start-0" style="width: 100%; height: 100%; pointer-events: none;"></svg>-->
<!--        </div>-->
<!--    </div>-->
<!--</div>-->


                                    <div class="form-section mt-4">
                                        <h5 class="mb-3">Current Condition of the Vehicle</h5>
<div class="row">
    <?php
    $image_fields = ['front_image', 'back_image', 'left_image', 'right_image', 'top_image', 'bottom_image'];
    foreach ($image_fields as $image_field) {
        $image_url = isset($user[$image_field]) && !empty($user[$image_field]) ? $user[$image_field] : ''; // Get image URL from DB

        echo "<div class='col-md-6 mb-3'>";
        echo "<label for='$image_field' class='col-form-label fw-bold'>" . ucfirst(str_replace('_', ' ', $image_field)) . ":</label>";
        echo "<input type='file' name='$image_field' id='$image_field' class='form-control' accept='image/*' onchange='previewImage(this, \"{$image_field}_preview\")'>";

        // Display existing image if available
        echo "<div id='{$image_field}_preview' class='mt-2'>";
        if (!empty($image_url)) {
            echo "<img src='$image_url' alt='$image_field' class='img-thumbnail' style='max-width: 200px; max-height: 200px;'>";
        }
        echo "</div>";

        echo "</div>";
    }
    ?>
</div>

                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-lg-12 text-center">
                                            <button type="submit" class="btn btn-primary w-100">Submit</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php include('partials/footer.php'); ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
