<?php
$search_patient = $_GET['patient'] ?? '';
$search_status = $_GET['status'] ?? '';

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

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

$query .= " ORDER BY li.inquiry_date DESC";
$stmt = $db->prepare($query);
$stmt->execute($params);
$inquiries = $stmt->fetchAll();

// Fetch tests for each inquiry
foreach ($inquiries as &$inquiry) {
    $stmt = $db->prepare("
        SELECT it.*, t.name_$lang as test_name, t.normal_range as reference_range
        FROM inquiry_tests it 
        JOIN laboratory_tests t ON it.test_id = t.id 
        WHERE it.inquiry_id = ?");
    $stmt->execute([$inquiry['id']]);
    $inquiry['tests'] = $stmt->fetchAll();
}
unset($inquiry);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h3 class="fw-bold text-secondary"><?php echo __('inquiries'); ?></h3>
    <button class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#addInquiryModal">
        <i class="bi bi-plus-circle me-1"></i> <?php echo __('add_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 __('tests'); ?></th>
                        <th class="py-3 text-end px-4"><?php echo __('actions'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($inquiries)): ?>
                    <tr>
                        <td colspan="6" class="text-center py-5 text-muted">
                            <i class="bi bi-question-circle display-4 d-block mb-3"></i>
                            <?php echo __('no_data_found') ?? '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>
                                    <?php echo __('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; ?> px-2 py-1"><?php echo __($inquiry['status']); ?></span>
                        </td>
                        <td>
                            <?php foreach ($inquiry['tests'] as $test): ?>
                            <div class="mb-1">
                                <span class="badge bg-light text-dark border small" data-bs-toggle="tooltip" title="Ref: <?php echo htmlspecialchars($test['reference_range']); ?>">
                                    <?php echo htmlspecialchars($test['test_name']); ?>: <strong><?php echo htmlspecialchars($test['result'] ?: '-'); ?></strong>
                                </span>
                                <?php if ($test['attachment']): ?>
                                    <a href="<?php echo htmlspecialchars($test['attachment']); ?>" target="_blank" class="text-info ms-1" title="<?php echo __('view_image'); ?>"><i class="bi bi-image"></i></a>
                                <?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-dark py-1 px-2 border-end" 
                                        onclick="printInquiry(<?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="showEditInquiryModal(<?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="showDeleteInquiryModal(<?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>
    </div>
</div>

<!-- Edit Inquiry Modal -->
<div class="modal fade" id="editInquiryModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=laboratory_inquiries" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="edit_inquiry">
            <input type="hidden" name="id" id="edit_inquiry_id">
            <input type="hidden" name="visit_id" id="edit_lab_visit_id">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('edit_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_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_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_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 __('tests'); ?></label>
                    <div class="table-responsive mb-2">
                        <table class="table table-bordered table-sm" id="editInquiryTestsTable">
                            <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="addEditInquiryTestRow()">
                        <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_inquiry_notes" class="form-control" 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 Inquiry Modal -->
<div class="modal fade" id="deleteInquiryModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=laboratory_inquiries" method="POST">
            <input type="hidden" name="action" value="delete_inquiry">
            <input type="hidden" name="id" id="delete_inquiry_id">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('delete'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p class="mb-0"><?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>
    const allTestsData = <?php echo json_encode($GLOBALS['all_tests'] ?? []); ?>;

    function addEditInquiryTestRow(test = null) {
        const tbody = document.querySelector('#editInquiryTestsTable tbody');
        const tr = document.createElement('tr');
        
        let options = '<option value=""><?php echo __('select'); ?>...</option>';
        allTestsData.forEach(t => {
            const selected = (test && test.test_id == t.id) ? 'selected' : '';
            options += `<option value="${t.id}" ${selected}>${t.name} ($${t.price})</option>`;
        });
        
        let resultVal = test && test.result ? test.result.replace(/"/g, '&quot;') : '';
        let attachmentHtml = '<input type="file" name="attachments[]" class="form-control form-control-sm">';
        let existingAttachment = '';
        if (test && test.attachment) {
            existingAttachment = `<input type="hidden" name="existing_attachments[]" value="${test.attachment}">`;
            attachmentHtml += `<div class="mt-1 small"><a href="${test.attachment}" target="_blank" class="text-info"><i class="bi bi-paperclip"></i> <?php echo __('view_image'); ?></a></div>`;
        } else {
            existingAttachment = `<input type="hidden" name="existing_attachments[]" value="">`;
        }
        
        tr.innerHTML = `
            <td><select name="test_ids[]" class="form-select form-select-sm select2-modal">${options}</select></td>
            <td><input type="text" name="results[]" class="form-control form-control-sm" value="${resultVal}"></td>
            <td>${attachmentHtml}${existingAttachment}</td>
            <td><button type="button" class="btn btn-sm btn-danger py-0 px-2" onclick="this.closest('tr').remove()"><i class="bi bi-x"></i></button></td>
        `;
        tbody.appendChild(tr);
        if (typeof jQuery !== 'undefined') {
            $(tr).find('.select2-modal').select2({ dropdownParent: $(tr).closest('.modal'), width: '100%' });
        }
    }

    function showEditInquiryModal(inquiry) {
        if (!inquiry) return;
        var el = document.getElementById('editInquiryModal');
        if (el) {
            document.getElementById('edit_inquiry_id').value = inquiry.id || '';
            document.getElementById('edit_lab_visit_id').value = inquiry.visit_id || '';
            document.getElementById('edit_inquiry_patient_name').value = inquiry.patient_name || inquiry.official_patient_name || '';
            
            var fields = {
                'edit_inquiry_status': inquiry.status || 'Pending',
                'edit_inquiry_notes': inquiry.notes || ''
            };
            for (var id in fields) {
                var field = document.getElementById(id);
                if (field) field.value = fields[id];
            }
            if (inquiry.inquiry_date) {
                var dateField = document.getElementById('edit_inquiry_date');
                if (dateField) dateField.value = inquiry.inquiry_date.replace(' ', 'T').substring(0, 16);
            }
            
            const tbody = document.querySelector('#editInquiryTestsTable tbody');
            if (tbody) tbody.innerHTML = '';
            
            if (inquiry.tests && inquiry.tests.length > 0) {
                inquiry.tests.forEach(test => {
                    addEditInquiryTestRow(test);
                });
            } else {
                addEditInquiryTestRow();
            }
            
            var modal = bootstrap.Modal.getOrCreateInstance(el);
            modal.show();
        }
    }

    function showDeleteInquiryModal(id) {
        var el = document.getElementById('deleteInquiryModal');
        if (el) {
            var field = document.getElementById('delete_inquiry_id');
            if (field) field.value = id || '';
            var modal = bootstrap.Modal.getOrCreateInstance(el);
            modal.show();
        }
    }

    function printInquiry(inquiry) {
        if (!inquiry) return;
        try {
            const printWindow = window.open('', '_blank');
            if (!printWindow) return;
            const date = inquiry.inquiry_date ? new Date(inquiry.inquiry_date).toLocaleString() : '';
            
            let testsHtml = '';
            if (inquiry.tests && inquiry.tests.length > 0) {
                inquiry.tests.forEach(t => {
                    testsHtml += `
                        <tr>
                            <td style="padding: 10px; border-bottom: 1px solid #eee;">${t.test_name}</td>
                            <td style="padding: 10px; border-bottom: 1px solid #eee; text-align: center;"><strong>${t.result || '-'}</strong></td>
                            <td style="padding: 10px; border-bottom: 1px solid #eee; text-align: center;">${t.reference_range || '-'}</td>
                        </tr>
                    `;
                });
            }

            printWindow.document.write(`
                <html>
                <head>
                    <title><?php echo __('laboratory_inquiries'); ?> - ${inquiry.patient_name || inquiry.official_patient_name}</title>
                    <style>
                        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #333; line-height: 1.6; }
                        .header { text-align: center; border-bottom: 2px solid #002D62; padding-bottom: 20px; margin-bottom: 30px; }
                        .header h1 { margin: 0; color: #002D62; }
                        .info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 30px; }
                        .info-item b { color: #555; }
                        table { width: 100%; border-collapse: collapse; margin-bottom: 30px; }
                        th { background-color: #f8f9fa; text-align: left; padding: 12px; border-bottom: 2px solid #dee2e6; }
                        .footer { margin-top: 50px; border-top: 1px solid #eee; padding-top: 20px; text-align: center; font-size: 0.9em; color: #777; }
                    </style>
                </head>
                <body>
                    <div class="header">
                        <h1>LABORATORY REPORT</h1>
                    </div>
                    
                    <div class="info-grid">
                        <div class="info-item"><b><?php echo __('patient'); ?>:</b> ${inquiry.patient_name || inquiry.official_patient_name}</div>
                        <div class="info-item"><b><?php echo __('date'); ?>:</b> ${date}</div>
                        <div class="info-item"><b><?php echo __('inquiry'); ?> #:</b> #${inquiry.id}</div>
                        <div class="info-item"><b><?php echo __('status'); ?>:</b> ${inquiry.status}</div>
                    </div>

                    <table>
                        <thead>
                            <tr>
                                <th><?php echo __('test'); ?></th>
                                <th style="text-align: center;"><?php echo __('result'); ?></th>
                                <th style="text-align: center;"><?php echo __('normal_range'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            ${testsHtml}
                        </tbody>
                    </table>

                    ${inquiry.notes ? `<div style="margin-top: 20px;"><b><?php echo __('notes'); ?>:</b><p>${inquiry.notes}</p></div>` : ''}

                    <div class="footer">
                        <p><?php echo __('computer_generated_report'); ?></p>
                        <p><?php echo __('printed_on'); ?>: ${new Date().toLocaleString()}</p>
                    </div>
                    
                    <script>
                        window.onload = function() { window.print(); setTimeout(function() { window.close(); }, 500); }
                    <\/script>
                </body>
                </html>
            `);
            printWindow.document.close();
        } catch (e) { console.error('Print inquiry failed:', e); }
    }
</script>