<?php
include_once 'config/db.php';

if (isset($_GET['link'])) {
    $profile_link = $_GET['link'];

    $stmt = $pdo->prepare("SELECT * FROM users WHERE profile_link = :profile_link");
    $stmt->execute([':profile_link' => $profile_link]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user) {
        $markersJson = $user['vehicle_diagram'] ?? '[]';

        $update_stmt = $pdo->prepare("SELECT * FROM updates WHERE users_id = :user_id ORDER BY created_at DESC");
        $update_stmt->execute([':user_id' => $user['id']]);
        $updates = $update_stmt->fetchAll(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'
        ];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vehicle Profile</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.min.css">
    <style>
        body {
            background: linear-gradient(135deg, #f0f2f5, #d6dbe0);
            color: #333;
            font-family: 'Poppins', sans-serif;
        }
        .container {
            max-width: 1200px;
            margin: 30px auto;
            padding: 30px;
            border-radius: 20px;
            background: #fff;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
        }
        .profile-icon img {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            border: 3px solid #007BFF;
        }
        .user-info h2 {
            margin-top: 15px;
            color: #007BFF;
        }
        .recent-updates .update-item {
            background: #f1f3f5;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 15px;
        }
        .slider img {
            height: 150px;
            object-fit: cover;
            border-radius: 10px;
            cursor: pointer;
        }
        .user-images img, .fuel-level img, .signature-section img {
            width: 100%;
            max-height: 250px;
            object-fit: contain;
            border: 2px solid #007BFF;
            border-radius: 15px;
            margin-top: 10px;
        }
        .marker-list .list-group-item {
            background: #e3f2fd;
            border: none;
            margin: 5px 0;
            border-radius: 10px;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            padding-top: 60px;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.7);
        }
        .modal-content {
            margin: auto;
            display: block;
            max-width: 80%;
        }
        .close {
            position: absolute;
            top: 30px;
            right: 30px;
            color: #fff;
            font-size: 40px;
            cursor: pointer;
        }
        .vehicle-info p {
            margin: 6px 0;
        }
        .form-section {
            margin-top: 30px;
        }
        .slider {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }
        .update-image {
            max-width: 100%;
            padding: 5px !important;
        }
        .badge {
            font-size: 14px;
            padding: 8px 12px;
            border-radius: 20px;
            margin-left: 10px;
            vertical-align: middle;
        }
        .badge.bg-warning {
            background-color: #ffc107 !important;
            color: #000 !important;
        }
        .badge.bg-success {
            background-color: #28a745 !important;
            color: #fff !important;
        }
        .badge i {
            margin-right: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="d-flex align-items-center mb-4">
            <div class="profile-icon me-3">
                <img src="https://cdn-icons-png.flaticon.com/512/9094/9094119.png" alt="Profile Icon">
            </div>
            <div class="user-info">
                <h2><?= htmlspecialchars($user['customer_name']) ?>
                    <?php if ($user['status'] === 'Progress') : ?>
                        <span class="badge bg-warning"><i class="fas fa-spinner"></i> In Progress</span>
                    <?php elseif ($user['status'] === 'Completed') : ?>
                        <span class="badge bg-success"><i class="fas fa-check-circle"></i> Completed</span>
                    <?php endif; ?>
                </h2>
                <p><i class="fas fa-car"></i> Registration No: <?= htmlspecialchars($user['registration_no']) ?></p>
                <p><i class="fas fa-tachometer-alt"></i> Mileage: <?= htmlspecialchars($user['mileage']) ?></p>
                <p><i class="fas fa-calendar-alt"></i> Created At: <?= htmlspecialchars($user['date']) ?></p>
            </div>
        </div>
        <div class="recent-updates">
            <h3 class="mb-3">Recent Updates</h3>
            <?php foreach ($updates as $update) : ?>
                <div class="update-item">
                    <div class="d-flex align-items-center mb-2">
                        <img src="https://cdn-icons-png.flaticon.com/512/1253/1253756.png" class="admin-icon me-2" alt="Admin" style="width:40px;height:40px;border-radius:50%;">
                        <div>
                            <span class="fw-bold">Added By Admin</span><br>
                            <small><?= date('d/m/Y h:i A', strtotime($update['created_at'])) ?></small>
                        </div>
                    </div>
                    <p><strong>Title:</strong> <?= htmlspecialchars($update['title']) ?></p>
                    <p><strong>Description:</strong> <?= htmlspecialchars($update['description']) ?></p>
                    <?php if (!empty($update['image'])) : ?>
                        <div class="slider-container">
                            <div class="slider">
                                <?php
                                $images = explode(',', $update['image']);
                                foreach ($images as $image) :
                                    $image = trim($image);
                                    if (!empty($image)) : ?>
                                        <img src="<?= htmlspecialchars($image) ?>" alt="Update Image" onclick="openModal('<?= htmlspecialchars($image) ?>')" class="update-image">
                                    <?php endif;
                                endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
        
        <div class="form-section mt-4">
            <h5 class="mb-3">Damage Markers</h5>
            <div class="row">
                <div class="col-md-4">
                    <ul id="markerList" class="list-group marker-list"></ul>
                </div>
                <div class="col-md-8">
                    <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="img-fluid border rounded" 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>
        <div class="row mt-4">
            <div class="col-md-6">
                <h5 class="text-primary mb-3">Fuel Level</h5>
                <?php
                    $fuel_level = $user['fuel_level'];
                    $fuel_percentage = 0;

                    switch ($fuel_level) {
                        case 'Empty':
                            $fuel_percentage = 0;
                            break;
                        case '4/1':
                            $fuel_percentage = 25;
                            break;
                        case '2/1':
                            $fuel_percentage = 50;
                            break;
                        case '4/3':
                            $fuel_percentage = 75;
                            break;
                        case 'Full':
                            $fuel_percentage = 100;
                            break;
                        default:
                            $fuel_percentage = 0;
                    }
                ?>
                <div class="fuel-meter">
                    <div class="d-flex align-items-center">
                        <i class="fas fa-gas-pump fa-2x text-primary me-3"></i>
                        <div class="progress flex-grow-1" style="height: 25px; border-radius: 20px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);">
                            <div class="progress-bar" role="progressbar" style="width: <?= $fuel_percentage ?>%; background: linear-gradient(90deg, rgba(255, 59, 48, 1) 0%, rgba(255, 149, 0, 1) 25%, rgba(255, 204, 0, 1) 50%, rgba(76, 217, 100, 1) 75%, rgba(52, 199, 89, 1) 100%); border-radius: 20px;" aria-valuenow="<?= $fuel_percentage ?>" aria-valuemin="0" aria-valuemax="100">
                                <span class="ms-2 text-white fw-bold"><?= $fuel_level ?></span>
                            </div>
                        </div>
                    </div>
                    <div class="mt-2 text-muted">
                        <small>Current Fuel Level: <?= $fuel_level ?></small>
                    </div>
                </div>
            </div>
        </div>
        <div class="card shadow-sm mb-3" style="border-radius: 15px;">
            <div class="card-header bg-light" style="border-radius: 15px 15px 0 0;">
                <h5 class="card-title mb-0">Damage Report</h5>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <p><strong>Remarks:</strong></p>
                    <p class="ms-3"><?= htmlspecialchars($user['remarks']) ?></p> 
                </div>
                <div>
                    <p><strong>Damages Noted:</strong></p>
                    <p class="ms-3"><?= htmlspecialchars($user['damages_noted']) ?></p> 
                </div>
            </div>
        </div>
        <div class="form-section mt-4">
            <div class="slider-container">
                <div class="slider">
                    <?php
                    $vehicleImages = [
                        'front_image' => $user['front_image'],
                        'back_image' => $user['back_image'],
                        'left_image' => $user['left_image'],
                        'right_image' => $user['right_image'],
                        'top_image' => $user['top_image']
                    ];
                    
                    foreach ($vehicleImages as $key => $image) :
                        if (!empty($image)) : ?>
                            <img src="<?= htmlspecialchars($image) ?>" alt="<?= ucfirst(str_replace('_', ' ', $key)) ?>" onclick="openModal('<?= htmlspecialchars($image) ?>')" class="update-image">
                        <?php endif;
                    endforeach; ?>
                </div>
            </div>
        </div>
        <div class="vehicle-info mt-4">
            <h5 class="mb-3">Vehicle Information</h5>
            <div class="row">
                <?php foreach ($fields as $field) : ?>
                    <div class="col-md-4 mb-2">
                        <div class="border p-2 rounded">
                            <p><strong><?= ucwords(str_replace('_', ' ', $field)) ?>:</strong> <?= $user[$field] === 'Yes' ? '<i class="fas fa-check-circle text-success"></i>' : '<i class="fas fa-times-circle text-danger"></i>' ?></p>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <div id="myModal" class="modal" onclick="closeModal()">
            <span class="close">&times;</span>
            <img class="modal-content" id="modalImg">
        </div>

        <h4 class="mb-3">Job Information List</h4>
        <div class="table-responsive">
            <table class="table table-bordered table-striped">
                <thead class="thead-dark">
                    <tr>
                        <th>Title</th>
                        <th>Description</th>
                        <th>Images</th>
                        <th>Video</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // Fetch jobs for the specific user
                    $job_stmt = $pdo->prepare("SELECT * FROM jobs WHERE user_id = :user_id ORDER BY created_at DESC");
                    $job_stmt->execute([':user_id' => $user['id']]);
                    $jobs = $job_stmt->fetchAll(PDO::FETCH_ASSOC);

                    // Check if there are any jobs to display
                    if ($jobs) {
                        foreach ($jobs as $row) {
                            echo "<tr>";
                            echo "<td>" . htmlspecialchars(strlen($row['title']) > 20 ? substr($row['title'], 0, 20) . '...' : $row['title']) . "</td>";
                            echo "<td>" . htmlspecialchars(strlen($row['description']) > 30 ? substr($row['description'], 0, 30) . '...' : $row['description']) . "</td>";

                            // Display images
                            echo "<td>";
                            if (!empty($row['images'])) {
                                $images = json_decode($row['images'], true);
                                if (is_array($images) && count($images) > 0) {
                                    echo '<img src="' . htmlspecialchars(trim($images[0])) . '" alt="Job Image" width="80" height="80" style="border-radius: 5px; margin-right: 5px;" class="job-image">';
                                    if (count($images) > 1) {
                                        echo '<img src="' . htmlspecialchars(trim($images[1])) . '" alt="Job Image" width="80" height="80" style="border-radius: 5px; margin-right: 5px;" class="job-image hidden-mobile">';
                                    }
                                    if (count($images) > 2) {
                                        echo '<img src="' . htmlspecialchars(trim($images[2])) . '" alt="Job Image" width="80" height="80" style="border-radius: 5px; margin-right: 5px;" class="job-image hidden-mobile">';
                                    }
                                }
                            }
                            echo "</td>";

                            // Display video buttons (if any)
                            echo "<td class='d-flex'>";
                            if (!empty($row['video_upload'])) {
                                echo "<button class='btn btn-primary btn-sm ms-2' onclick=\"openVideoModal('" . htmlspecialchars($row['video_upload']) . "')\" style='background-color: #007bff !important; color: white; border: 1px solid #ffffff00 !important;'>
                                          <i class='fas fa-play-circle'></i> View
                                      </button>";
                                echo "<a href='" . htmlspecialchars($row['video_upload']) . "' download class='btn btn-primary btn-sm ms-2' style='background-color: #28a745 !important; color: white; border: 1px solid #ffffff00 !important;'>
                                          <i class='fas fa-download'></i> Download
                                      </a>";
                            }

                            echo "</td>";

                            echo "</tr>";
                        }
                    } else {
                        // If no jobs found, display a message
                        echo "<tr><td colspan='4' class='text-center'>No jobs found</td></tr>";
                    }
                    ?>
                </tbody>
            </table>
        </div>


<!-- Customer's Signature Section -->
<div class="row mt-4">
    <div class="col-md-6 mb-4">
        <div class="card shadow-sm border-0" style="border-radius: 15px; overflow: hidden;">
            <div class="card-header bg-primary text-white" style="border-radius: 15px 15px 0 0;">
                <h5 class="mb-0">Customer's Signature</h5>
            </div>
            <div class="card-body p-0">
                <img src="<?= htmlspecialchars($user['customer_signature']) ?>" alt="Customer's Signature" class="img-fluid w-100" style="border-radius: 0 0 15px 15px;">
            </div>
        </div>
    </div>
</div>

    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const markers = <?php echo $markersJson; ?>;
    const markerList = document.getElementById('markerList');
    const svgOverlay = document.getElementById('svgOverlay');
    
    // Define the full descriptions for each marker type
    const markerTypes = {
        "S": "Scratch",
        "D": "Dent",
        "P": "Paint Defect",
        "C": "Crack",
        "R": "Rust",
        "B": "Bubble"
    };

    markers.forEach((marker, index) => {
        const markerNumber = index + 1;
        const markerTypeDescription = markerTypes[marker.note] || marker.note; // Get full description or use the original note

        // Create the circle element for the SVG overlay
        const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
        circle.setAttribute('cx', `${marker.x}%`);
        circle.setAttribute('cy', `${marker.y}%`);
        circle.setAttribute('r', 8);
        circle.setAttribute('fill', 'red');
        svgOverlay.appendChild(circle);

        // Create the text label for the marker number
        const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
        text.setAttribute('x', `${marker.x}%`);
        text.setAttribute('y', `${marker.y}%`);
        text.setAttribute('dy', -10);
        text.setAttribute('text-anchor', 'middle');
        text.setAttribute('font-size', '12');
        text.setAttribute('fill', 'black');
        text.textContent = markerNumber;
        svgOverlay.appendChild(text);

        // Create the list item for the marker with description
        const li = document.createElement('li');
        li.className = 'list-group-item d-flex justify-content-between align-items-center';
        li.innerHTML = `Marker ${markerNumber}: ${markerTypeDescription}`;
        markerList.appendChild(li);
    });
});
</script>

    <style>
        /* Hide additional images on mobile devices */
        @media (max-width: 767px) {
            .hidden-mobile {
                display: none;
            }
        }

        /* Show all images on larger screens */
        @media (min-width: 768px) {
            .hidden-mobile {
                display: inline-block;
            }
        }
    </style>
</body>
</html>
<?php
    }
}
?>