<?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 = 'monitoring';

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

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

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

$success_message = '';
$error_message = '';

// ============================================================
// CRUD Operations
// ============================================================

// --- ADD simple monitoring record ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_simple') {
    try {
        $patient_name  = trim($_POST['patient_name'] ?? '');
        $mrn           = trim($_POST['mrn'] ?? '');
        $report_date   = $_POST['report_date'] ?? date('Y-m-d');
        $consultant    = trim($_POST['consultant_name'] ?? '');
        $location      = trim($_POST['location'] ?? '');
        $notes         = trim($_POST['notes'] ?? '');

        if (empty($patient_name) || empty($mrn)) {
            throw new Exception('اسم المريض والرقم الطبي مطلوبان');
        }

        // Get or create patient
        $stmt = $conn->prepare("SELECT id FROM patients WHERE mrn = ?");
        $stmt->execute([$mrn]);
        $existing = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($existing) {
            $patient_id = $existing['id'];
        } else {
            $stmt = $conn->prepare("INSERT INTO patients (patient_name, mrn, created_by) VALUES (?, ?, ?)");
            $stmt->execute([$patient_name, $mrn, $_SESSION['user_id']]);
            $patient_id = $conn->lastInsertId();
        }

        $stmt = $conn->prepare("INSERT INTO simple_patient_monitoring 
            (patient_id, report_date, consultant_name, location, notes, created_by) 
            VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$patient_id, $report_date, $consultant, $location, $notes, $_SESSION['user_id']]);

        $success_message = 'تم إضافة السجل بنجاح';
    } catch (Exception $e) {
        $error_message = 'خطأ: ' . $e->getMessage();
    }
}

// --- EDIT simple monitoring record ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit_simple') {
    try {
        $id          = (int)$_POST['record_id'];
        $report_date = $_POST['report_date'] ?? date('Y-m-d');
        $consultant  = trim($_POST['consultant_name'] ?? '');
        $location    = trim($_POST['location'] ?? '');
        $notes       = trim($_POST['notes'] ?? '');

        $stmt = $conn->prepare("UPDATE simple_patient_monitoring 
            SET report_date=?, consultant_name=?, location=?, notes=? 
            WHERE id=?");
        $stmt->execute([$report_date, $consultant, $location, $notes, $id]);

        $success_message = 'تم تعديل السجل بنجاح';
    } catch (Exception $e) {
        $error_message = 'خطأ: ' . $e->getMessage();
    }
}

// --- DELETE simple monitoring record ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_simple') {
    try {
        $id = (int)$_POST['record_id'];
        $stmt = $conn->prepare("DELETE FROM simple_patient_monitoring WHERE id=?");
        $stmt->execute([$id]);
        $success_message = 'تم حذف السجل بنجاح';
    } catch (Exception $e) {
        $error_message = 'خطأ: ' . $e->getMessage();
    }
}

// --- DELETE antibiotic report ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_antibiotic') {
    try {
        $id = (int)$_POST['record_id'];
        $stmt = $conn->prepare("DELETE FROM antibiotic_reports WHERE id=?");
        $stmt->execute([$id]);
        $success_message = 'تم حذف التقرير بنجاح';
    } catch (Exception $e) {
        $error_message = 'خطأ: ' . $e->getMessage();
    }
}

// Get monitoring data - combining reports with patient and antibiotic info
$stmt = $conn->prepare("
    SELECT 
        ar.id,
        ar.report_date,
        p.patient_name,
        p.mrn as medical_no,
        COALESCE(a.antibiotic_name, ar.other_medication_name, 'غير محدد') as antibiotic_name,
        ar.status as approval_status,
        ar.problem_authority as indication,
        ar.intervention_choice as adjustment,
        usr.full_name as consultant_name,
        u.unit_name as location
    FROM antibiotic_reports ar
    JOIN patients p ON ar.patient_id = p.id
    LEFT JOIN antibiotics a ON ar.antibiotic_id = a.id
    JOIN users usr ON ar.reporting_pharmacist_id = usr.id
    JOIN units u ON ar.unit_id = u.id
    WHERE ar.drug_type = 'antibiotic'
    ORDER BY ar.report_date DESC, ar.created_at DESC
");
$stmt->execute();
$antibiotic_monitoring_data = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get simple monitoring data - patients without antibiotics + other drug reports
$stmt = $conn->prepare("
    SELECT 
        spm.id,
        spm.report_date,
        p.patient_name,
        p.mrn as medical_no,
        spm.consultant_name,
        spm.location,
        spm.notes,
        usr.full_name as pharmacist_name,
        'simple' as source
    FROM simple_patient_monitoring spm
    JOIN patients p ON spm.patient_id = p.id
    JOIN users usr ON spm.created_by = usr.id
    
    UNION ALL
    
    SELECT 
        ar.id,
        ar.report_date,
        p.patient_name,
        p.mrn as medical_no,
        ar.problem_authority_name as consultant_name,
        u.unit_name as location,
        CONCAT('دواء: ', ar.other_medication_name, ' | توصية: ', ar.recommendations) as notes,
        usr.full_name as pharmacist_name,
        'antibiotic_reports' as source
    FROM antibiotic_reports ar
    JOIN patients p ON ar.patient_id = p.id
    JOIN users usr ON ar.reporting_pharmacist_id = usr.id
    JOIN units u ON ar.unit_id = u.id
    WHERE ar.drug_type = 'other'
    
    ORDER BY report_date DESC
");
$stmt->execute();
$simple_monitoring_data = $stmt->fetchAll(PDO::FETCH_ASSOC);

include 'includes/header.php';
?>

<style>
.toggle-buttons {
    display: flex;
    justify-content: center;
    margin-bottom: 30px;
    gap: 10px;
}

.toggle-btn {
    background: #f8f9fa;
    border: 2px solid #dee2e6;
    color: #495057;
    padding: 15px 30px;
    border-radius: 25px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 16px;
}

.toggle-btn.active {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-color: #667eea;
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.toggle-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.content-section {
    display: none !important;
}

.content-section.active {
    display: block !important;
}

.card {
    border: none;
    border-radius: 15px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    transition: all 0.3s ease;
}

.card-header {
    border-radius: 15px 15px 0 0 !important;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
}

.action-btn {
    border-radius: 8px;
    padding: 8px 16px;
    font-weight: 600;
    margin: 3px;
    transition: all 0.3s ease;
    font-size: 0.875rem;
    white-space: nowrap;
}

.action-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

.monitoring-table {
    font-size: 0.9rem;
}

.monitoring-table th {
    background-color: #f8f9fa;
    font-weight: 600;
    text-align: center;
    vertical-align: middle;
    border: 1px solid #dee2e6;
    padding: 12px 8px;
}

.monitoring-table td {
    text-align: center;
    vertical-align: middle;
    border: 1px solid #dee2e6;
    padding: 10px 8px;
}

.status-approved {
    background-color: #d4edda;
    color: #155724;
    font-weight: bold;
}

.status-pending {
    background-color: #fff3cd;
    color: #856404;
    font-weight: bold;
}

.status-rejected {
    background-color: #f8d7da;
    color: #721c24;
    font-weight: bold;
}

@media print {
    .no-print { display: none; }
    .monitoring-table { font-size: 0.8rem; }
    .monitoring-table th, .monitoring-table td { padding: 6px 4px; }
}

@media (max-width: 768px) {
    .monitoring-table { font-size: 0.8rem; }
    .monitoring-table th, .monitoring-table td { padding: 8px 4px; }
}
</style>


    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4 no-print flex-wrap gap-2">
        <div>
            <h1 class="h3 mb-0" style="color: #667eea;">
                <i class="fas fa-table me-2"></i>
                <?php echo __('monitoring_management_title'); ?>
            </h1>
            <p class="text-muted mb-0"><?php echo __('monitoring_management_subtitle'); ?></p>
        </div>
        <div class="d-flex flex-wrap align-items-center gap-2">
            <?php if (PagePermissions::hasPermission($currentPage, 'print_monitoring')): ?>
            <div class="dropdown d-inline-block">
                <button class="btn btn-outline-primary action-btn dropdown-toggle" type="button" data-bs-toggle="dropdown">
                    <i class="fas fa-print me-2"></i> <?php echo __('print'); ?>
                </button>
                <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="#" onclick="printWithData()">
                        <i class="fas fa-table me-2"></i> <?php echo __('print_with_data'); ?>
                    </a></li>
                    <li><a class="dropdown-item" href="#" onclick="showEmptyTableModal()">
                        <i class="fas fa-table me-2"></i> <?php echo __('print_empty_table'); ?>
                    </a></li>
                </ul>
            </div>
            <?php endif; ?>
            
            <?php if (PagePermissions::hasPermission($currentPage, 'export_monitoring_excel')): ?>
            <div class="dropdown d-inline-block">
                <button class="btn btn-outline-success action-btn dropdown-toggle" type="button" data-bs-toggle="dropdown">
                    <i class="fas fa-file-excel me-2"></i> <?php echo __('export_excel'); ?>
                </button>
                <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="#" onclick="exportToExcel('with-data')">
                        <i class="fas fa-download me-2"></i> <?php echo __('export_with_data'); ?>
                    </a></li>
                    <li><a class="dropdown-item" href="#" onclick="showExcelEmptyModal()">
                        <i class="fas fa-file me-2"></i> <?php echo __('export_empty_table'); ?>
                    </a></li>
                </ul>
            </div>
            <?php endif; ?>
            
            <a href="key_performance_indicators.php" class="btn btn-info action-btn">
                <i class="fas fa-tablets me-2"></i> <?php echo __('patient_medication_table'); ?>
            </a>
            <a href="index.php" class="btn btn-outline-secondary action-btn">
                <i class="fas fa-arrow-<?php echo Translation::getDirection() == 'rtl' ? 'right' : 'left'; ?> me-2"></i> <?php echo __('back'); ?>
            </a>
        </div>
    </div>

    <!-- Success / Error Messages -->
    <?php if ($success_message): ?>
    <div class="alert alert-success alert-dismissible fade show no-print">
        <i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars($success_message); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    <?php if ($error_message): ?>
    <div class="alert alert-danger alert-dismissible fade show no-print">
        <i class="fas fa-exclamation-circle me-2"></i><?php echo htmlspecialchars($error_message); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <!-- Toggle Buttons -->
    <div class="toggle-buttons no-print">
        <?php if (PagePermissions::hasPermission($currentPage, 'view_monitoring')): ?>
        <button class="toggle-btn active" onclick="showSection('antibiotic', this)">
            <i class="fas fa-pills me-2"></i>
            <?php echo __('antibiotic_monitoring_table'); ?>
        </button>
        <button class="toggle-btn" onclick="showSection('simple', this)">
            <i class="fas fa-clipboard-list me-2"></i>
            <?php echo __('simple_monitoring'); ?>
        </button>
        <?php endif; ?>
    </div>

    <!-- Antibiotic Monitoring Section -->
    <div id="antibiotic-section" class="content-section active">
        <div class="card">
            <div class="card-header text-white text-center">
                <h3 class="mb-0"><?php echo __('antibiotic_monitoring_table'); ?></h3>
                <small>Antibiotic Monitoring Table</small>
            </div>
            
            <div class="card-body">
                <!-- زر إضافة تقرير جديد -->
                <?php if (PagePermissions::hasPermission($currentPage, 'add_monitoring')): ?>
                <div class="mb-3 no-print">
                    <a href="clinical_pharmacy_intervention.php" class="btn btn-success">
                        <i class="fas fa-plus me-1"></i> <?php echo Translation::getLanguage() === 'ar' ? 'إضافة تقرير جديد' : 'Add New Report'; ?>
                    </a>
                </div>
                <?php endif; ?>

                <?php if (count($antibiotic_monitoring_data) > 0): ?>
                <div class="table-responsive">
                    <table class="table monitoring-table table-bordered">
                        <thead>
                            <tr>
                                <th rowspan="2"><?php echo __('date'); ?><br><small>Date</small></th>
                                <th rowspan="2"><?php echo __('patient_name'); ?><br><small>Patient Name</small></th>
                                <th rowspan="2"><?php echo __('medical_no'); ?><br><small>Medical No.</small></th>
                                <th rowspan="2"><?php echo __('antibiotic'); ?><br><small>Antibiotic</small></th>
                                <th colspan="3"><?php echo __('approval'); ?><br><small>Approval</small></th>
                                <th rowspan="2"><?php echo __('indication'); ?><br><small>Indication</small></th>
                                <th rowspan="2"><?php echo __('adjustment'); ?><br><small>Adjustment</small></th>
                                <th rowspan="2"><?php echo __('consultant'); ?><br><small>Consultant</small></th>
                                <th rowspan="2"><?php echo __('location'); ?><br><small>Location</small></th>
                                <th rowspan="2" class="no-print"><?php echo __('actions'); ?></th>
                            </tr>
                            <tr>
                                <th><?php echo __('approved'); ?><br><small>Approved</small></th>
                                <th><?php echo __('pending'); ?><br><small>Pending</small></th>
                                <th><?php echo __('rejected'); ?><br><small>Rejected</small></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($antibiotic_monitoring_data as $row): ?>
                            <tr>
                                <td><?php echo formatArabicDate($row['report_date']); ?></td>
                                <td><?php echo htmlspecialchars($row['patient_name']); ?></td>
                                <td><?php echo htmlspecialchars($row['medical_no']); ?></td>
                                <td><?php echo htmlspecialchars($row['antibiotic_name']); ?></td>
                                <td class="<?php echo $row['approval_status'] == 'approved' ? 'status-approved' : ''; ?>">
                                    <?php echo $row['approval_status'] == 'approved' ? '✓' : ''; ?>
                                </td>
                                <td class="<?php echo $row['approval_status'] == 'pending' ? 'status-pending' : ''; ?>">
                                    <?php echo $row['approval_status'] == 'pending' ? '⏳' : ''; ?>
                                </td>
                                <td class="<?php echo $row['approval_status'] == 'rejected' ? 'status-rejected' : ''; ?>">
                                    <?php echo $row['approval_status'] == 'rejected' ? '✗' : ''; ?>
                                </td>
                                <td><?php echo htmlspecialchars($row['indication']); ?></td>
                                <td><?php echo htmlspecialchars($row['adjustment']); ?></td>
                                <td><?php echo htmlspecialchars($row['consultant_name']); ?></td>
                                <td><?php echo htmlspecialchars($row['location']); ?></td>
                                <td class="no-print">
                                    <a href="edit_report.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-warning mb-1">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('<?php echo Translation::getLanguage() === 'ar' ? 'هل أنت متأكد من الحذف؟' : 'Are You Sure You Want To Delete?'; ?>')">
                                        <input type="hidden" name="action" value="delete_antibiotic">
                                        <input type="hidden" name="record_id" value="<?php echo $row['id']; ?>">
                                        <button type="submit" class="btn btn-sm btn-danger">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <div class="text-center py-5">
                    <i class="fas fa-pills fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted"><?php echo __('no_monitoring_data'); ?></h5>
                    <p class="text-muted"><?php echo __('no_antibiotic_reports_created'); ?></p>
                    <a href="clinical_pharmacy_intervention.php" class="btn btn-primary">
                        <i class="fas fa-plus me-1"></i> <?php echo __('create_new_report'); ?>
                    </a>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Simple Monitoring Section -->
    <div id="simple-section" class="content-section">
        <div class="card">
            <div class="card-header text-white text-center">
                <h3 class="mb-0"><?php echo __('patient_monitoring_table'); ?></h3>
                <small>Patient Monitoring Table</small>
            </div>
            
            <div class="card-body">
                <!-- زر إضافة سجل جديد -->
                <?php if (PagePermissions::hasPermission($currentPage, 'add_monitoring')): ?>
                <div class="mb-3 no-print">
                    <button class="btn btn-success" type="button" data-bs-toggle="collapse" data-bs-target="#addSimpleForm">
                        <i class="fas fa-plus me-1"></i> <?php echo Translation::getLanguage() === 'ar' ? 'إضافة سجل جديد' : 'Add New Record'; ?>
                    </button>
                </div>

                <!-- فورم الإضافة -->
                <div class="collapse mb-4 no-print" id="addSimpleForm">
                    <div class="card card-body border-success">
                        <h6 class="text-success mb-3"><i class="fas fa-plus-circle me-1"></i> <?php echo Translation::getLanguage() === 'ar' ? 'إضافة سجل متابعة جديد' : 'Add New Monitoring Record'; ?></h6>
                        <form method="POST">
                            <input type="hidden" name="action" value="add_simple">
                            <div class="row g-3">
                                <div class="col-md-3">
                                    <label class="form-label"><?php echo Translation::getLanguage() === 'ar' ? 'اسم المريض *' : 'Patient Name *'; ?></label>
                                    <input type="text" name="patient_name" class="form-control" required>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label"><?php echo Translation::getLanguage() === 'ar' ? 'الرقم الطبي *' : 'Medical No. *'; ?></label>
                                    <input type="text" name="mrn" class="form-control" required>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label"><?php echo Translation::getLanguage() === 'ar' ? 'التاريخ' : 'Date'; ?></label>
                                    <input type="date" name="report_date" class="form-control" value="<?php echo date('Y-m-d'); ?>">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label"><?php echo Translation::getLanguage() === 'ar' ? 'الطبيب المعالج' : 'Consultant'; ?></label>
                                    <input type="text" name="consultant_name" class="form-control">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label"><?php echo Translation::getLanguage() === 'ar' ? 'الموقع' : 'Location'; ?></label>
                                    <input type="text" name="location" class="form-control">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label"><?php echo Translation::getLanguage() === 'ar' ? 'الملاحظات' : 'Notes'; ?></label>
                                    <input type="text" name="notes" class="form-control">
                                </div>
                                <div class="col-md-2 d-flex align-items-end">
                                    <button type="submit" class="btn btn-success w-100">
                                        <i class="fas fa-save me-1"></i> <?php echo Translation::getLanguage() === 'ar' ? 'حفظ' : 'Save'; ?>
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <?php endif; ?>

                <?php if (count($simple_monitoring_data) > 0): ?>
                <div class="table-responsive">
                    <table class="table monitoring-table table-bordered">
                        <thead>
                            <tr>
                                <th><?php echo __('date'); ?><br><small>Date</small></th>
                                <th><?php echo __('patient_name'); ?><br><small>Patient Name</small></th>
                                <th><?php echo __('medical_no'); ?><br><small>Medical No.</small></th>
                                <th><?php echo __('consultant'); ?><br><small>Consultant</small></th>
                                <th><?php echo __('location'); ?><br><small>Location</small></th>
                                <th><?php echo __('notes'); ?><br><small>Notes</small></th>
                                <th><?php echo __('pharmacist'); ?><br><small>Pharmacist</small></th>
                                <th class="no-print"><?php echo __('actions'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($simple_monitoring_data as $row): ?>
                            <tr>
                                <td><?php echo formatArabicDate($row['report_date']); ?></td>
                                <td><?php echo htmlspecialchars($row['patient_name']); ?></td>
                                <td><?php echo htmlspecialchars($row['medical_no']); ?></td>
                                <td><?php echo htmlspecialchars($row['consultant_name']); ?></td>
                                <td><?php echo htmlspecialchars($row['location']); ?></td>
                                <td><?php echo htmlspecialchars($row['notes']); ?></td>
                                <td><?php echo htmlspecialchars($row['pharmacist_name']); ?></td>
                                <td class="no-print" style="white-space:nowrap;">
                                    <?php if ($row['source'] === 'simple'): ?>
                                        <!-- زر تعديل للسجل البسيط -->
                                        <button class="btn btn-sm btn-warning mb-1"
                                            onclick="openEditModal(<?php echo $row['id']; ?>, '<?php echo addslashes($row['report_date']); ?>', '<?php echo addslashes($row['consultant_name']); ?>', '<?php echo addslashes($row['location']); ?>', '<?php echo addslashes($row['notes']); ?>')">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <!-- زر حذف للسجل البسيط -->
                                        <form method="POST" style="display:inline;" onsubmit="return confirm('<?php echo Translation::getLanguage() === 'ar' ? 'هل أنت متأكد من الحذف؟' : 'Are You Sure You Want To Delete?'; ?>')">
                                            <input type="hidden" name="action" value="delete_simple">
                                            <input type="hidden" name="record_id" value="<?php echo $row['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-danger">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <!-- زر تعديل لتقرير الأدوية الأخرى -->
                                        <a href="edit_report.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-warning mb-1">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <!-- زر حذف لتقرير الأدوية الأخرى -->
                                        <form method="POST" style="display:inline;" onsubmit="return confirm('<?php echo Translation::getLanguage() === 'ar' ? 'هل أنت متأكد من الحذف؟' : 'Are You Sure You Want To Delete?'; ?>')">
                                            <input type="hidden" name="action" value="delete_antibiotic">
                                            <input type="hidden" name="record_id" value="<?php echo $row['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-danger">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <div class="text-center py-5">
                    <i class="fas fa-clipboard-list fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted"><?php echo __('no_monitoring_data'); ?></h5>
                    <p class="text-muted"><?php echo __('no_patient_monitoring_records'); ?></p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Edit Simple Monitoring Modal -->
<div class="modal fade" id="editSimpleModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-warning text-dark">
                <h5 class="modal-title"><i class="fas fa-edit me-2"></i> <?php echo Translation::getLanguage() === 'ar' ? 'تعديل سجل المتابعة' : 'Edit Monitoring Record'; ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="edit_simple">
                <input type="hidden" name="record_id" id="edit_record_id">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label"><?php echo Translation::getLanguage() === 'ar' ? 'التاريخ' : 'Date'; ?></label>
                            <input type="date" name="report_date" id="edit_report_date" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><?php echo Translation::getLanguage() === 'ar' ? 'الطبيب المعالج' : 'Consultant'; ?></label>
                            <input type="text" name="consultant_name" id="edit_consultant_name" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><?php echo Translation::getLanguage() === 'ar' ? 'الموقع' : 'Location'; ?></label>
                            <input type="text" name="location" id="edit_location" class="form-control">
                        </div>
                        <div class="col-12">
                            <label class="form-label"><?php echo Translation::getLanguage() === 'ar' ? 'الملاحظات' : 'Notes'; ?></label>
                            <textarea name="notes" id="edit_notes" class="form-control" rows="3"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo Translation::getLanguage() === 'ar' ? 'إلغاء' : 'Cancel'; ?></button>
                    <button type="submit" class="btn btn-warning"><i class="fas fa-save me-1"></i> <?php echo Translation::getLanguage() === 'ar' ? 'حفظ التعديلات' : 'Save Changes'; ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Empty Table Modal -->
<div class="modal fade" id="emptyTableModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo __('print_empty_table'); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <label class="form-label"><?php echo __('table_type'); ?></label>
                        <select class="form-select" id="emptyTableType">
                            <option value="antibiotic"><?php echo __('antibiotic_monitoring_table'); ?></option>
                            <option value="simple"><?php echo __('patient_monitoring_table'); ?></option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label"><?php echo __('number_of_rows'); ?></label>
                        <input type="number" class="form-control" id="emptyTableRows" value="10" min="1" max="50">
                    </div>
                </div>
            </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-primary" onclick="printEmptyTable()"><?php echo __('print'); ?></button>
            </div>
        </div>
    </div>
</div>

<!-- Excel Empty Modal -->
<div class="modal fade" id="excelEmptyModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo __('export_empty_table_excel'); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label"><?php echo __('table_type'); ?></label>
                    <select class="form-select" id="excelEmptyTableType">
                        <option value="antibiotic"><?php echo __('antibiotic_monitoring_table'); ?></option>
                        <option value="simple"><?php echo __('patient_monitoring_table'); ?></option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label"><?php echo __('number_of_rows'); ?></label>
                    <input type="number" class="form-control" id="excelEmptyTableRows" value="20" min="1" max="100">
                </div>
            </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-success" onclick="exportEmptyToExcel()"><?php echo __('export'); ?></button>
            </div>
        </div>
    </div>
</div>

<script>
function showSection(section, btn) {
    // Hide all sections
    document.querySelectorAll('.content-section').forEach(function(el) {
        el.style.display = 'none';
        el.classList.remove('active');
    });
    
    // Remove active class from all buttons
    document.querySelectorAll('.toggle-btn').forEach(function(b) {
        b.classList.remove('active');
    });
    
    // Show selected section
    var target = document.getElementById(section + '-section');
    if (target) {
        target.style.display = 'block';
        target.classList.add('active');
    }
    
    // Add active class to clicked button
    if (btn) btn.classList.add('active');
}

// Open edit modal for simple monitoring
function openEditModal(id, report_date, consultant_name, location, notes) {
    document.getElementById('edit_record_id').value = id;
    document.getElementById('edit_report_date').value = report_date;
    document.getElementById('edit_consultant_name').value = consultant_name;
    document.getElementById('edit_location').value = location;
    document.getElementById('edit_notes').value = notes;
    new bootstrap.Modal(document.getElementById('editSimpleModal')).show();
}

// Print functions
function printWithData() {
    window.print();
}

function showEmptyTableModal() {
    const modal = new bootstrap.Modal(document.getElementById('emptyTableModal'));
    modal.show();
}

// Excel Export Functions
function showExcelEmptyModal() {
    const modal = new bootstrap.Modal(document.getElementById('excelEmptyModal'));
    modal.show();
}

function printEmptyTable() {
    const tableType = document.getElementById('emptyTableType').value;
    const rows = parseInt(document.getElementById('emptyTableRows').value);
    
    const printWindow = window.open('', '_blank');
    const tableHtml = generateEmptyTableHtml(tableType, rows);
    
    printWindow.document.write(`
        <!DOCTYPE html>
        <html dir="rtl" lang="ar">
        <head>
            <meta charset="UTF-8">
            <title>جدول فارغ للطباعة</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                .header { text-align: center; margin-bottom: 30px; }
                .table { width: 100%; border-collapse: collapse; font-size: 12px; }
                .table th, .table td { border: 1px solid #000; padding: 8px; text-align: center; }
                .table th { background-color: #f0f0f0; font-weight: bold; }
                @media print {
                    body { margin: 0; }
                    .table { font-size: 10px; }
                    .table th, .table td { padding: 6px 4px; }
                }
            </style>
        </head>
        <body>
            <div class="header">
                <h2>${tableType === 'antibiotic' ? 'جدول مراقبة المضادات الحيوية' : 'جدول متابعة المرضى'}</h2>
                <p>التاريخ: ${new Date().toLocaleDateString('ar-EG')}</p>
            </div>
            ${tableHtml}
        </body>
        </html>
    `);
    
    printWindow.document.close();
    printWindow.print();
    
    // Close modal
    bootstrap.Modal.getInstance(document.getElementById('emptyTableModal')).hide();
}

function generateEmptyTableHtml(tableType, rows) {
    let headerHtml = '';
    
    if (tableType === 'antibiotic') {
        headerHtml = `
            <tr>
                <th rowspan="2">التاريخ<br><small>Date</small></th>
                <th rowspan="2">اسم المريض<br><small>Patient Name</small></th>
                <th rowspan="2">الرقم الطبي<br><small>Medical No.</small></th>
                <th rowspan="2">المضاد الحيوي<br><small>Antibiotic</small></th>
                <th colspan="3">الموافقة<br><small>Approval</small></th>
                <th rowspan="2">المؤشر<br><small>Indication</small></th>
                <th rowspan="2">التعديل<br><small>Adjustment</small></th>
                <th rowspan="2">الطبيب المعالج<br><small>Consultant</small></th>
                <th rowspan="2">الموقع<br><small>Location</small></th>
            </tr>
            <tr>
                <th>موافق<br><small>Approved</small></th>
                <th>معلق<br><small>Pending</small></th>
                <th>مرفوض<br><small>Rejected</small></th>
            </tr>
        `;
    } else {
        headerHtml = `
            <tr>
                <th>التاريخ<br><small>Date</small></th>
                <th>اسم المريض<br><small>Patient Name</small></th>
                <th>الرقم الطبي<br><small>Medical No.</small></th>
                <th>الطبيب المعالج<br><small>Consultant</small></th>
                <th>الموقع<br><small>Location</small></th>
                <th>الملاحظات<br><small>Notes</small></th>
                <th>الصيدلي<br><small>Pharmacist</small></th>
            </tr>
        `;
    }
    
    let bodyHtml = '';
    const cellCount = tableType === 'antibiotic' ? 11 : 7;
    
    for (let i = 0; i < rows; i++) {
        bodyHtml += '<tr>';
        for (let j = 0; j < cellCount; j++) {
            bodyHtml += '<td style="height: 40px;">&nbsp;</td>';
        }
        bodyHtml += '</tr>';
    }
    
    return `
        <table class="table">
            <thead>${headerHtml}</thead>
            <tbody>${bodyHtml}</tbody>
        </table>
    `;
}

// Excel Export Functions
function exportToExcel(type) {
    const activeSection = document.querySelector('.content-section.active');
    const tableType = activeSection.id === 'antibiotic-section' ? 'antibiotic' : 'simple';
    
    // Create form and submit
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = 'export/monitoring_excel.php';
    
    const typeInput = document.createElement('input');
    typeInput.type = 'hidden';
    typeInput.name = 'export_type';
    typeInput.value = type;
    
    const tableTypeInput = document.createElement('input');
    tableTypeInput.type = 'hidden';
    tableTypeInput.name = 'table_type';
    tableTypeInput.value = tableType;
    
    form.appendChild(typeInput);
    form.appendChild(tableTypeInput);
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

function exportEmptyToExcel() {
    const tableType = document.getElementById('excelEmptyTableType').value;
    const rows = document.getElementById('excelEmptyTableRows').value;
    
    // Create form and submit
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = 'export/monitoring_excel.php';
    
    const typeInput = document.createElement('input');
    typeInput.type = 'hidden';
    typeInput.name = 'export_type';
    typeInput.value = 'empty';
    
    const tableTypeInput = document.createElement('input');
    tableTypeInput.type = 'hidden';
    tableTypeInput.name = 'table_type';
    tableTypeInput.value = tableType;
    
    const rowsInput = document.createElement('input');
    rowsInput.type = 'hidden';
    rowsInput.name = 'empty_rows';
    rowsInput.value = rows;
    
    form.appendChild(typeInput);
    form.appendChild(tableTypeInput);
    form.appendChild(rowsInput);
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
    
    // Close modal
    bootstrap.Modal.getInstance(document.getElementById('excelEmptyModal')).hide();
}
</script>

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