<?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');
}

// Check permission to access patient management
$currentPage = 'patients';
PagePermissions::requirePageAccess($currentPage);

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

// ============================================================
// Handle direct delete from this page (bypass delete.php)
// ============================================================
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id']) && is_numeric($_GET['id'])) {
    if (PagePermissions::hasPermission($currentPage, 'delete_patient')) {
        $del_id = (int)$_GET['id'];
        try {
            // Check patient exists
            $chk = $conn->prepare("SELECT id FROM patients WHERE id = ?");
            $chk->execute([$del_id]);
            if ($chk->rowCount() > 0) {
                // Check no reports
                $rpt = $conn->prepare("SELECT COUNT(*) as cnt FROM antibiotic_reports WHERE patient_id = ?");
                $rpt->execute([$del_id]);
                $cnt = $rpt->fetch(PDO::FETCH_ASSOC)['cnt'];
                if ($cnt > 0) {
                    $_SESSION['delete_message'] = 'لا يمكن حذف المريض لأنه مرتبط بتقارير موجودة';
                } else {
                    $conn->prepare("DELETE FROM patients WHERE id = ?")->execute([$del_id]);
                    logActivity($conn, $_SESSION['user_id'], 'حذف مريض', 'patients', $del_id);
                    $_SESSION['delete_message'] = 'تم حذف المريض بنجاح';
                }
            } else {
                $_SESSION['delete_message'] = 'المريض غير موجود';
            }
        } catch (Exception $e) {
            $_SESSION['delete_message'] = 'حدث خطأ: ' . $e->getMessage();
        }
    } else {
        $_SESSION['delete_message'] = 'ليس لديك صلاحية لحذف المرضى';
    }
    // Redirect to same page without action param
    $base = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\') . '/';
    header("Location: " . $base . "manage_patients.php");
    exit();
}

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

// Get patients with statistics
$stmt = $conn->query("
    SELECT 
        p.*,
        COUNT(ar.id) as report_count,
        MAX(ar.created_at) as last_report_date,
        u.unit_name
    FROM patients p
    LEFT JOIN antibiotic_reports ar ON p.id = ar.patient_id
    LEFT JOIN units u ON JSON_CONTAINS(p.units, JSON_QUOTE(u.unit_name))
    GROUP BY p.id
    ORDER BY p.created_at DESC
");
$patients = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get statistics
$total_patients = count($patients);
$patients_with_reports = count(array_filter($patients, function($p) { return $p['report_count'] > 0; }));
$male_patients = count(array_filter($patients, function($p) { return $p['gender'] == 'male'; }));
$female_patients = count(array_filter($patients, function($p) { return $p['gender'] == 'female'; }));

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

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

<link rel="stylesheet" href="assets/css/permissions-box.css">

<style>
.pt-table th { background: #5e35b1; color: #fff; font-size: .82rem; white-space: nowrap; }
.pt-table td { font-size: .82rem; vertical-align: middle; }
.pt-table tbody tr:hover { background: #f8f5ff; }
.gender-badge { padding: 3px 10px; border-radius: 20px; font-size: .72rem; font-weight: 600; }
.gender-male  { background: #ebf8ff; color: #2b6cb0; }
.gender-female{ background: #fff5f7; color: #b83280; }
.unit-badge   { display:inline-block; background:#f7fafc; color:#4a5568; padding:2px 7px; border-radius:5px; font-size:.68rem; margin:1px; border:1px solid #e2e8f0; }
.kpi-card     { border-radius:14px; padding:1rem; color:#fff; position:relative; overflow:hidden; }
.kpi-card .kpi-num { font-size:1.8rem; font-weight:800; }
.kpi-card .kpi-lbl { font-size:.75rem; opacity:.9; }
.kpi-card .kpi-icon{ position:absolute; left:1rem; top:50%; transform:translateY(-50%); font-size:2.5rem; opacity:.18; }
[dir=rtl] .kpi-card .kpi-icon { left:auto; right:1rem; }
.kpi-blue  { background:linear-gradient(135deg,#1e88e5,#1565c0); }
.kpi-green { background:linear-gradient(135deg,#43a047,#2e7d32); }
.kpi-info  { background:linear-gradient(135deg,#00897b,#00695c); }
.kpi-pink  { background:linear-gradient(135deg,#d81b60,#880e4f); }
@media print { .no-print{display:none!important;} }
</style>

<!-- Main Content -->

    <div class="header no-print">
        <div>
            <h1 class="h3 mb-0"><?php echo __('patient_management'); ?></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_patient')): ?>
            <a href="add_patient.php" class="btn btn-success">
                <i class="fas fa-user-plus"></i> <?php echo __('add_patient'); ?>
            </a>
            <?php endif; ?>
            <?php if (PagePermissions::hasPermission($currentPage, 'export_patients_excel')): ?>
            <button type="button" class="btn btn-primary" onclick="exportPatients()">
                <i class="fas fa-file-excel"></i> <?php echo __('export_excel'); ?>
            </button>
            <?php endif; ?>
        </div>
    </div>

    <?php if (isset($_SESSION['delete_message'])): ?>
    <div class="alert <?php echo strpos($_SESSION['delete_message'], 'بنجاح') !== false ? 'alert-success' : 'alert-warning'; ?> alert-dismissible fade show" role="alert">
        <i class="fas <?php echo strpos($_SESSION['delete_message'], 'بنجاح') !== false ? 'fa-check-circle' : 'fa-exclamation-triangle'; ?> me-2"></i>
        <?php echo htmlspecialchars($_SESSION['delete_message']); unset($_SESSION['delete_message']); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <!-- Statistics Overview -->
    <div class="row g-3 mb-4">
        <div class="col-6 col-md-3">
            <div class="kpi-card kpi-blue">
                <div class="kpi-num"><?php echo $total_patients; ?></div>
                <div class="kpi-lbl"><?php echo __('total_patients'); ?></div>
                <i class="fas fa-users kpi-icon"></i>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="kpi-card kpi-green">
                <div class="kpi-num"><?php echo $patients_with_reports; ?></div>
                <div class="kpi-lbl"><?php echo __('patients_with_reports'); ?></div>
                <i class="fas fa-file-medical kpi-icon"></i>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="kpi-card kpi-info">
                <div class="kpi-num"><?php echo $male_patients; ?></div>
                <div class="kpi-lbl"><?php echo __('male_patients'); ?></div>
                <i class="fas fa-mars kpi-icon"></i>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="kpi-card kpi-pink">
                <div class="kpi-num"><?php echo $female_patients; ?></div>
                <div class="kpi-lbl"><?php echo __('female_patients'); ?></div>
                <i class="fas fa-venus kpi-icon"></i>
            </div>
        </div>
    </div>

    <!-- Search and Filter -->
    <div class="card mb-3 border-0 shadow-sm" style="border-radius:12px;">
        <div class="card-body py-2">
            <div class="row g-2 align-items-center">
                <div class="col-md-4">
                    <input type="text" class="form-control form-control-sm" id="searchPatients" placeholder="<?php echo __('search_patients'); ?>">
                </div>
                <div class="col-md-3">
                    <select class="form-select form-select-sm" id="genderFilter">
                        <option value=""><?php echo __('all_genders'); ?></option>
                        <option value="male"><?php echo __('male'); ?></option>
                        <option value="female"><?php echo __('female'); ?></option>
                    </select>
                </div>
                <div class="col-md-3">
                    <select class="form-select form-select-sm" id="reportsFilter">
                        <option value=""><?php echo __('all_patients'); ?></option>
                        <option value="with_reports"><?php echo __('patients_with_reports_filter'); ?></option>
                        <option value="without_reports"><?php echo __('patients_without_reports'); ?></option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-sm btn-outline-secondary w-100" onclick="clearFilters()">
                        <i class="fas fa-times me-1"></i><?php echo __('reset'); ?>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Patients Table -->
    <div class="card border-0 shadow-sm" style="border-radius:12px;">
        <div class="card-body p-0">
            <?php if (empty($patients)): ?>
            <div class="text-center py-5">
                <i class="fas fa-users fa-3x text-muted mb-3"></i>
                <h5 class="text-muted"><?php echo __('no_patients'); ?></h5>
                <p class="text-muted"><?php echo __('no_patients_message'); ?></p>
                <a href="add_patient.php" class="btn btn-primary btn-sm">
                    <i class="fas fa-user-plus me-1"></i><?php echo __('add_patient'); ?>
                </a>
            </div>
            <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover mb-0 pt-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th><?php echo __('patient_name'); ?></th>
                            <th><?php echo __('mrn'); ?></th>
                            <th><?php echo __('gender'); ?></th>
                            <th><?php echo __('units_departments'); ?></th>
                            <th class="text-center"><?php echo __('reports'); ?></th>
                            <th><?php echo __('last_report'); ?></th>
                            <th><?php echo __('date_added'); ?></th>
                            <th class="text-center no-print"><?php echo __('actions'); ?></th>
                        </tr>
                    </thead>
                    <tbody id="patientsTableBody">
                        <?php foreach ($patients as $i => $patient): ?>
                        <tr class="patient-row"
                            data-name="<?php echo strtolower(htmlspecialchars($patient['patient_name'])); ?>"
                            data-mrn="<?php echo strtolower(htmlspecialchars($patient['mrn'])); ?>"
                            data-gender="<?php echo $patient['gender']; ?>"
                            data-reports="<?php echo $patient['report_count'] > 0 ? 'with_reports' : 'without_reports'; ?>">
                            <td class="text-muted"><?php echo $i + 1; ?></td>
                            <td>
                                <div class="d-flex align-items-center gap-2">
                                    <div style="width:32px;height:32px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-weight:700;color:#fff;font-size:.85rem;flex-shrink:0;background:<?php echo $patient['gender']=='male'?'linear-gradient(135deg,#4299e1,#3182ce)':'linear-gradient(135deg,#ed64a6,#d53f8c)'; ?>">
                                        <?php echo strtoupper(mb_substr($patient['patient_name'], 0, 1)); ?>
                                    </div>
                                    <span class="fw-semibold"><?php echo htmlspecialchars($patient['patient_name']); ?></span>
                                </div>
                            </td>
                            <td><code><?php echo htmlspecialchars($patient['mrn']); ?></code></td>
                            <td>
                                <span class="gender-badge gender-<?php echo $patient['gender']; ?>">
                                    <?php echo $patient['gender'] == 'male' ? __('male') : __('female'); ?>
                                </span>
                            </td>
                            <td>
                                <?php
                                if (!empty($patient['units'])) {
                                    $units_arr = json_decode($patient['units'], true);
                                    if ($units_arr) {
                                        foreach (array_slice($units_arr, 0, 3) as $u) {
                                            echo '<span class="unit-badge">' . htmlspecialchars($u) . '</span>';
                                        }
                                        if (count($units_arr) > 3) echo '<span class="unit-badge">+' . (count($units_arr)-3) . '</span>';
                                    }
                                } else {
                                    echo '<span class="text-muted small">-</span>';
                                }
                                ?>
                            </td>
                            <td class="text-center">
                                <?php if ($patient['report_count'] > 0): ?>
                                <span class="badge bg-primary"><?php echo $patient['report_count']; ?></span>
                                <?php else: ?>
                                <span class="badge bg-light text-muted">0</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-muted small">
                                <?php echo $patient['last_report_date'] ? date('Y-m-d', strtotime($patient['last_report_date'])) : '<span class="text-muted">-</span>'; ?>
                            </td>
                            <td class="text-muted small"><?php echo date('Y-m-d', strtotime($patient['created_at'])); ?></td>
                            <td class="text-center no-print">
                                <div class="d-flex gap-1 justify-content-center">
                                    <?php if (PagePermissions::hasPermission($currentPage, 'view_patient_details')): ?>
                                    <a href="view_patient.php?id=<?php echo $patient['id']; ?>" class="btn btn-xs btn-outline-info py-0 px-2" title="<?php echo __('view'); ?>">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <?php endif; ?>
                                    <?php if (PagePermissions::hasPermission($currentPage, 'edit_patient')): ?>
                                    <a href="edit_patient.php?id=<?php echo $patient['id']; ?>" class="btn btn-xs btn-outline-warning py-0 px-2" title="<?php echo __('edit'); ?>">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <?php endif; ?>
                                    <?php if (PagePermissions::hasPermission($currentPage, 'delete_patient') && $patient['report_count'] == 0): ?>
                                    <button type="button" class="btn btn-xs btn-outline-danger py-0 px-2" title="<?php echo __('delete'); ?>"
                                            onclick="confirmDeletePatient(<?php echo (int)$patient['id']; ?>, '<?php echo htmlspecialchars(addslashes($patient['patient_name']), ENT_QUOTES); ?>')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <div class="px-3 py-2 text-muted small border-top">
                <?php echo __('total_records'); ?>: <strong id="visibleCount"><?php echo count($patients); ?></strong>
            </div>
            <?php endif; ?>
        </div>
    </div>

<script>
// Search & Filter
document.getElementById('searchPatients').addEventListener('input', filterPatients);
document.getElementById('genderFilter').addEventListener('change', filterPatients);
document.getElementById('reportsFilter').addEventListener('change', filterPatients);

function filterPatients() {
    const search  = document.getElementById('searchPatients').value.toLowerCase();
    const gender  = document.getElementById('genderFilter').value;
    const reports = document.getElementById('reportsFilter').value;
    const rows    = document.querySelectorAll('.patient-row');
    let visible   = 0;

    rows.forEach(row => {
        const matchSearch  = !search  || row.dataset.name.includes(search) || row.dataset.mrn.includes(search);
        const matchGender  = !gender  || row.dataset.gender  === gender;
        const matchReports = !reports || row.dataset.reports === reports;
        const show = matchSearch && matchGender && matchReports;
        row.style.display = show ? '' : 'none';
        if (show) visible++;
    });

    const cnt = document.getElementById('visibleCount');
    if (cnt) cnt.textContent = visible;
}

function clearFilters() {
    document.getElementById('searchPatients').value = '';
    document.getElementById('genderFilter').value   = '';
    document.getElementById('reportsFilter').value  = '';
    filterPatients();
}

function confirmDeletePatient(patientId, patientName) {
    if (!patientId || isNaN(patientId)) {
        alert('خطأ: معرف المريض غير صحيح');
        return;
    }
    var msg = patientName 
        ? 'هل أنت متأكد من حذف المريض: ' + patientName + '؟\nلا يمكن التراجع عن هذا الإجراء!'
        : 'هل أنت متأكد من حذف هذا المريض؟\nلا يمكن التراجع عن هذا الإجراء!';
    if (confirm(msg)) {
        window.location.href = 'manage_patients.php?action=delete&id=' + parseInt(patientId);
    }
}

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

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