<?php
// csr_manager/verification_queue.php - Verification Queue for customer-submitted requests
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['csr_id'])) {
    header('Location: ../login.php');
    exit();
}

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

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

$title = 'Verification Queue';
$currentCsrId = (int)$_SESSION['csr_id'];

$search = trim((string)($_GET['search'] ?? ''));
$status = trim((string)($_GET['status'] ?? 'pending'));
if (!in_array($status, ['pending','approved','rejected','all'], true)) {
    $status = 'pending';
}

$where = ["(sr.source_system = 'php_cx' OR sr.ticket_source IN ('cx_online','customer'))"];
$params = [];

if ($status !== 'all') {
    $where[] = "COALESCE(sr.verification_status, 'approved') = :verification_status";
    $params[':verification_status'] = $status;
}

if ($search !== '') {
    $where[] = "(sr.request_number LIKE :search OR sr.full_name LIKE :search OR sr.phone_number LIKE :search OR sr.customer_email LIKE :search OR sr.zip_code LIKE :search)";
    $params[':search'] = '%' . $search . '%';
}

$whereSql = 'WHERE ' . implode(' AND ', $where);

$stmt = $db->prepare("
    SELECT
        sr.id,
        sr.request_number,
        sr.full_name,
        sr.phone_number,
        sr.customer_email,
        sr.zip_code,
        sr.state,
        sr.region,
        COALESCE(sa.city, c.city_name) AS city_name,
        COALESCE(b.name, sr.manual_brand, 'Unknown Brand') AS brand_name,
        COALESCE(at.name, sr.manual_appliance_type, 'Unknown Appliance') AS appliance_name,
        COALESCE(sr.verification_status, 'approved') AS verification_status,
        sr.verification_reject_reason,
        sr.requested_at,
        sr.last_updated_at
    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
    $whereSql
    ORDER BY
        CASE COALESCE(sr.verification_status, 'approved') WHEN 'pending' THEN 1 WHEN 'rejected' THEN 2 ELSE 3 END,
        sr.requested_at DESC
    LIMIT 200
");
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value, PDO::PARAM_STR);
}
$stmt->execute();
$requests = $stmt->fetchAll(PDO::FETCH_ASSOC);

$counts = ['pending' => 0, 'approved' => 0, 'rejected' => 0];
try {
    $countStmt = $db->query("SELECT COALESCE(verification_status, 'approved') AS status_key, COUNT(*) AS total
                            FROM service_requests
                            WHERE source_system = 'php_cx' OR ticket_source IN ('cx_online','customer')
                            GROUP BY COALESCE(verification_status, 'approved')");
    foreach ($countStmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $key = (string)$row['status_key'];
        if (isset($counts[$key])) {
            $counts[$key] = (int)$row['total'];
        }
    }
} catch (Throwable $e) {}

$rejectReasons = [
    'Incomplete details',
    'Invalid contact information',
    'Duplicate request',
    'Outside service area / wrong address',
    'Suspicious or troll request',
    'Customer requested cancellation',
    'Other'
];

ob_start();
?>
<style>
.verification-wrap { max-width: 1280px; margin: 0 auto; }
.verification-hero { display:flex; align-items:flex-start; justify-content:space-between; gap:16px; margin-bottom:18px; }
.verification-hero h2 { color:#fff; font-weight:900; margin:0; }
.verification-hero p { color:var(--cm-muted); margin:6px 0 0; }
.vq-stats { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:12px; margin-bottom:16px; }
.vq-stat { background:var(--cm-card); border:1px solid var(--cm-border); border-radius:16px; padding:16px; }
.vq-stat strong { display:block; font-size:1.8rem; font-weight:900; line-height:1; color:#fff; }
.vq-stat span { color:var(--cm-muted); font-weight:800; font-size:.78rem; text-transform:uppercase; letter-spacing:.05em; }
.vq-filters { background:var(--cm-card); border:1px solid var(--cm-border); border-radius:16px; padding:14px; margin-bottom:16px; display:flex; gap:10px; flex-wrap:wrap; align-items:end; }
.vq-table-card { background:var(--cm-card); border:1px solid var(--cm-border); border-radius:16px; overflow:hidden; }
.vq-table-card .table { margin:0; }
.vq-request-link { color:#dff7ff !important; font-weight:900; text-decoration:none; }
.vq-request-link:hover { text-decoration:underline; }
.vq-status { display:inline-flex; align-items:center; gap:6px; border-radius:999px; padding:6px 10px; font-size:.72rem; font-weight:900; }
.vq-status.pending { background:rgba(245,158,11,.18); color:#fde68a; }
.vq-status.approved { background:rgba(34,197,94,.18); color:#bbf7d0; }
.vq-status.rejected { background:rgba(239,68,68,.18); color:#fecaca; }
.vq-actions { display:flex; gap:7px; flex-wrap:wrap; }
.vq-empty { padding:48px 20px; text-align:center; color:var(--cm-muted); }
.vq-detail-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; }
.vq-detail-card { background:rgba(8,20,48,.42); border:1px solid rgba(96,165,250,.24); border-radius:14px; padding:14px; }
.vq-detail-card h6 { color:#fff; font-weight:900; margin-bottom:10px; border-bottom:1px solid rgba(96,165,250,.2); padding-bottom:8px; }
.vq-detail-row { display:grid; grid-template-columns:150px 1fr; gap:10px; margin-bottom:8px; font-size:.88rem; }
.vq-detail-row span:first-child { color:var(--cm-muted); font-weight:800; }
.vq-detail-row span:last-child { color:#fff; word-break:break-word; }
.vq-images { display:grid; grid-template-columns:repeat(auto-fill,minmax(130px,1fr)); gap:10px; }
.vq-images img { width:100%; height:110px; object-fit:cover; border-radius:12px; border:1px solid rgba(96,165,250,.24); }
@media(max-width:760px){ .vq-stats{grid-template-columns:1fr;} .vq-detail-grid{grid-template-columns:1fr;} .vq-detail-row{grid-template-columns:1fr;} }
</style>

<div class="verification-wrap">
    <div class="verification-hero">
        <div>
            <h2><i class="fas fa-shield-alt me-2 text-info"></i>Verification Queue</h2>
            <p>Review customer-submitted requests before they become normal tickets. Use this to avoid troll, duplicate, or incomplete requests.</p>
        </div>
        <a href="tickets.php" class="cm-btn"><i class="fas fa-clipboard-list"></i> Tickets</a>
    </div>

    <div class="vq-stats">
        <div class="vq-stat"><strong><?= (int)$counts['pending'] ?></strong><span>Pending Review</span></div>
        <div class="vq-stat"><strong><?= (int)$counts['approved'] ?></strong><span>Approved</span></div>
        <div class="vq-stat"><strong><?= (int)$counts['rejected'] ?></strong><span>Rejected</span></div>
    </div>

    <form class="vq-filters" method="GET">
        <div style="min-width:220px;flex:1;">
            <label class="form-label">Search</label>
            <input type="text" name="search" class="form-control" placeholder="Ticket, name, phone, email, ZIP" value="<?= h($search) ?>">
        </div>
        <div style="min-width:190px;">
            <label class="form-label">Status</label>
            <select name="status" class="form-select">
                <option value="pending" <?= $status==='pending'?'selected':'' ?>>Pending</option>
                <option value="approved" <?= $status==='approved'?'selected':'' ?>>Approved</option>
                <option value="rejected" <?= $status==='rejected'?'selected':'' ?>>Rejected</option>
                <option value="all" <?= $status==='all'?'selected':'' ?>>All</option>
            </select>
        </div>
        <button class="btn btn-primary" type="submit"><i class="fas fa-filter me-1"></i>Filter</button>
    </form>

    <div class="vq-table-card">
        <div class="table-responsive">
            <table class="table align-middle">
                <thead>
                    <tr>
                        <th>Ticket No</th>
                        <th>Customer</th>
                        <th>Contact</th>
                        <th>Area</th>
                        <th>Product</th>
                        <th>Submitted</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!$requests): ?>
                    <tr><td colspan="8"><div class="vq-empty"><i class="fas fa-inbox fa-2x mb-2"></i><br>No requests found in this queue.</div></td></tr>
                <?php else: ?>
                    <?php foreach ($requests as $request): ?>
                        <?php $vStatus = $request['verification_status'] ?: 'approved'; ?>
                        <tr id="verification-row-<?= (int)$request['id'] ?>">
                            <td>
                                <a href="#" class="vq-request-link" onclick="openVerificationDetails(<?= (int)$request['id'] ?>); return false;">
                                    <?= h($request['request_number']) ?>
                                </a>
                            </td>
                            <td><strong><?= h($request['full_name'] ?: 'Customer') ?></strong></td>
                            <td>
                                <div><?= h($request['phone_number'] ?: '—') ?></div>
                                <small><?= h($request['customer_email'] ?: 'No email') ?></small>
                            </td>
                            <td>
                                <div><?= h($request['city_name'] ?: '—') ?><?= $request['state'] ? ', ' . h($request['state']) : '' ?></div>
                                <small><?= h($request['zip_code'] ?: '') ?><?= $request['region'] ? ' · ' . h($request['region']) : '' ?></small>
                            </td>
                            <td>
                                <div><?= h($request['appliance_name']) ?></div>
                                <small><?= h($request['brand_name']) ?></small>
                            </td>
                            <td><small><?= h(date('M d, Y h:i A', strtotime($request['requested_at'] ?? 'now'))) ?></small></td>
                            <td><span class="vq-status <?= h($vStatus) ?>"><i class="fas <?= $vStatus==='approved'?'fa-check-circle':($vStatus==='rejected'?'fa-times-circle':'fa-clock') ?>"></i><?= h(ucwords(str_replace('_',' ',$vStatus))) ?></span></td>
                            <td>
                                <?php if ($vStatus === 'pending'): ?>
                                    <div class="vq-actions">
                                        <button type="button" class="btn btn-sm btn-success" onclick="approveVerification(<?= (int)$request['id'] ?>)"><i class="fas fa-check me-1"></i>Approve</button>
                                        <button type="button" class="btn btn-sm btn-danger" onclick="openRejectModal(<?= (int)$request['id'] ?>, '<?= h($request['request_number']) ?>')"><i class="fas fa-ban me-1"></i>Reject</button>
                                    </div>
                                <?php else: ?>
                                    <small class="text-muted"><?= $vStatus === 'rejected' ? h($request['verification_reject_reason'] ?: 'Rejected') : 'Reviewed' ?></small>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="verificationDetailsModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-file-alt me-2"></i>Request Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="verificationDetailsBody">
                <div class="text-center py-5"><div class="loader"></div><p class="mt-3 text-muted">Loading details...</p></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="rejectVerificationModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form class="modal-content" id="rejectVerificationForm">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-ban me-2"></i>Reject Request</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="request_id" id="rejectRequestId">
                <p class="text-muted">Rejecting <strong id="rejectRequestNumber"></strong>. Please choose why this request cannot proceed.</p>
                <div class="mb-3">
                    <label class="form-label">Reject Reason</label>
                    <select name="reject_reason" id="rejectReason" class="form-select" required>
                        <option value="">Select reason</option>
                        <?php foreach ($rejectReasons as $reason): ?>
                            <option value="<?= h($reason) ?>"><?= h($reason) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Notes <span class="text-muted">(optional)</span></label>
                    <textarea name="notes" class="form-control" rows="3" placeholder="Add internal notes or explanation for the customer notification..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-danger"><i class="fas fa-ban me-1"></i>Reject Request</button>
            </div>
        </form>
    </div>
</div>

<script>
function verificationToast(message, type = 'info') {
    if (typeof showToast === 'function') {
        showToast(message, type);
    } else {
        alert(message);
    }
}

function openVerificationDetails(requestId) {
    $('#verificationDetailsBody').html('<div class="text-center py-5"><div class="loader"></div><p class="mt-3 text-muted">Loading details...</p></div>');
    bootstrap.Modal.getOrCreateInstance(document.getElementById('verificationDetailsModal')).show();
    $.ajax({
        url: '../csr/ajax/get_verification_details.php',
        method: 'GET',
        dataType: 'json',
        data: { request_id: requestId },
        success: function(response) {
            if (response.success) {
                $('#verificationDetailsBody').html(response.html);
            } else {
                $('#verificationDetailsBody').html('<div class="alert alert-danger">' + (response.message || 'Unable to load details.') + '</div>');
            }
        },
        error: function() {
            $('#verificationDetailsBody').html('<div class="alert alert-danger">Unable to load request details.</div>');
        }
    });
}

function approveVerification(requestId) {
    if (!confirm('Approve this request and move it to Tickets?')) return;
    $.ajax({
        url: '../csr/ajax/review_request_verification.php',
        method: 'POST',
        dataType: 'json',
        data: { request_id: requestId, action: 'approve' },
        success: function(response) {
            if (response.success) {
                verificationToast(response.message || 'Request approved.', 'success');
                setTimeout(function(){ location.reload(); }, 600);
            } else {
                verificationToast(response.message || 'Unable to approve request.', 'error');
            }
        },
        error: function() { verificationToast('Unable to approve request.', 'error'); }
    });
}

function openRejectModal(requestId, requestNumber) {
    $('#rejectRequestId').val(requestId);
    $('#rejectRequestNumber').text(requestNumber || ('Request #' + requestId));
    $('#rejectReason').val('');
    $('#rejectVerificationForm textarea[name="notes"]').val('');
    bootstrap.Modal.getOrCreateInstance(document.getElementById('rejectVerificationModal')).show();
}

$('#rejectVerificationForm').on('submit', function(e) {
    e.preventDefault();
    $.ajax({
        url: '../csr/ajax/review_request_verification.php',
        method: 'POST',
        dataType: 'json',
        data: $(this).serialize() + '&action=reject',
        success: function(response) {
            if (response.success) {
                verificationToast(response.message || 'Request rejected.', 'success');
                bootstrap.Modal.getInstance(document.getElementById('rejectVerificationModal')).hide();
                setTimeout(function(){ location.reload(); }, 600);
            } else {
                verificationToast(response.message || 'Unable to reject request.', 'error');
            }
        },
        error: function() { verificationToast('Unable to reject request.', 'error'); }
    });
});

<?php if (!empty($_GET['request_id'])): ?>
$(document).ready(function(){ openVerificationDetails(<?= (int)$_GET['request_id'] ?>); });
<?php endif; ?>
</script>
<?php
$content = ob_get_clean();
include 'layout.php';
