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

// Ensure admin is logged in
if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: admin_login.php');
    exit;
}

// Logout functionality
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin_login.php');
    exit;
}

// Retrieve profile_link from URL
if (!isset($_GET['profile_link'])) {
    die("Profile link is missing.");
}
$profile_link = $_GET['profile_link'];

// Retrieve the contact number for sending SMS
$stmt = $pdo->prepare("SELECT contact_no, customer_name FROM users WHERE profile_link = :profile_link");
$stmt->execute([':profile_link' => $profile_link]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    die("User not found.");
}

$contact_no = $user['contact_no'];
$customer_name = $user['customer_name'];

// Proceed to update the user profile with the form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        // Get form inputs
        $fuel_level = $_POST['fuel_level'] ?? 'Empty';
        $remarks = htmlspecialchars($_POST['remarks'] ?? '', ENT_QUOTES, 'UTF-8');
        $damages_noted = htmlspecialchars($_POST['damages_noted'] ?? '', ENT_QUOTES, 'UTF-8');
        $customer_signature = $_POST['customer_signature'] ?? '';
        $vehicle_diagram = $_POST['vehicle_diagram'] ?? '';

        // Don't overwrite customer_name with POST data, use URL value instead
        $customer_name = htmlspecialchars($customer_name, ENT_QUOTES, 'UTF-8'); // Keeps the original name from URL

        // Define dynamic fields
        $dynamic_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'
        ];

        // Prepare SQL update statement dynamically
        $sql = "UPDATE users SET 
            fuel_level = :fuel_level,
            remarks = :remarks,
            damages_noted = :damages_noted,
            customer_signature = :customer_signature,
            vehicle_diagram = :vehicle_diagram,
            customer_name = :customer_name"; // Updated customer_name from URL

        // Add dynamic fields to the SQL query
        foreach ($dynamic_fields as $field) {
            $sql .= ", $field = :$field";
        }

        $sql .= " WHERE profile_link = :profile_link";

        // Prepare the statement
        $stmt = $pdo->prepare($sql);

        // Bind basic parameters
        $params = [
            ':fuel_level' => $fuel_level,
            ':remarks' => $remarks,
            ':damages_noted' => $damages_noted,
            ':customer_signature' => $customer_signature,
            ':vehicle_diagram' => $vehicle_diagram,
            ':customer_name' => $customer_name, // Keep customer_name from the URL
            ':profile_link' => $profile_link
        ];

        // Bind dynamic parameters
        foreach ($dynamic_fields as $field) {
            $params[":$field"] = $_POST[$field] ?? 'No'; // Default to 'No' if not submitted
        }

        // Execute the query
        $stmt->execute($params);

        // Handle image uploads
        $image_fields = ['front_image', 'back_image', 'left_image', 'right_image', 'top_image', 'bottom_image'];
        $allowed_types = ['image/jpeg', 'image/png', 'image/jpg'];

        foreach ($image_fields as $image_field) {
            if (!empty($_FILES[$image_field]['name'])) {
                $file_tmp = $_FILES[$image_field]['tmp_name'];
                $file_type = mime_content_type($file_tmp);
                $file_name = time() . '_' . basename($_FILES[$image_field]['name']);
                $target_path = 'uploads/' . $file_name;

                if (!in_array($file_type, $allowed_types)) {
                    die("Error: Only JPG, PNG, and JPEG files are allowed.");
                }

                if (move_uploaded_file($file_tmp, $target_path)) {
                    $stmt = $pdo->prepare("
                        UPDATE users SET $image_field = :image_path WHERE profile_link = :profile_link
                    ");
                    $stmt->execute([
                        ':image_path' => $target_path,
                        ':profile_link' => $profile_link
                    ]);
                }
            }
        }

        // Prepare SMS message
        $sms_message = "Hello $customer_name, your profile has been updated. Visit your profile here: https://blog.onedriveme.com/profile.php?link=$profile_link";

        // Send SMS via Notify.lk API
        $user_id = '29008'; // Your User ID
        $api_key = 'HwPmIPEriPmyEOVOmfhp'; // Your API Key
        $sender_id = 'BnS INT'; // Your approved Sender ID (replace with your actual sender ID)

        // Prepare the URL for the SMS request
        $sms_url = "https://app.notify.lk/api/v1/send?user_id=$user_id&api_key=$api_key&sender_id=$sender_id&to=$contact_no&message=" . urlencode($sms_message);

        // Send the request
        $response = file_get_contents($sms_url);

        // Check if the request was successful
        if ($response === FALSE) {
            $sms_status = 'fail';
            $sms_message = 'Error sending SMS';
        } else {
            $sms_status = 'success';
            $sms_message = 'SMS sent successfully';
        }

        // Redirect to success page with SMS status and profile update message
        header("Location: success.php?sms_status=$sms_status&sms_message=" . urlencode($sms_message) . "&profile_link=$profile_link");
        exit;

    } catch (PDOException $e) {
        die("Database error: " . $e->getMessage());
    }
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('partials/head.php'); ?>
    <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>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const imageFields = ['front_image', 'back_image', 'left_image', 'right_image', 'top_image', 'bottom_image'];
            imageFields.forEach(field => {
                const input = document.getElementById(field);
                const previewContainer = document.getElementById(`${field}_preview`);
                if (input && previewContainer) {
                    input.addEventListener('change', function(event) {
                        const file = event.target.files[0];
                        if (file) {
                            const reader = new FileReader();
                            reader.onload = function(e) {
                                const img = document.createElement('img');
                                img.src = e.target.result;
                                img.style.maxWidth = '200px';
                                img.style.maxHeight = '200px';
                                img.style.margin = '10px';
                                previewContainer.innerHTML = '';
                                previewContainer.appendChild(img);
                            };
                            reader.readAsDataURL(file);
                        }
                    });
                }
            });
        });
    </script>
</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>Second Form</h4>
                        <h6>Fill in the Second Form details below</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));

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

                                                        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'>";
                                                        echo "<option value='Yes'>Yes</option>";
                                                        echo "<option value='No'>No</option>";
                                                        echo "</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'>";
                                                            echo "<option value='Yes'>Yes</option>";
                                                            echo "<option value='No'>No</option>";
                                                            echo "</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">Empty</option>
                                                <option value="4/1">4/1</option>
                                                <option value="4/2">4/2</option>
                                                <option value="4/3">4/3</option>
                                                <option value="Full">Full</option>
                                            </select>
                                        </div>
                                    </div>
                                    <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..."></textarea>
                                        </div>
                                    </div>
                                    <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..."></textarea>
                                        </div>
                                    </div>
                                    <div class="form-section mt-4">
                                        <h5 class="mb-3">Customer Signature</h5>
                                        <div class="border border-secondary rounded p-3">
                                            <canvas id="customer_signatureCanvas" class="w-100 border border-dark" style="height: 200px; cursor: crosshair;"></canvas>
                                            <button type="button" id="clearCustomerBtn" class="btn btn-danger mt-2">Clear Signature</button>
                                            <button type="button" id="saveCustomerBtn" class="btn btn-primary mt-2">Save Signature</button>
                                        </div>
                                        <input type="hidden" id="customer_signatureData" name="customer_signature">
                                    </div>
<div class="form-section">
    <h5 class="mb-3">Markers</h5>
    <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 w-100" 
                 style="background-color: #e0e0e0; position: relative; display: block;" />
            
            <!-- SVG Overlay with Correct Positioning -->
            <svg id="svgOverlay" 
                 class="position-absolute top-0 start-0" 
                 style="width: 100%; height: 100%; pointer-events: none; left: 0; top: 0;">
            </svg>
        </div>
    </div>
    <ul id="markerList" class="list-group mt-3"></ul>
</div>
                          <input type="hidden" id="vehicle_diagram" name="vehicle_diagram" value="">
                                    <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) {
                                                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/*'>";
                                                echo "<div id='{$image_field}_preview' class='mt-2'></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 class="mb-4 mb-md-5 text-white d-block d-md-none"></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>
    <script src="assets/script/custom.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
    let markers = [];
    const markerList = document.getElementById('markerList');
    const markersDataInput = document.getElementById('vehicle_diagram');
    const mapImage = document.getElementById('mapImage');
    const svgOverlay = document.getElementById('svgOverlay');

    if (mapImage) {
        mapImage.style.cursor = 'crosshair'; // Indicate clickable area
        
        function getImageSize() {
            const rect = mapImage.getBoundingClientRect();
            return { width: rect.width, height: rect.height, left: rect.left, top: rect.top };
        }

        function addMarker(event) {
            event.preventDefault();

            const imageSize = getImageSize();
            const clientX = event.clientX || event.touches?.[0]?.clientX;
            const clientY = event.clientY || event.touches?.[0]?.clientY;

            if (!clientX || !clientY) return; 

            const x = ((clientX - imageSize.left) / imageSize.width) * 100;
            const y = ((clientY - imageSize.top) / imageSize.height) * 100;

            const markerId = `marker-${Date.now()}`;
            const marker = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
            marker.setAttribute('cx', `${x}%`);
            marker.setAttribute('cy', `${y}%`);
            marker.setAttribute('r', 5);
            marker.setAttribute('fill', 'red');
            marker.setAttribute('class', 'marker-point');
            marker.setAttribute('data-id', markerId);
            svgOverlay.appendChild(marker);

            markers.push({ id: markerId, x, y, note: '' });
            updateMarkerList();
            updateMarkersData();
        }

        function updateMarkerList() {
            markerList.innerHTML = '';
            markers.forEach(marker => {
                const li = document.createElement('li');
                li.classList.add('list-group-item');
                li.innerHTML = `
                    <div>
                        <strong>Marker at (${marker.x.toFixed(2)}%, ${marker.y.toFixed(2)}%)</strong>
                        <button type="button" class="btn btn-danger btn-sm float-end delete-marker" data-id="${marker.id}">Delete</button>
                    </div>
                    <select class="form-control mt-2" data-id="${marker.id}">
                        <option value="" disabled ${!marker.note ? 'selected' : ''}>Select Damage</option>
                        <option value="S">Scratch</option>
                        <option value="D">Dent</option>
                        <option value="P">Paint Defect</option>
                        <option value="C">Crack</option>
                        <option value="R">Rust</option>
                        <option value="B">Bubble</option>
                    </select>
                `;
                markerList.appendChild(li);
            });
            
            document.querySelectorAll('.delete-marker').forEach(button => {
                button.addEventListener('click', function () {
                    deleteMarker(this.getAttribute('data-id'));
                });
            });
            
            document.querySelectorAll('select').forEach(select => {
                select.addEventListener('change', function () {
                    updateNoteForMarker(this.getAttribute('data-id'), this.value);
                });
            });
        }

        function updateNoteForMarker(markerId, note) {
            const marker = markers.find(m => m.id === markerId);
            if (marker) {
                marker.note = note;
                updateMarkersData();
            }
        }

        function updateMarkersData() {
            markersDataInput.value = JSON.stringify(markers);
        }

        function deleteMarker(markerId) {
            const markerElement = svgOverlay.querySelector(`[data-id="${markerId}"]`);
            if (markerElement) markerElement.remove();
            markers = markers.filter(m => m.id !== markerId);
            updateMarkerList();
            updateMarkersData();
        }

        window.addEventListener('resize', function () {
            markers.forEach(marker => {
                const markerElement = svgOverlay.querySelector(`[data-id="${marker.id}"]`);
                if (markerElement) {
                    markerElement.setAttribute('cx', `${marker.x}%`);
                    markerElement.setAttribute('cy', `${marker.y}%`);
                }
            });
        });

        mapImage.addEventListener('click', addMarker);
        mapImage.addEventListener('touchstart', addMarker);
    }
});

    </script>
</body>
</html>
