<?php
require_once '../auth.php';
ensureAdminAjaxAuth();
// ajax/get_request_details.php
require_once '../../config/database.php';

header('Content-Type: application/json');



if(!isset($_GET['id'])) {
    echo json_encode(['success' => false, 'message' => 'Request ID required']);
    exit;
}

$id = intval($_GET['id']);

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Get request details
    $query = "SELECT 
                sr.*,
                b.name as brand_name,
                a.name as appliance_name,
                COALESCE(sz.city, l.location_name, c.city_name) AS city_name,
                COALESCE(sz.region, c.region, c.city_name) AS service_region_name,
                u.name as urgency_name,
                u.time_frame as urgency_time,
                j.status_name,
                j.color_code,
                l.location_name
              FROM service_requests sr
              LEFT JOIN brands b ON sr.brand_id = b.id
              LEFT JOIN appliance_types a ON sr.appliance_type_id = a.id
              LEFT JOIN cities c ON sr.city_id = c.id
              LEFT JOIN service_areas sz ON sz.zip_code = sr.zip_code AND sz.is_active = 1
              LEFT JOIN urgency_levels u ON sr.urgency_level_id = u.id
              LEFT JOIN job_statuses j ON sr.job_status_id = j.id
              LEFT JOIN locations l ON sr.location_id = l.id
              WHERE sr.id = :id";
    
    $stmt = $db->prepare($query);
    $stmt->execute([':id' => $id]);
    $request = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if(!$request) {
        echo json_encode(['success' => false, 'message' => 'Request not found']);
        exit;
    }
    
    // Get images for this request
    $images_query = "SELECT * FROM request_images WHERE request_id = :id ORDER BY uploaded_at ASC";
    $images_stmt = $db->prepare($images_query);
    $images_stmt->execute([':id' => $id]);
    $images = $images_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get status history
    $history_query = "SELECT 
                        rsh.*,
                        j.status_name,
                        j.color_code
                      FROM request_status_history rsh
                      JOIN job_statuses j ON rsh.job_status_id = j.id
                      WHERE rsh.request_id = :id
                      ORDER BY rsh.changed_at DESC";
    
    $history_stmt = $db->prepare($history_query);
    $history_stmt->execute([':id' => $id]);
    $history = $history_stmt->fetchAll(PDO::FETCH_ASSOC);


    
    // Generate HTML
    ob_start();
    ?>
    
    <style>
        .image-gallery {
            margin-top: 15px;
        }
        .image-gallery .gallery-item {
            position: relative;
            margin-bottom: 15px;
            cursor: pointer;
        }
        .image-gallery .gallery-item img {
            width: 100%;
            height: 150px;
            object-fit: cover;
            border-radius: 8px;
            transition: transform 0.3s;
        }
        .image-gallery .gallery-item img:hover {
            transform: scale(1.05);
        }
        .image-gallery .gallery-item .overlay {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 5px;
            font-size: 11px;
            text-align: center;
            border-radius: 0 0 8px 8px;
            opacity: 0;
            transition: opacity 0.3s;
        }
        .image-gallery .gallery-item:hover .overlay {
            opacity: 1;
        }
        .no-images {
            text-align: center;
            padding: 30px;
            background: #f8f9fa;
            border-radius: 8px;
            color: #7f8c8d;
        }
        /* Lightbox styles */
        .lightbox {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.9);
            z-index: 9999;
            cursor: pointer;
        }
        .lightbox.active {
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .lightbox img {
            max-width: 90%;
            max-height: 90%;
            object-fit: contain;
        }
        .lightbox .close-lightbox {
            position: absolute;
            top: 20px;
            right: 40px;
            color: white;
            font-size: 40px;
            cursor: pointer;
        }
        .lightbox .prev, .lightbox .next {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            color: white;
            font-size: 40px;
            cursor: pointer;
            padding: 20px;
            background: rgba(0,0,0,0.5);
        }
        .lightbox .prev {
            left: 20px;
        }
        .lightbox .next {
            right: 20px;
        }
        .lightbox .image-counter {
            position: absolute;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            color: white;
            background: rgba(0,0,0,0.7);
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 14px;
        }
        .image-info {
            font-size: 12px;
            color: #6c757d;
            margin-top: 5px;
            text-align: center;
        }
    </style>
    
    <div class="row">
        <div class="col-md-6">
            <div class="info-group">
                <div class="info-label">Request Number</div>
                <div class="info-value">
                    <i class="fas fa-hashtag"></i>
                    <?php echo htmlspecialchars($request['request_number']); ?>
                </div>
            </div>
            
            <div class="info-group">
                <div class="info-label">Customer Information</div>
                <div class="info-value">
                    <i class="fas fa-user"></i>
                    <?php echo htmlspecialchars($request['full_name']); ?><br>
                    <i class="fas fa-phone mt-2"></i>
                    <?php echo htmlspecialchars($request['phone_number']); ?>
                </div>
            </div>
            
            <div class="info-group">
                <div class="info-label">Service Address</div>
                <div class="info-value">
                    <i class="fas fa-map-marker-alt"></i>
                    <?php echo nl2br(htmlspecialchars($request['service_address'])); ?><br>
                    <strong><?php echo htmlspecialchars($request['city_name']); ?></strong> - 
                    <?php echo htmlspecialchars($request['zip_code']); ?><br>
                    <?php if($request['landmark']): ?>
                        <i class="fas fa-flag mt-2"></i>
                        Landmark: <?php echo htmlspecialchars($request['landmark']); ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="info-group">
                <div class="info-label">Appliance Details</div>
                <div class="info-value">
                    <i class="fas fa-tools"></i>
                    <?php echo htmlspecialchars($request['appliance_name']); ?><br>
                    <i class="fas fa-tag mt-2"></i>
                    Brand: <?php echo htmlspecialchars($request['brand_name']); ?><br>
                    <?php if($request['model_number']): ?>
                        Model: <?php echo htmlspecialchars($request['model_number']); ?><br>
                    <?php endif; ?>
                    <?php if($request['serial_number']): ?>
                        Serial: <?php echo htmlspecialchars($request['serial_number']); ?>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="info-group">
                <div class="info-label">Service Details</div>
                <div class="info-value">
                    <i class="fas fa-clock"></i>
                    Urgency: <?php echo htmlspecialchars($request['urgency_name']); ?> 
                    (<?php echo htmlspecialchars($request['urgency_time']); ?>)<br>
                    <i class="fas fa-calendar-alt mt-2"></i>
                    Requested: <?php echo date('F d, Y h:i A', strtotime($request['requested_at'])); ?><br>
                    <i class="fas fa-tag mt-2"></i>
                    Status: <span class="status-badge" style="background-color: <?php echo $request['color_code']; ?>">
                        <?php echo $request['status_name']; ?>
                    </span>
                </div>
            </div>
            
            <div class="info-group">
                <div class="info-label">Issue Description</div>
                <div class="info-value">
                    <i class="fas fa-exclamation-triangle"></i>
                    <?php echo nl2br(htmlspecialchars($request['issue_description'])); ?>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Images Section -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="info-label">
                <i class="fas fa-images"></i> Attached Images
                <?php if(count($images) > 0): ?>
                    <span class="badge bg-secondary ms-2"><?php echo count($images); ?> image(s)</span>
                <?php endif; ?>
            </div>
            <div class="image-gallery">
                <?php if(count($images) > 0): ?>
                    <div class="row">
                        <?php foreach($images as $index => $image): 
                            // Path to images in customer folder
                            // Since ajax file is in admin/ajax/, we need to go up 2 levels to reach root,
                            // then go into customer folder and then the image path
                            $image_path = '../' . $image['image_path'];
                            // echo $image_path;
                        ?>
                        <div class="col-md-4 col-sm-6 gallery-item" onclick="openLightbox(<?php echo $index; ?>)">
                            <img src="<?php echo $image_path; ?>" alt="<?php echo htmlspecialchars($image['original_name']); ?>" class="img-fluid"
                                 onerror="this.src='https://via.placeholder.com/300x200?text=Image+Not+Found'">
                            <div class="overlay">
                                <i class="fas fa-search-plus"></i> Click to enlarge
                            </div>
                            <?php if($image['original_name']): ?>
                            <div class="image-info">
                                <small><?php echo htmlspecialchars($image['original_name']); ?></small>
                            </div>
                            <?php endif; ?>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="no-images">
                        <i class="fas fa-image fa-3x mb-3 d-block"></i>
                        <p>No images attached to this request</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <?php if(!empty($history)): ?>
    <div class="row mt-4">
        <div class="col-12">
            <div class="info-label">Status History</div>
            <div class="history-list">
                <?php foreach($history as $h): ?>
                <div class="history-item">
                    <div class="d-flex justify-content-between">
                        <span class="history-status">
                            <span class="badge" style="background-color: <?php echo $h['color_code']; ?>">
                                <?php echo $h['status_name']; ?>
                            </span>
                        </span>
                        <span class="history-date">
                            <?php echo date('M d, Y h:i A', strtotime($h['changed_at'])); ?>
                        </span>
                    </div>
                    <?php if($h['notes']): ?>
                    <div class="history-note">
                        <i class="fas fa-comment"></i>
                        <?php echo htmlspecialchars($h['notes']); ?>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- Lightbox Modal -->
    <div id="lightbox" class="lightbox" onclick="closeLightbox()">
        <span class="close-lightbox" onclick="closeLightbox()">&times;</span>
        <span class="prev" onclick="event.stopPropagation(); changeImage(-1)">&#10094;</span>
        <span class="next" onclick="event.stopPropagation(); changeImage(1)">&#10095;</span>
        <img id="lightbox-img" src="" alt="">
        <div class="image-counter" id="image-counter"></div>
    </div>
    
    <script>
    // Store images data for lightbox
    const images = <?php echo json_encode($images); ?>;
    let currentImageIndex = 0;
    
    function openLightbox(index) {
        currentImageIndex = index;
        const lightbox = document.getElementById('lightbox');
        const img = document.getElementById('lightbox-img');
        const counter = document.getElementById('image-counter');
        
        // Path to images in customer folder
        let imgPath = '../' + images[currentImageIndex].image_path;
        
        img.src = imgPath;
        counter.textContent = (currentImageIndex + 1) + ' / ' + images.length;
        lightbox.classList.add('active');
    }
    
    function closeLightbox() {
        document.getElementById('lightbox').classList.remove('active');
    }
    
    function changeImage(direction) {
        currentImageIndex += direction;
        if (currentImageIndex < 0) currentImageIndex = images.length - 1;
        if (currentImageIndex >= images.length) currentImageIndex = 0;
        
        const img = document.getElementById('lightbox-img');
        const counter = document.getElementById('image-counter');
        
        let imgPath = '../../../customer/' + images[currentImageIndex].image_path;
        
        img.src = imgPath;
        counter.textContent = (currentImageIndex + 1) + ' / ' + images.length;
    }
    
    // Prevent lightbox from closing when clicking on navigation buttons
    document.querySelector('.prev')?.addEventListener('click', function(e) {
        e.stopPropagation();
    });
    document.querySelector('.next')?.addEventListener('click', function(e) {
        e.stopPropagation();
    });
    
    // Close lightbox with escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && document.getElementById('lightbox').classList.contains('active')) {
            closeLightbox();
        }
    });
    </script>
    
    <?php
    $html = ob_get_clean();
    
    echo json_encode([
        'success' => true,
        'html' => $html,
        'request' => $request,
        'images' => $images
    ]);
    
} catch(Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>