<?php
session_start();
require_once 'config/database.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
require_once 'includes/translation.php';
require_once 'includes/page_permissions_helper.php';

if (!isset($_SESSION['user_id'])) {
    redirect('login.php');
}

// Set current page for permissions
$currentPage = 'reports';

// Check page access permission
PagePermissions::requirePageAccess($currentPage);

$db = new Database();
$conn = $db->getConnection();

// Get all reports with related data
$stmt = $conn->prepare("
    SELECT 
        ar.id,
        ar.report_date,
        ar.problem_authority,
        ar.status,
        ar.created_at,
        ar.drug_type,
        ar.other_medication_name,
        p.patient_name,
        p.mrn,
        u.unit_name,
        COALESCE(a.antibiotic_name, ar.other_medication_name, 'غير محدد') as antibiotic_name,
        usr.full_name as pharmacist_name
    FROM antibiotic_reports ar
    JOIN patients p ON ar.patient_id = p.id
    JOIN units u ON ar.unit_id = u.id
    LEFT JOIN antibiotics a ON ar.antibiotic_id = a.id
    JOIN users usr ON ar.reporting_pharmacist_id = usr.id
    ORDER BY ar.created_at DESC
");
$stmt->execute();
$reports = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Set page title
$page_title = __('medical_reports_page') . ' - ' . __('system_name');

// Include header
include 'includes/header.php';
?>

<!-- Main Content -->

    <div class="header no-print">
        <div>
            <h1 class="h3 mb-0"><?php echo __('medical_reports_page'); ?></h1>
            <p class="text-muted mb-0"><?php echo __('system_overview'); ?></p>
        </div>
        <div class="d-flex gap-2">
            <?php if (PagePermissions::hasPermission($currentPage, 'add_report')): ?>
            <a href="clinical_pharmacy_intervention.php" class="btn btn-success">
                <i class="fas fa-file-medical"></i> <?php echo __('medical_event_report'); ?>
            </a>
            <?php endif; ?>
            
            <?php if (PagePermissions::hasPermission($currentPage, 'export_reports_excel')): ?>
            <button type="button" class="btn btn-primary" onclick="exportToExcel()">
                <i class="fas fa-file-excel"></i> <?php echo __('export_excel'); ?>
            </button>
            <?php endif; ?>
        </div>
    </div>

    <!-- Filter Options -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="row">
                <div class="col-md-3">
                    <label for="statusFilter" class="form-label"><?php echo __('filter_by_status'); ?></label>
                    <select class="form-select" id="statusFilter">
                        <option value=""><?php echo __('all_status'); ?></option>
                        <option value="pending"><?php echo __('pending'); ?></option>
                        <option value="completed"><?php echo __('completed'); ?></option>
                        <option value="cancelled"><?php echo __('cancelled'); ?></option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label for="dateFilter" class="form-label"><?php echo __('filter_by_date'); ?></label>
                    <input type="date" class="form-control" id="dateFilter">
                </div>
                <div class="col-md-4">
                    <label for="searchFilter" class="form-label"><?php echo __('search'); ?></label>
                    <input type="text" class="form-control" id="searchFilter" placeholder="<?php echo __('search_patient_or_mrn'); ?>">
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button type="button" class="btn btn-secondary w-100" onclick="clearFilters()">
                        <i class="fas fa-times"></i> <?php echo __('clear_filters'); ?>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Reports Table -->
    <div class="card shadow">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary"><?php echo __('reports_list'); ?></h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered" id="reportsTable" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th><?php echo __('report_date'); ?></th>
                            <th><?php echo __('patient_name'); ?></th>
                            <th><?php echo __('mrn'); ?></th>
                            <th><?php echo __('antibiotic'); ?></th>
                            <th><?php echo __('unit'); ?></th>
                            <th><?php echo __('pharmacist'); ?></th>
                            <th><?php echo __('status'); ?></th>
                            <th><?php echo __('actions'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($reports as $report): ?>
                        <tr>
                            <td><?php echo date('Y-m-d', strtotime($report['report_date'])); ?></td>
                            <td><?php echo htmlspecialchars($report['patient_name']); ?></td>
                            <td><?php echo htmlspecialchars($report['mrn']); ?></td>
                            <td><?php echo htmlspecialchars($report['antibiotic_name']); ?></td>
                            <td><?php echo htmlspecialchars($report['unit_name']); ?></td>
                            <td><?php echo htmlspecialchars($report['pharmacist_name']); ?></td>
                            <td data-status="<?php echo $report['status']; ?>">
                                <?php
                                $status_class = '';
                                $status_text = '';
                                switch($report['status']) {
                                    case 'pending':
                                        $status_class = 'bg-warning';
                                        $status_text = __('pending');
                                        break;
                                    case 'completed':
                                        $status_class = 'bg-success';
                                        $status_text = __('completed');
                                        break;
                                    case 'cancelled':
                                        $status_class = 'bg-danger';
                                        $status_text = __('cancelled');
                                        break;
                                    default:
                                        $status_class = 'bg-secondary';
                                        $status_text = __('not_specified');
                                }
                                ?>
                                <span class="badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                            </td>
                            <td>
                                <?php if (PagePermissions::hasPermission($currentPage, 'view_reports')): ?>
                                <a href="view_medical_event.php?id=<?php echo $report['id']; ?>" class="btn btn-sm btn-info" title="<?php echo __('view'); ?>">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <?php endif; ?>
                                
                                <?php if (PagePermissions::hasPermission($currentPage, 'edit_report')): ?>
                                <a href="edit_report.php?id=<?php echo $report['id']; ?>" class="btn btn-sm btn-warning" title="<?php echo __('edit'); ?>">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <?php endif; ?>
                                
                                <?php if (PagePermissions::hasPermission($currentPage, 'print_reports')): ?>
                                <a href="print_report.php?id=<?php echo $report['id']; ?>" class="btn btn-sm btn-secondary" title="<?php echo __('print'); ?>" target="_blank">
                                    <i class="fas fa-print"></i>
                                </a>
                                <?php endif; ?>
                                
                                <?php if (PagePermissions::hasPermission($currentPage, 'delete_report')): ?>
                                <button type="button" class="btn btn-sm btn-danger" title="<?php echo __('delete'); ?>" onclick="confirmReportDelete(<?php echo $report['id']; ?>)">
                                    <i class="fas fa-trash"></i>
                                </button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalLabel"><?php echo __('confirm_delete'); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <?php echo __('confirm_delete_report_message'); ?>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn"><?php echo __('delete'); ?></button>
            </div>
        </div>
    </div>
</div>

<script>
let reportToDelete = null;

function confirmReportDelete(reportId) {
    reportToDelete = reportId;
    const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
    modal.show();
}

document.getElementById('confirmDeleteBtn').addEventListener('click', function() {
    if (reportToDelete) {
        window.location.href = `delete.php?type=report&id=${reportToDelete}`;
    }
});

// Filter functionality
document.getElementById('statusFilter').addEventListener('change', filterTable);
document.getElementById('dateFilter').addEventListener('change', filterTable);
document.getElementById('searchFilter').addEventListener('input', filterTable);

function filterTable() {
    const statusFilter = document.getElementById('statusFilter').value.toLowerCase();
    const dateFilter = document.getElementById('dateFilter').value;
    const searchFilter = document.getElementById('searchFilter').value.toLowerCase();
    const table = document.getElementById('reportsTable');
    const rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');

    for (let i = 0; i < rows.length; i++) {
        const row = rows[i];
        const cells = row.getElementsByTagName('td');
        
        const reportDate = cells[0].textContent;
        const patientName = cells[1].textContent.toLowerCase();
        const mrn = cells[2].textContent.toLowerCase();
        const status = cells[6].getAttribute('data-status').toLowerCase();
        
        let showRow = true;
        
        // Status filter
        if (statusFilter && status !== statusFilter) {
            showRow = false;
        }
        
        // Date filter
        if (dateFilter && reportDate !== dateFilter) {
            showRow = false;
        }
        
        // Search filter
        if (searchFilter && !patientName.includes(searchFilter) && !mrn.includes(searchFilter)) {
            showRow = false;
        }
        
        row.style.display = showRow ? '' : 'none';
    }
}

function clearFilters() {
    document.getElementById('statusFilter').value = '';
    document.getElementById('dateFilter').value = '';
    document.getElementById('searchFilter').value = '';
    filterTable();
}

function exportToExcel() {
    const exportBtn = document.querySelector('[onclick="exportToExcel()"]');
    if (exportBtn) {
        exportBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> <?php echo __('exporting'); ?>';
        exportBtn.disabled = true;
    }
    
    window.location.href = 'export/excel_export.php';
    
    setTimeout(() => {
        if (exportBtn) {
            exportBtn.innerHTML = '<i class="fas fa-file-excel"></i> <?php echo __('export_excel'); ?>';
            exportBtn.disabled = false;
        }
    }, 2000);
}
</script>

<?php include 'includes/footer.php'; ?>
