<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

if (!isset($_SESSION['csr_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

require_once '../../config/database.php';
require_once '../../includes/app_helpers.php';

function vq_h($value): string {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function vq_row(string $label, $value): string {
    $display = trim((string)$value) !== '' ? vq_h($value) : '—';
    return '<div class="vq-detail-row"><span>' . vq_h($label) . '</span><span>' . $display . '</span></div>';
}

try {
    $requestId = (int)($_GET['request_id'] ?? 0);
    if ($requestId <= 0) {
        throw new Exception('Missing request ID.');
    }

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

    $stmt = $db->prepare("SELECT
            sr.*,
            COALESCE(b.name, sr.manual_brand) AS brand_name,
            COALESCE(at.name, sr.manual_appliance_type) AS appliance_name,
            COALESCE(sa.city, c.city_name) AS city_name,
            COALESCE(sa.region, c.region, sr.region) AS region_name,
            js.status_name,
            CONCAT(cu.first_name, ' ', cu.last_name) AS reviewed_by_name
        FROM service_requests sr
        LEFT JOIN brands b ON b.id = sr.brand_id
        LEFT JOIN appliance_types at ON at.id = sr.appliance_type_id
        LEFT JOIN cities c ON c.id = sr.city_id
        LEFT JOIN service_areas sa ON sa.zip_code = sr.zip_code AND sa.is_active = 1
        LEFT JOIN job_statuses js ON js.id = sr.job_status_id
        LEFT JOIN csr_users cu ON cu.id = sr.verification_reviewed_by
        WHERE sr.id = :id
          AND (sr.source_system = 'php_cx' OR sr.ticket_source IN ('cx_online','customer'))
        LIMIT 1");
    $stmt->execute([':id' => $requestId]);
    $r = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$r) {
        throw new Exception('Request not found.');
    }

    $images = [];
    try {
        $imgStmt = $db->prepare("SELECT image_path, original_name FROM request_images WHERE request_id = :id ORDER BY id ASC");
        $imgStmt->execute([':id' => $requestId]);
        $images = $imgStmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {}

    $status = $r['verification_status'] ?: 'approved';
    $html = '<div class="mb-3 d-flex gap-2 flex-wrap">';
    $html .= '<span class="vq-status ' . vq_h($status) . '"><i class="fas fa-shield-alt"></i>' . vq_h(ucwords($status)) . '</span>';
    $html .= '<span class="badge bg-info">' . vq_h($r['request_number']) . '</span>';
    $html .= '</div>';

    $html .= '<div class="vq-detail-grid">';
    $html .= '<div class="vq-detail-card"><h6><i class="fas fa-user me-1"></i>Customer Information</h6>';
    $html .= vq_row('Ticket No', $r['request_number']);
    $html .= vq_row('Source', $r['origin_type'] ?: 'CX Submission');
    $html .= vq_row('Name', $r['full_name']);
    $html .= vq_row('Primary Phone', $r['phone_number']);
    $html .= vq_row('Secondary Phone', $r['secondary_phone']);
    $html .= vq_row('Email', $r['customer_email']);
    $html .= vq_row('Address', $r['service_address']);
    $html .= vq_row('Address Note', $r['service_address_2'] ?: $r['landmark']);
    $html .= vq_row('City', $r['city_name']);
    $html .= vq_row('State', $r['state']);
    $html .= vq_row('ZIP Code', $r['zip_code']);
    $html .= vq_row('Region', $r['region_name']);
    $html .= '</div>';

    $html .= '<div class="vq-detail-card"><h6><i class="fas fa-box-open me-1"></i>Product Information</h6>';
    $html .= vq_row('Model', $r['model_number']);
    $html .= vq_row('Serial', $r['serial_number']);
    $html .= vq_row('Model Version', $r['product_model_version']);
    $html .= vq_row('Brand', $r['brand_name']);
    $html .= vq_row('Product Category', $r['appliance_name']);
    $html .= vq_row('Purchase Date', $r['purchase_date']);
    $html .= vq_row('Warranty Type', $r['warranty_type']);
    $html .= vq_row('CX Preferred Date', $r['preferred_date']);
    $html .= vq_row('Submitted At', $r['requested_at']);
    $html .= '</div>';

    $html .= '<div class="vq-detail-card"><h6><i class="fas fa-clipboard me-1"></i>Service Information</h6>';
    $html .= vq_row('Problem Description', $r['issue_description']);
    $html .= vq_row('Special Request', $r['special_request']);
    $html .= vq_row('System Status', $r['status_name']);
    $html .= '</div>';

    $html .= '<div class="vq-detail-card"><h6><i class="fas fa-user-check me-1"></i>Verification</h6>';
    $html .= vq_row('Review Status', ucwords($status));
    $html .= vq_row('Reviewed By', $r['reviewed_by_name']);
    $html .= vq_row('Reviewed At', $r['verification_reviewed_at']);
    $html .= vq_row('Reject Reason', $r['verification_reject_reason']);
    $html .= vq_row('Review Notes', $r['verification_notes']);
    $html .= '</div>';
    $html .= '</div>';

    $html .= '<div class="vq-detail-card mt-3"><h6><i class="fas fa-images me-1"></i>Uploaded Images</h6>';
    if (!$images) {
        $html .= '<p class="text-muted mb-0">No images uploaded.</p>';
    } else {
        $html .= '<div class="vq-images">';
        foreach ($images as $img) {
            $src = '../' . ltrim((string)$img['image_path'], '/');
            $html .= '<a href="' . vq_h($src) . '" target="_blank"><img src="' . vq_h($src) . '" alt="' . vq_h($img['original_name'] ?? 'Request image') . '"></a>';
        }
        $html .= '</div>';
    }
    $html .= '</div>';

    echo json_encode(['success' => true, 'html' => $html]);
} catch (Throwable $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
