<?php
// ajax/get_customer_request_details.php
session_start();
require_once '../../config/database.php';
require_once '../../includes/app_helpers.php';

header('Content-Type: text/html; charset=utf-8');

if (!isset($_SESSION['customer_id']) || !isset($_GET['id'])) {
    echo '<div class="request-alert request-alert-danger">Invalid request.</div>';
    exit;
}

$database = new Database();
$db = $database->getConnection();
ensureAddressAndCallQueueTables($db);

$request_id = intval($_GET['id']);
$customer_id = $_SESSION['customer_id'];

// Get request details with all related information
$query = "SELECT 
            sr.*,
            b.name as brand_name,
            a.name as appliance_name,
            c.city_name,
            u.name as urgency_name,
            u.time_frame as urgency_time,
            j.status_name,
            j.color_code as status_color,
            loc.location_name,
            CONCAT(tech.first_name, ' ', tech.last_name) as technician_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 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 loc ON sr.location_id = loc.id
          LEFT JOIN service_assignments sa ON sr.id = sa.request_id AND sa.status IN ('assigned', 'en_route', 'on_site')
          LEFT JOIN technicians tech ON sa.technician_id = tech.id
          WHERE sr.id = :id AND sr.customer_id = :customer_id";

$stmt = $db->prepare($query);
$stmt->execute([
    ':id' => $request_id,
    ':customer_id' => $customer_id
]);

$request = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$request) {
    echo '<div class="request-alert request-alert-danger">Request not found.</div>';
    exit;
}

// Get status history
$history_query = "SELECT 
                    rsh.*,
                    js.status_name,
                    js.color_code
                  FROM request_status_history rsh
                  JOIN job_statuses js ON rsh.job_status_id = js.id
                  WHERE rsh.request_id = :request_id
                  ORDER BY rsh.changed_at DESC";

$history_stmt = $db->prepare($history_query);
$history_stmt->execute([':request_id' => $request_id]);
$history = $history_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get customer-visible updates from CSR/Admin notes
$updates_query = "SELECT rn.*, CONCAT(cu.first_name, ' ', cu.last_name) AS csr_name
                  FROM request_notes rn
                  LEFT JOIN csr_users cu ON rn.csr_id = cu.id
                  WHERE rn.request_id = :request_id
                    AND rn.note_type = 'customer'
                  ORDER BY rn.created_at DESC";
$updates_stmt = $db->prepare($updates_query);
$updates_stmt->execute([':request_id' => $request_id]);
$customer_updates = $updates_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get request images
$images_query = "SELECT * FROM request_images WHERE request_id = :request_id ORDER BY uploaded_at ASC";
$images_stmt = $db->prepare($images_query);
$images_stmt->execute([':request_id' => $request_id]);
$images = $images_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get assignment details if any
$assignment_query = "SELECT 
                        sa.*,
                        tech.first_name,
                        tech.last_name,
                        tech.phone_number,
                        tech.email
                      FROM service_assignments sa
                      JOIN technicians tech ON sa.technician_id = tech.id
                      WHERE sa.request_id = :request_id
                      ORDER BY sa.assigned_at DESC
                      LIMIT 1";

$assignment_stmt = $db->prepare($assignment_query);
$assignment_stmt->execute([':request_id' => $request_id]);
$assignment = $assignment_stmt->fetch(PDO::FETCH_ASSOC);

function safeVal($array, $key, $default = '') {
    return isset($array[$key]) && $array[$key] !== '' && $array[$key] !== null ? $array[$key] : $default;
}

function formatDateTimeSafe($date, $format = 'M d, Y h:i A') {
    if (empty($date)) return 'Date not available';
    return date($format, strtotime($date));
}

function buildImageUrl($imagePath) {
    $imagePath = trim((string)$imagePath);

    if ($imagePath === '') {
        return '';
    }

    $imagePath = str_replace('\\', '/', $imagePath);
    $imagePath = ltrim($imagePath, '/');

    // If database already saved uploads/filename.jpg
    if (strpos($imagePath, 'uploads/') === 0) {
        return '../../' . implode('/', array_map('rawurlencode', explode('/', $imagePath)));
    }

    // If database saved request_images/filename.jpg
    if (strpos($imagePath, 'request_images/') === 0) {
        return '../../uploads/' . implode('/', array_map('rawurlencode', explode('/', $imagePath)));
    }

    // If database saved only filename.jpg
    return '../../uploads/request_images/' . rawurlencode(basename($imagePath));
}

$statusColor = safeVal($request, 'status_color', '#16a34a');
$statusBgColor = $statusColor . '24';
?>

<style>
.request-details-wrap {
    color: #ffffff;
}

.request-details-wrap * {
    box-sizing: border-box;
}

.request-status-banner {
    background: rgba(8, 20, 48, 0.45);
    border: 1px solid rgba(96, 165, 250, 0.24);
    border-left: 4px solid <?php echo htmlspecialchars($statusColor); ?>;
    border-radius: 14px;
    padding: 14px 16px;
    margin-bottom: 14px;
}

.request-status-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    flex-wrap: wrap;
}

.request-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 5px 11px;
    border-radius: 999px;
    font-size: 12px;
    font-weight: 800;
    color: #ffffff;
    background: <?php echo htmlspecialchars($statusColor); ?>;
    border: 1px solid rgba(255,255,255,0.14);
}

.request-muted {
    color: #d7e7ff !important;
    font-size: 12px;
}

.request-section {
    background: rgba(8, 20, 48, 0.42);
    border: 1px solid rgba(96, 165, 250, 0.24);
    border-radius: 14px;
    margin-bottom: 14px;
    overflow: hidden;
}

.request-section-header {
    background: rgba(56, 189, 248, 0.10);
    border-bottom: 1px solid rgba(96, 165, 250, 0.24);
    padding: 12px 16px;
}

.request-section-header h6 {
    color: #ffffff !important;
    font-weight: 800;
    margin: 0;
    font-size: 15px;
}

.request-section-header i {
    color: #dff7ff !important;
}

.request-section-body {
    padding: 16px;
}

.request-label {
    color: #d7e7ff !important;
    font-size: 12px;
    margin-bottom: 4px;
    display: block;
}

.request-value {
    color: #ffffff !important;
    font-size: 14px;
    margin-bottom: 0;
}

.request-value-bold {
    color: #ffffff !important;
    font-weight: 800;
    font-size: 15px;
    margin-bottom: 0;
}

.request-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 14px;
}

.request-grid-3 {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 14px;
}

.request-pill-warning {
    display: inline-flex;
    padding: 4px 8px;
    border-radius: 999px;
    background: #f59e0b;
    color: #111827 !important;
    font-size: 11px;
    font-weight: 800;
    margin-left: 5px;
}

.request-pill-info {
    display: inline-flex;
    padding: 5px 10px;
    border-radius: 999px;
    background: rgba(56, 189, 248, 0.18);
    color: #dff7ff !important;
    font-size: 12px;
    font-weight: 700;
    border: 1px solid rgba(56, 189, 248, 0.28);
}

.request-image-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(135px, 1fr));
    gap: 12px;
}

.request-image-card {
    background: rgba(56, 189, 248, 0.10);
    border: 1px solid rgba(56, 189, 248, 0.25);
    border-radius: 12px;
    overflow: hidden;
    padding: 8px;
}

.request-image-card img {
    width: 100%;
    height: 125px;
    object-fit: cover;
    border-radius: 10px;
    cursor: pointer;
    display: block;
    background: rgba(255,255,255,0.05);
}

.request-image-name {
    color: #d7e7ff !important;
    font-size: 12px;
    display: block;
    margin-top: 7px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.request-image-error {
    color: #fecaca !important;
    background: rgba(127, 29, 29, 0.35);
    border: 1px solid rgba(248, 113, 113, 0.35);
    border-radius: 10px;
    padding: 10px;
    font-size: 12px;
    display: none;
    margin-top: 8px;
}

.request-tech-card {
    display: flex;
    align-items: center;
    gap: 14px;
}

.request-tech-icon {
    width: 48px;
    height: 48px;
    background: rgba(56, 189, 248, 0.14);
    border: 1px solid rgba(56, 189, 248, 0.32);
    border-radius: 999px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #dff7ff;
    flex-shrink: 0;
}

.request-history-list {
    display: flex;
    flex-direction: column;
    gap: 0;
}

.request-history-item {
    padding: 13px 16px;
    border-bottom: 1px solid rgba(96, 165, 250, 0.18);
    background: rgba(8, 20, 48, 0.25);
}

.request-history-item:last-child {
    border-bottom: none;
}

.request-history-row {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 10px;
}

.request-action-row {
    display: flex;
    gap: 10px;
    margin: 14px 0;
}

.request-action-row .btn {
    border-radius: 10px;
    font-weight: 700;
}

.request-print-btn {
    background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%) !important;
    border: none !important;
    color: #ffffff !important;
}

.request-cancel-btn {
    border: 1px solid rgba(248, 113, 113, 0.45) !important;
    color: #fecaca !important;
    background: rgba(127, 29, 29, 0.30) !important;
}

.request-alert {
    padding: 13px 15px;
    border-radius: 12px;
    margin: 14px;
    font-weight: 700;
}

.request-alert-danger {
    background: rgba(127, 29, 29, 0.35);
    color: #fecaca;
    border: 1px solid rgba(248, 113, 113, 0.35);
}

.request-update-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.request-update-item {
    background: rgba(56, 189, 248, 0.10);
    border: 1px solid rgba(56, 189, 248, 0.24);
    border-radius: 12px;
    padding: 12px 14px;
}

.request-update-meta {
    display: flex;
    justify-content: space-between;
    gap: 10px;
    flex-wrap: wrap;
    margin-bottom: 6px;
}

@media (max-width: 576px) {
    .request-grid,
    .request-grid-3 {
        grid-template-columns: 1fr;
    }

    .request-status-row,
    .request-history-row {
        align-items: flex-start;
        flex-direction: column;
    }

    .request-image-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }

    .request-action-row {
        flex-direction: column;
    }
}
</style>

<div class="request-details-wrap">
    <div class="request-status-banner" style="background-color: <?php echo htmlspecialchars($statusBgColor); ?>;">
        <div class="request-status-row">
            <div>
                <span class="request-badge">
                    <?php echo htmlspecialchars(safeVal($request, 'status_name', 'Unknown Status')); ?>
                </span>
                <span class="request-muted ms-2">
                    Request #<?php echo htmlspecialchars(safeVal($request, 'request_number', 'N/A')); ?>
                </span>
            </div>

            <span class="request-muted">
                <i class="far fa-calendar-alt me-1"></i>
                <?php echo formatDateTimeSafe(safeVal($request, 'requested_at')); ?>
            </span>
        </div>
    </div>

    <div class="request-section">
        <div class="request-section-header">
            <h6><i class="fas fa-tools me-2"></i>Appliance Information</h6>
        </div>

        <div class="request-section-body">
            <div class="request-grid">
                <div>
                    <label class="request-label">Brand</label>
                    <p class="request-value-bold">
                        <?php 
                        if (!empty($request['brand_name'])) {
                            echo htmlspecialchars($request['brand_name']);
                        } elseif (!empty($request['manual_brand'])) {
                            echo htmlspecialchars($request['manual_brand']) . ' <span class="request-pill-warning">Manual Entry</span>';
                        } else {
                            echo '<span class="request-muted">Not specified</span>';
                        }
                        ?>
                    </p>
                </div>

                <div>
                    <label class="request-label">Appliance Type</label>
                    <p class="request-value-bold">
                        <?php 
                        if (!empty($request['appliance_name'])) {
                            echo htmlspecialchars($request['appliance_name']);
                        } elseif (!empty($request['manual_appliance_type'])) {
                            echo htmlspecialchars($request['manual_appliance_type']) . ' <span class="request-pill-warning">Manual Entry</span>';
                        } else {
                            echo '<span class="request-muted">Not specified</span>';
                        }
                        ?>
                    </p>
                </div>

                <div>
                    <label class="request-label">Model Number</label>
                    <p class="request-value"><?php echo htmlspecialchars($request['model_number'] ?: 'Not provided'); ?></p>
                </div>

                <div>
                    <label class="request-label">Serial Number</label>
                    <p class="request-value"><?php echo htmlspecialchars($request['serial_number'] ?: 'Not provided'); ?></p>
                </div>
            </div>
        </div>
    </div>

    <div class="request-section">
        <div class="request-section-header">
            <h6><i class="fas fa-user me-2"></i>Contact Information</h6>
        </div>

        <div class="request-section-body">
            <div class="request-grid">
                <div>
                    <label class="request-label">Full Name</label>
                    <p class="request-value-bold"><?php echo htmlspecialchars($request['full_name'] ?? 'N/A'); ?></p>
                </div>

                <div>
                    <label class="request-label">Phone Number</label>
                    <p class="request-value"><?php echo htmlspecialchars($request['phone_number'] ?? 'N/A'); ?></p>
                </div>
            </div>
        </div>
    </div>

    <div class="request-section">
        <div class="request-section-header">
            <h6><i class="fas fa-map-marker-alt me-2"></i>Service Address</h6>
        </div>

        <div class="request-section-body">
            <p class="request-value mb-1"><?php echo nl2br(htmlspecialchars($request['service_address'] ?? '')); ?></p>

            <?php if (!empty($request['service_address_2'])): ?>
                <p class="request-value mb-1"><?php echo nl2br(htmlspecialchars($request['service_address_2'])); ?></p>
            <?php endif; ?>

            <p class="request-value mb-0">
                <?php echo htmlspecialchars($request['city_name'] ?? 'Unknown City'); ?>,
                <?php echo htmlspecialchars($request['state'] ?? ''); ?>
                <?php echo htmlspecialchars($request['zip_code'] ?? 'No ZIP'); ?>
            </p>
            <?php if (!empty($request['region'])): ?>
                <p class="request-muted mb-0 mt-1">Region: <?php echo htmlspecialchars($request['region']); ?></p>
            <?php endif; ?>

            <?php if (!empty($request['location_name'])): ?>
                <p class="request-muted mb-0 mt-1">Service Area: <?php echo htmlspecialchars($request['location_name']); ?></p>
            <?php endif; ?>

            <?php if (!empty($request['landmark'])): ?>
                <div class="mt-2">
                    <span class="request-pill-info">
                        <i class="fas fa-flag me-1"></i>
                        Landmark: <?php echo htmlspecialchars($request['landmark']); ?>
                    </span>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="request-section">
        <div class="request-section-header">
            <h6><i class="fas fa-clock me-2"></i>Service Details</h6>
        </div>

        <div class="request-section-body">
            <div class="request-grid-3">
                <div>
                    <label class="request-label">Urgency Level</label>
                    <p class="request-value-bold"><?php echo htmlspecialchars($request['urgency_name'] ?? 'Not specified'); ?></p>
                    <small class="request-muted"><?php echo htmlspecialchars($request['urgency_time'] ?? ''); ?></small>
                </div>

                <div>
                    <label class="request-label">Preferred Date</label>
                    <p class="request-value-bold">
                        <?php 
                        if (!empty($request['preferred_date'])) {
                            echo date('M d, Y', strtotime($request['preferred_date']));
                        } else {
                            echo '<span class="request-muted">Not specified</span>';
                        }
                        ?>
                    </p>
                </div>

                <div>
                    <label class="request-label">Preferred Time</label>
                    <p class="request-value-bold">
                        <?php 
                        if (!empty($request['preferred_time'])) {
                            echo htmlspecialchars($request['preferred_time']);
                        } elseif (!empty($request['preferred_time_slot'])) {
                            echo htmlspecialchars($request['preferred_time_slot']);
                        } else {
                            echo '<span class="request-muted">Not specified</span>';
                        }
                        ?>
                    </p>
                </div>
            </div>

            <div class="mt-3">
                <label class="request-label">Issue Description</label>
                <p class="request-value"><?php echo nl2br(htmlspecialchars($request['issue_description'] ?? '')); ?></p>
            </div>

            <?php if (!empty($request['special_request'])): ?>
                <div class="mt-3">
                    <label class="request-label">Special Request</label>
                    <p class="request-value"><?php echo nl2br(htmlspecialchars($request['special_request'])); ?></p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <?php if (!empty($images)): ?>
        <div class="request-section">
            <div class="request-section-header">
                <h6><i class="fas fa-camera me-2"></i>Uploaded Photos (<?php echo count($images); ?>)</h6>
            </div>

            <div class="request-section-body">
                <div class="request-image-grid">
                    <?php foreach ($images as $image): ?>
                        <?php
                            $imagePath = $image['image_path'] ?? '';
                            $imageUrl = buildImageUrl($imagePath);
                            $imageName = $image['original_name'] ?? basename($imagePath) ?: 'Image';
                        ?>

                        <div class="request-image-card">
                            <img src="<?php echo htmlspecialchars($imageUrl); ?>"
                                 alt="<?php echo htmlspecialchars($imageName); ?>"
                                 onclick="zoomImage('<?php echo htmlspecialchars($imageUrl, ENT_QUOTES); ?>')"
                                 onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">

                            <div class="request-image-error">
                                Image not found:<br>
                                <?php echo htmlspecialchars($imageName); ?>
                            </div>

                            <small class="request-image-name">
                                <?php echo htmlspecialchars($imageName); ?>
                            </small>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <?php if ($assignment): ?>
        <div class="request-section">
            <div class="request-section-header">
                <h6><i class="fas fa-user-cog me-2"></i>Assigned Technician</h6>
            </div>

            <div class="request-section-body">
                <div class="request-tech-card">
                    <div class="request-tech-icon">
                        <i class="fas fa-user"></i>
                    </div>

                    <div>
                        <h6 class="request-value-bold mb-1">
                            <?php echo htmlspecialchars(trim(($assignment['first_name'] ?? '') . ' ' . ($assignment['last_name'] ?? ''))); ?>
                        </h6>

                        <p class="request-value mb-1">
                            <i class="fas fa-phone me-1"></i>
                            <?php echo htmlspecialchars($assignment['phone_number'] ?? 'N/A'); ?><br>
                            <i class="fas fa-envelope me-1"></i>
                            <?php echo htmlspecialchars($assignment['email'] ?? 'N/A'); ?>
                        </p>

                        <?php if (!empty($assignment['estimated_arrival_time'])): ?>
                            <span class="request-pill-info">
                                <i class="far fa-clock me-1"></i>
                                Est. Arrival: <?php echo date('M d, Y h:i A', strtotime($assignment['estimated_arrival_time'])); ?>
                            </span>
                        <?php endif; ?>
                    </div>
                </div>

                <?php if (!empty($assignment['technician_notes'])): ?>
                    <div class="mt-3 request-section" style="margin-bottom: 0;">
                        <div class="request-section-body">
                            <small class="request-value">
                                <strong>Technician Notes:</strong><br>
                                <?php echo nl2br(htmlspecialchars($assignment['technician_notes'])); ?>
                            </small>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>

    <?php if (!empty($customer_updates)): ?>
        <div class="request-section">
            <div class="request-section-header">
                <h6><i class="fas fa-bell me-2"></i>Customer Updates</h6>
            </div>

            <div class="request-section-body">
                <div class="request-update-list">
                    <?php foreach ($customer_updates as $update): ?>
                        <div class="request-update-item">
                            <div class="request-update-meta">
                                <strong class="request-value-bold">
                                    <?php echo htmlspecialchars(!empty($update['csr_name']) ? $update['csr_name'] : 'CSR Team'); ?>
                                </strong>
                                <small class="request-muted">
                                    <i class="far fa-clock me-1"></i>
                                    <?php echo formatDateTimeSafe($update['created_at']); ?>
                                </small>
                            </div>
                            <p class="request-value mb-0"><?php echo nl2br(htmlspecialchars($update['note_content'])); ?></p>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <?php if (!empty($history)): ?>
        <div class="request-section">
            <div class="request-section-header">
                <h6><i class="fas fa-history me-2"></i>Status History</h6>
            </div>

            <div class="request-history-list">
                <?php foreach ($history as $entry): ?>
                    <?php $historyColor = safeVal($entry, 'color_code', '#6c757d'); ?>

                    <div class="request-history-item">
                        <div class="request-history-row">
                            <div>
                                <span class="request-badge" style="background-color: <?php echo htmlspecialchars($historyColor); ?>;">
                                    <?php echo htmlspecialchars(safeVal($entry, 'status_name', 'Unknown')); ?>
                                </span>

                                <?php if (!empty($entry['notes'])): ?>
                                    <small class="request-muted d-block mt-2">
                                        <?php echo nl2br(htmlspecialchars($entry['notes'])); ?>
                                    </small>
                                <?php endif; ?>
                            </div>

                            <small class="request-muted">
                                <i class="far fa-clock me-1"></i>
                                <?php echo formatDateTimeSafe(safeVal($entry, 'changed_at')); ?>
                            </small>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endif; ?>

    <div class="request-action-row">
        <?php if (($request['job_status_id'] ?? 0) == 1): ?>
            <button class="btn request-cancel-btn flex-fill" onclick="cancelRequest(<?php echo $request['id']; ?>)">
                <i class="fas fa-times me-2"></i>Cancel Request
            </button>
        <?php endif; ?>

        <button class="btn request-print-btn flex-fill" onclick="createCallRequest(<?php echo $request['id']; ?>)">
            <i class="fas fa-phone-volume me-2"></i>Request a Call
        </button>

        <button class="btn request-print-btn flex-fill" onclick="window.print()">
            <i class="fas fa-print me-2"></i>Print Details
        </button>
    </div>
</div>

<script>
function createCallRequest(requestId) {
    if (!confirm('Send a call request to the CSR team?')) return;
    $.ajax({
        url: 'ajax/create_call_request.php',
        method: 'POST',
        data: { request_id: requestId },
        dataType: 'json',
        success: function(response) {
            alert(response.message || (response.success ? 'Call request sent.' : 'Unable to send call request.'));
            if (response.success && response.room_url) {
                window.location.href = response.room_url;
            }
        },
        error: function() {
            alert('Error sending call request.');
        }
    });
}

function cancelRequest(requestId) {
    if (confirm('Are you sure you want to cancel this request?')) {
        $.ajax({
            url: 'ajax/cancel_request.php',
            method: 'POST',
            data: { id: requestId },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    alert('Request cancelled successfully');
                    location.reload();
                } else {
                    alert(response.message || 'Error cancelling request');
                }
            },
            error: function() {
                alert('Error cancelling request');
            }
        });
    }
}
</script>