<?php
$search_patient = $_GET['patient'] ?? '';
$search_status = $_GET['status'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

$query = "
    SELECT xi.*, p.name as official_patient_name, v.visit_date
    FROM xray_inquiries xi
    LEFT JOIN patients p ON xi.patient_id = p.id
    LEFT JOIN visits v ON xi.visit_id = v.id
    WHERE 1=1";
$params = [];

if ($search_patient) {
    $query .= " AND (xi.patient_name LIKE ? OR p.name LIKE ?)";
    $params[] = "%$search_patient%";
    $params[] = "%$search_patient%";
}
if ($search_status) {
    $query .= " AND xi.status = ?";
    $params[] = $search_status;
}

// Count total records for pagination
$count_query = str_replace("xi.*, p.name as official_patient_name, v.visit_date", "COUNT(*)", $query);
$stmt = $db->prepare($count_query);
$stmt->execute($params);
$total_records = $stmt->fetchColumn();
$total_pages = ceil($total_records / $limit);

$query .= " ORDER BY xi.inquiry_date DESC LIMIT $limit OFFSET $offset";
$stmt = $db->prepare($query);
$stmt->execute($params);
$inquiries = $stmt->fetchAll();

// Fetch items for each inquiry
foreach ($inquiries as &$inquiry) {
    $stmt = $db->prepare("
        SELECT it.*, t.name_$lang as xray_name
        FROM xray_inquiry_items it 
        JOIN xray_tests t ON it.xray_id = t.id 
        WHERE it.inquiry_id = ?");
    $stmt->execute([$inquiry['id']]);
    $inquiry['items'] = $stmt->fetchAll();
}
unset($inquiry);

$all_xrays_list = $db->query("SELECT id, name_$lang as name, price FROM xray_tests ORDER BY name_$lang ASC")->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h3 class="fw-bold text-secondary"><?php echo __('xray_inquiries'); ?></h3>
    <button class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#addXrayInquiryModal">
        <i class="bi bi-plus-circle me-1"></i> <?php echo __('add_xray_inquiry'); ?>
    </button>
</div>

<!-- Search Bar -->
<div class="card shadow-sm border-0 mb-4">
    <div class="card-body">
        <form method="GET" action="" class="row g-3">
            <div class="col-md-6">
                <div class="input-group">
                    <span class="input-group-text bg-light border-end-0 text-muted"><i class="bi bi-search"></i></span>
                    <input type="text" name="patient" class="form-control bg-light border-start-0" placeholder="<?php echo __('patient'); ?>" value="<?php echo htmlspecialchars($search_patient); ?>">
                </div>
            </div>
            <div class="col-md-4">
                <select name="status" class="form-select bg-light">
                    <option value=""><?php echo __('status'); ?> (<?php echo __('all'); ?>)</option>
                    <option value="Pending" <?php echo $search_status == 'Pending' ? 'selected' : ''; ?>><?php echo __('Pending'); ?></option>
                    <option value="Completed" <?php echo $search_status == 'Completed' ? 'selected' : ''; ?>><?php echo __('Completed'); ?></option>
                    <option value="Cancelled" <?php echo $search_status == 'Cancelled' ? 'selected' : ''; ?>><?php echo __('Cancelled'); ?></option>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-secondary w-100"><?php echo __('search'); ?></button>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm border-0">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light text-secondary">
                    <tr>
                        <th class="px-4 py-3">#</th>
                        <th class="py-3"><?php echo __('patient'); ?></th>
                        <th class="py-3"><?php echo __('inquiry_date'); ?></th>
                        <th class="py-3"><?php echo __('status'); ?></th>
                        <th class="py-3"><?php echo __('xrays'); ?></th>
                        <th class="py-3"><?php echo __('results'); ?></th>
                        <th class="py-3 text-end px-4"><?php echo __('actions'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($inquiries)): ?>
                    <tr>
                        <td colspan="7" class="text-center py-5 text-muted">
                            <i class="bi bi-question-circle display-4 d-block mb-3"></i>
                            No inquiries found.
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($inquiries as $inquiry): ?>
                    <tr>
                        <td class="px-4 text-secondary"><?php echo $inquiry['id']; ?></td>
                        <td class="fw-semibold text-dark">
                            <?php echo htmlspecialchars($inquiry['official_patient_name'] ?: $inquiry['patient_name']); ?>
                            <?php if ($inquiry['visit_id']): ?>
                                <div class="small text-muted">
                                    <i class="bi bi-calendar-check me-1"></i>
                                    Linked to Visit #<?php echo $inquiry['visit_id']; ?> (<?php echo date('Y-m-d', strtotime($inquiry['visit_date'])); ?>)
                                </div>
                            <?php endif; ?>
                        </td>
                        <td class="text-secondary small"><?php echo $inquiry['inquiry_date']; ?></td>
                        <td>
                            <?php 
                            $status_class = 'bg-secondary';
                            if ($inquiry['status'] == 'Completed') $status_class = 'bg-success';
                            if ($inquiry['status'] == 'Pending') $status_class = 'bg-warning';
                            if ($inquiry['status'] == 'Cancelled') $status_class = 'bg-danger';
                            ?>
                            <span class="badge <?php echo $status_class; ?>"><?php echo __($inquiry['status']); ?></span>
                        </td>
                        <td>
                            <div class="d-flex flex-wrap gap-1">
                                <?php foreach ($inquiry['items'] as $item): ?>
                                    <span class="badge bg-light text-dark border">
                                        <?php echo htmlspecialchars($item['xray_name']); ?>
                                    </span>
                                <?php endforeach; ?>
                            </div>
                        </td>
                        <td>
                            <?php foreach ($inquiry['items'] as $item): ?>
                                <div class="small mb-1">
                                    <div class="d-flex align-items-center mb-1">
                                        <span class="text-muted me-1"><?php echo htmlspecialchars($item['xray_name']); ?>:</span>
                                        <span class="fw-bold me-2"><?php echo htmlspecialchars($item['result'] ?: '-'); ?></span>
                                    </div>
                                    <?php 
                                    $atts = json_decode($item['attachment'] ?? '', true);
                                    if (!is_array($atts) && !empty($item['attachment'])) {
                                        $atts = [['name' => basename($item['attachment']), 'path' => $item['attachment']]];
                                    } elseif (!is_array($atts)) {
                                        $atts = [];
                                    }
                                    ?>
                                    <?php if (!empty($atts)): ?>
                                    <div class="d-flex flex-wrap gap-1">
                                        <?php foreach ($atts as $att): ?>
                                            <a href="<?php echo htmlspecialchars($att['path']); ?>" target="_blank" class="btn btn-sm btn-outline-info py-0 px-1" title="<?php echo htmlspecialchars($att['name']); ?>">
                                                <i class="bi bi-image"></i> <small><?php echo htmlspecialchars($att['name']); ?></small>
                                            </a>
                                        <?php endforeach; ?>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </td>
                        <td class="text-end px-4">
                            <div class="btn-group shadow-sm border rounded bg-white">
                                <button class="btn btn-link text-info py-1 px-2 border-end" 
                                        onclick="printXrayInquiry(<?php echo htmlspecialchars(json_encode($inquiry, JSON_UNESCAPED_UNICODE)); ?>)"
                                        data-bs-toggle="tooltip" title="<?php echo __('print'); ?>">
                                    <i class="bi bi-printer"></i>
                                </button>
                                <button class="btn btn-link text-primary py-1 px-2 border-end" 
                                        onclick="showEditXrayInquiryModal(<?php echo htmlspecialchars(json_encode($inquiry, JSON_UNESCAPED_UNICODE)); ?>)"
                                        data-bs-toggle="tooltip" title="<?php echo __('edit'); ?>">
                                    <i class="bi bi-pencil-square"></i>
                                </button>
                                <button class="btn btn-link text-danger py-1 px-2" 
                                        onclick="showDeleteXrayInquiryModal(<?php echo $inquiry['id']; ?>)"
                                        data-bs-toggle="tooltip" title="<?php echo __('delete'); ?>">
                                    <i class="bi bi-trash3"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <nav aria-label="Page navigation" class="p-3 border-top bg-light">
            <ul class="pagination justify-content-center mb-0">
                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?section=xray_inquiries&page=<?php echo $page - 1; ?>&patient=<?php echo urlencode($search_patient); ?>&status=<?php echo urlencode($search_status); ?>" tabindex="-1">Previous</a>
                </li>
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <li class="page-item <?php echo $page == $i ? 'active' : ''; ?>">
                    <a class="page-link" href="?section=xray_inquiries&page=<?php echo $i; ?>&patient=<?php echo urlencode($search_patient); ?>&status=<?php echo urlencode($search_status); ?>"><?php echo $i; ?></a>
                </li>
                <?php endfor; ?>
                <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?section=xray_inquiries&page=<?php echo $page + 1; ?>&patient=<?php echo urlencode($search_patient); ?>&status=<?php echo urlencode($search_status); ?>">Next</a>
                </li>
            </ul>
        </nav>
        <?php endif; ?>
    </div>
</div>

<!-- Edit X-Ray Inquiry Modal -->
<div class="modal fade" id="editXrayInquiryModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=xray_inquiries" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="edit_xray_inquiry">
            <input type="hidden" name="id" id="edit_xray_inquiry_id">
            <input type="hidden" name="visit_id" id="edit_xray_inquiry_visit_id">
            <input type="hidden" name="patient_id" id="edit_xray_inquiry_patient_id">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('edit_xray_inquiry'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('patient_name'); ?></label>
                        <input type="text" name="patient_name" id="edit_xray_inquiry_patient_name" class="form-control" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('inquiry_date'); ?></label>
                            <input type="datetime-local" name="inquiry_date" id="edit_xray_inquiry_date" class="form-control">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('status'); ?></label>
                            <select name="status" id="edit_xray_inquiry_status" class="form-select">
                                <option value="Pending"><?php echo __('Pending'); ?></option>
                                <option value="Completed"><?php echo __('Completed'); ?></option>
                                <option value="Cancelled"><?php echo __('Cancelled'); ?></option>
                            </select>
                        </div>
                    </div>
                    
                    <label class="form-label fw-bold"><?php echo __('xray_tests'); ?></label>
                    <div class="table-responsive mb-2">
                        <table class="table table-bordered table-sm" id="editXrayInquiryTestsTable">
                            <thead>
                                <tr>
                                    <th><?php echo __('test'); ?></th>
                                    <th><?php echo __('result'); ?></th>
                                    <th><?php echo __('attachment'); ?></th>
                                    <th style="width: 50px;"></th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="addEditXrayInquiryTestRow()">
                        <i class="bi bi-plus-lg"></i> <?php echo __('add_test'); ?>
                    </button>
                    
                    <div class="mt-3">
                        <label class="form-label"><?php echo __('notes'); ?></label>
                        <textarea name="notes" id="edit_xray_inquiry_notes" class="form-control summernote" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4"><?php echo __('save'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Delete X-Ray Inquiry Modal -->
<div class="modal fade" id="deleteXrayInquiryModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=xray_inquiries" method="POST">
            <input type="hidden" name="action" value="delete_xray_inquiry">
            <input type="hidden" name="id" id="delete_xray_inquiry_id">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('delete_xray_inquiry'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p><?php echo __('confirm_delete'); ?>?</p>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-danger px-4"><?php echo __('delete'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
function showEditXrayInquiryModal(data) {
    document.getElementById('edit_xray_inquiry_id').value = data.id;
    document.getElementById('edit_xray_inquiry_visit_id').value = data.visit_id || '';
    document.getElementById('edit_xray_inquiry_patient_id').value = data.patient_id || '';
    document.getElementById('edit_xray_inquiry_patient_name').value = data.patient_name || (data.official_patient_name || '');
    document.getElementById('edit_xray_inquiry_date').value = data.inquiry_date ? data.inquiry_date.replace(' ', 'T') : '';
    document.getElementById('edit_xray_inquiry_status').value = data.status;
    
    // Summernote
    $('#edit_xray_inquiry_notes').summernote('code', data.notes || '');

    // Populate tests
    const tbody = document.querySelector('#editXrayInquiryTestsTable tbody');
    tbody.innerHTML = '';
    
    if (data.items && data.items.length > 0) {
        data.items.forEach(item => {
            addEditXrayInquiryTestRow(item.xray_id, item.result, item.attachment);
        });
    } else {
        addEditXrayInquiryTestRow();
    }
    
    var modal = new bootstrap.Modal(document.getElementById('editXrayInquiryModal'));
    modal.show();
}

function addEditXrayInquiryTestRow(xrayId = '', result = '', attachment = '') {
    const tbody = document.querySelector('#editXrayInquiryTestsTable tbody');
    const tr = document.createElement('tr');
    const rowIndex = tbody.children.length; // Unique index for this row
    
    let options = '<option value="">Select X-Ray...</option>';
    <?php foreach ($all_xrays_list as $x): ?>
        options += `<option value="<?php echo $x['id']; ?>" ${xrayId == <?php echo $x['id']; ?> ? 'selected' : ''}><?php echo htmlspecialchars($x['name']); ?> ($<?php echo $x['price']; ?>)</option>`;
    <?php endforeach; ?>
    
    // Parse attachments
    let files = [];
    try {
        files = JSON.parse(attachment || '[]');
        if (!Array.isArray(files)) throw new Error();
    } catch (e) {
        if (attachment) files = [{name: 'Attachment', path: attachment}];
    }

    let attachmentHtml = `
        <input type="file" name="new_attachments_${rowIndex}[]" class="form-control" multiple>
        <input type="hidden" name="row_indices[]" value="${rowIndex}">
        <div class="existing-files mt-1 d-flex flex-wrap gap-1">
    `;
    
    files.forEach((file) => {
        // Escape quotes for value attribute
        const fileJson = JSON.stringify(file).replace(/"/g, '&quot;');
        attachmentHtml += `
            <div class="badge bg-light text-dark border p-1 d-inline-flex align-items-center">
                <a href="${file.path}" target="_blank" class="text-decoration-none me-2 text-truncate" style="max-width: 100px;">${file.name}</a>
                <button type="button" class="btn-close btn-close-white small" style="width: 0.5em; height: 0.5em;" onclick="this.parentElement.remove()"></button>
                <input type="hidden" name="existing_attachments_${rowIndex}[]" value="${fileJson}">
            </div>
        `;
    });
    attachmentHtml += '</div>';

    tr.innerHTML = `
        <td><select name="xray_ids[]" class="form-select select2-modal">${options}</select></td>
        <td><input type="text" name="results[]" class="form-control" value="${result || ''}"></td>
        <td>${attachmentHtml}</td>
        <td><button type="button" class="btn btn-sm btn-danger" onclick="this.closest('tr').remove()"><i class="bi bi-x-lg"></i></button></td>
    `;
    tbody.appendChild(tr);
    $(tr).find('.select2-modal').select2({ dropdownParent: $(tr).closest('.modal'), width: '100%' });
}

function showDeleteXrayInquiryModal(id) {
    document.getElementById('delete_xray_inquiry_id').value = id;
    var modal = new bootstrap.Modal(document.getElementById('deleteXrayInquiryModal'));
    modal.show();
}

function printXrayInquiry(data) {
    const id = data.id;
    // Open in new window
    window.open('print_xray_inquiry.php?id=' + id, '_blank');
}
</script>