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

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

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

$message = '';
$error = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';
    
    try {
        switch($action) {
            case 'add_antibiotic':
                $antibiotic_name = sanitizeInput($_POST['antibiotic_name']);
                $generic_name = sanitizeInput($_POST['generic_name']);
                $category = sanitizeInput($_POST['category']);
                $dosage_forms = sanitizeInput($_POST['dosage_forms']);
                $strength = sanitizeInput($_POST['strength']);
                $route = sanitizeInput($_POST['route']);
                $indication = sanitizeInput($_POST['indication']);
                $contraindications = sanitizeInput($_POST['contraindications'] ?? '');
                $side_effects = sanitizeInput($_POST['side_effects'] ?? '');
                
                $stmt = $conn->prepare("
                    INSERT INTO antibiotics (antibiotic_name, generic_name, category, dosage_form, strength, indication, contraindications, side_effects)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([$antibiotic_name, $generic_name, $category, $dosage_forms, $strength, $indication, $contraindications, $side_effects]);
                
                logActivity($conn, $_SESSION['user_id'], __('add_antibiotic_activity'), 'antibiotics', $conn->lastInsertId());
                $message = __('antibiotic_added_successfully');
                break;
                
            case 'toggle_status':
                $antibiotic_id = intval($_POST['antibiotic_id']);
                $new_status = $_POST['status'] == 'active' ? 1 : 0;
                
                $stmt = $conn->prepare("UPDATE antibiotics SET is_active = ? WHERE id = ?");
                $stmt->execute([$new_status, $antibiotic_id]);
                
                logActivity($conn, $_SESSION['user_id'], __('change_antibiotic_status_activity'), 'antibiotics', $antibiotic_id);
                $message = __('antibiotic_status_updated');
                break;
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

// Get all antibiotics
$antibiotics = [];
try {
    $stmt = $conn->query("
        SELECT a.*, 
               (SELECT COUNT(*) FROM antibiotic_reports WHERE antibiotic_id = a.id) as usage_count
        FROM antibiotics a
        ORDER BY a.created_at DESC
    ");
    $antibiotics = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $error = __('error_fetching_antibiotics') . ': ' . $e->getMessage();
}

$page_title = __('antibiotic_management') . ' - ' . __('system_name');
include 'includes/header.php';
?>


    <div class="header no-print">
        <div>
            <h1 class="h3 mb-0"><?php echo __('antibiotic_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_antibiotic')): ?>
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addAntibioticModal">
                <i class="fas fa-plus"></i> <?php echo __('add_new_antibiotic'); ?>
            </button>
            <?php endif; ?>
            
            <?php if (PagePermissions::hasPermission($currentPage, 'export_antibiotics_excel')): ?>
            <button type="button" class="btn btn-success" onclick="exportAntibioticsToExcel()">
                <i class="fas fa-file-excel"></i> <?php echo __('export_excel'); ?>
            </button>
            <?php endif; ?>
            
            <a href="key_performance_indicators.php" class="btn btn-info">
                <i class="fas fa-tablets"></i> <?php echo __('patient_medication_table'); ?>
            </a>
        </div>
    </div>

    <!-- Statistics Overview -->
    <div class="row g-4 mb-5">
        <div class="col-xl-3 col-md-6">
            <div class="stat-box blue">
                <div class="stat-number"><?php echo count($antibiotics); ?></div>
                <div class="stat-label"><?php echo __('total_antibiotics'); ?></div>
                <i class="fas fa-pills stat-icon"></i>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="stat-box green">
                <div class="stat-number"><?php echo count(array_filter($antibiotics, function($a) { return $a['is_active']; })); ?></div>
                <div class="stat-label"><?php echo __('active_antibiotics'); ?></div>
                <i class="fas fa-check-circle stat-icon"></i>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="stat-box orange">
                <div class="stat-number"><?php echo count(array_filter($antibiotics, function($a) { return !$a['is_active']; })); ?></div>
                <div class="stat-label"><?php echo __('inactive_antibiotics'); ?></div>
                <i class="fas fa-pause-circle stat-icon"></i>
            </div>
        </div>
        <div class="col-xl-3 col-md-6">
            <div class="stat-box purple">
                <div class="stat-number">
                    <?php 
                    $max_usage = 0;
                    foreach ($antibiotics as $antibiotic) {
                        if ($antibiotic['usage_count'] > $max_usage) {
                            $max_usage = $antibiotic['usage_count'];
                        }
                    }
                    echo $max_usage;
                    ?>
                </div>
                <div class="stat-label"><?php echo __('most_used_count'); ?></div>
                <i class="fas fa-chart-bar stat-icon"></i>
            </div>
        </div>
    </div>

    <!-- Antibiotics Table -->
    <div class="card shadow">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary"><?php echo __('antibiotics_list'); ?></h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered" id="antibioticsTable" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th><?php echo __('antibiotic_name'); ?></th>
                            <th><?php echo __('generic_name'); ?></th>
                            <th><?php echo __('category'); ?></th>
                            <th><?php echo __('dosage_form'); ?></th>
                            <th><?php echo __('strength'); ?></th>
                            <th><?php echo __('route'); ?></th>
                            <th><?php echo __('usage_count'); ?></th>
                            <th><?php echo __('status'); ?></th>
                            <th><?php echo __('actions'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($antibiotics as $antibiotic): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($antibiotic['antibiotic_name'] ?? __('not_specified')); ?></td>
                            <td><?php echo htmlspecialchars($antibiotic['generic_name'] ?? __('not_specified')); ?></td>
                            <td><?php echo htmlspecialchars($antibiotic['category'] ?? __('not_specified')); ?></td>
                            <td><?php echo htmlspecialchars($antibiotic['dosage_form'] ?? $antibiotic['dosage_forms'] ?? __('not_specified')); ?></td>
                            <td><?php echo htmlspecialchars($antibiotic['strength'] ?? __('not_specified')); ?></td>
                            <td>-</td>
                            <td>
                                <span class="badge bg-info"><?php echo $antibiotic['usage_count'] ?? 0; ?></span>
                            </td>
                            <td>
                                <span class="badge bg-<?php echo $antibiotic['is_active'] ? 'success' : 'secondary'; ?>">
                                    <?php echo $antibiotic['is_active'] ? __('active') : __('inactive'); ?>
                                </span>
                            </td>
                            <td>
                                <div class="btn-group" role="group">
                                    <?php if (PagePermissions::hasPermission($currentPage, 'view_antibiotics')): ?>
                                    <button type="button" 
                                            class="btn btn-sm btn-info" 
                                            data-bs-toggle="modal" 
                                            data-bs-target="#viewAntibioticModal<?php echo $antibiotic['id']; ?>"
                                            title="<?php echo __('view_details'); ?>">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <?php endif; ?>
                                    
                                    <?php if (PagePermissions::hasPermission($currentPage, 'edit_antibiotic')): ?>
                                    <a href="edit_antibiotic.php?id=<?php echo $antibiotic['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, 'toggle_antibiotic_status')): ?>
                                    <button type="button" 
                                            class="btn btn-sm btn-<?php echo $antibiotic['is_active'] ? 'secondary' : 'success'; ?>" 
                                            onclick="toggleAntibioticStatus(<?php echo $antibiotic['id']; ?>, '<?php echo $antibiotic['is_active'] ? 'inactive' : 'active'; ?>')"
                                            title="<?php echo $antibiotic['is_active'] ? __('deactivate') : __('activate'); ?>">
                                        <i class="fas fa-<?php echo $antibiotic['is_active'] ? 'pause' : 'play'; ?>"></i>
                                    </button>
                                    <?php endif; ?>
                                    
                                    <?php if (PagePermissions::hasPermission($currentPage, 'delete_antibiotic')): ?>
                                    <button type="button" 
                                            class="btn btn-sm btn-danger" 
                                            onclick="deleteAntibiotic(<?php echo $antibiotic['id']; ?>)"
                                            title="<?php echo __('delete'); ?>">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add Antibiotic Modal -->
<div class="modal fade" id="addAntibioticModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><?php echo __('add_new_antibiotic'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body" style="max-height: 70vh; overflow-y: auto;">
                    <input type="hidden" name="action" value="add_antibiotic">
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="antibiotic_name" class="form-label"><?php echo __('antibiotic_name'); ?> *</label>
                            <input type="text" class="form-control" id="antibiotic_name" name="antibiotic_name" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="generic_name" class="form-label"><?php echo __('generic_name'); ?> *</label>
                            <input type="text" class="form-control" id="generic_name" name="generic_name" required>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label for="category" class="form-label"><?php echo __('category'); ?> *</label>
                            <select class="form-select" id="category" name="category" required>
                                <option value=""><?php echo __('select_category'); ?></option>
                                <option value="Penicillin">Penicillin</option>
                                <option value="Cephalosporin">Cephalosporin</option>
                                <option value="Fluoroquinolone">Fluoroquinolone</option>
                                <option value="Macrolide">Macrolide</option>
                                <option value="Carbapenem">Carbapenem</option>
                                <option value="Aminoglycoside">Aminoglycoside</option>
                                <option value="Tetracycline">Tetracycline</option>
                                <option value="Glycopeptide">Glycopeptide</option>
                                <option value="Other"><?php echo __('other'); ?></option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="dosage_forms" class="form-label"><?php echo __('dosage_form'); ?> *</label>
                            <select class="form-select" id="dosage_forms" name="dosage_forms" required>
                                <option value=""><?php echo __('select_dosage_form'); ?></option>
                                <option value="Tablet"><?php echo __('tablet'); ?></option>
                                <option value="Capsule"><?php echo __('capsule'); ?></option>
                                <option value="Injection"><?php echo __('injection'); ?></option>
                                <option value="Syrup"><?php echo __('syrup'); ?></option>
                                <option value="Suspension"><?php echo __('suspension'); ?></option>
                                <option value="Cream"><?php echo __('cream'); ?></option>
                                <option value="Ointment"><?php echo __('ointment'); ?></option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="strength" class="form-label"><?php echo __('strength'); ?> *</label>
                            <input type="text" class="form-control" id="strength" name="strength" placeholder="<?php echo __('strength_example'); ?>" required>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="route" class="form-label"><?php echo __('route'); ?> *</label>
                        <select class="form-select" id="route" name="route" required>
                            <option value=""><?php echo __('select_route'); ?></option>
                            <option value="Oral"><?php echo __('oral'); ?></option>
                            <option value="IV"><?php echo __('iv'); ?></option>
                            <option value="IM"><?php echo __('im'); ?></option>
                            <option value="Topical"><?php echo __('topical'); ?></option>
                            <option value="Inhalation"><?php echo __('inhalation'); ?></option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label for="indication" class="form-label"><?php echo __('indications'); ?> *</label>
                        <textarea class="form-control" id="indication" name="indication" rows="2" required></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="contraindications" class="form-label"><?php echo __('contraindications'); ?></label>
                        <textarea class="form-control" id="contraindications" name="contraindications" rows="2"></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="side_effects" class="form-label"><?php echo __('side_effects'); ?></label>
                        <textarea class="form-control" id="side_effects" name="side_effects" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times"></i> <?php echo __('cancel'); ?>
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> <?php echo __('save'); ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- View Antibiotic Modals -->
<?php foreach ($antibiotics as $antibiotic): ?>
<div class="modal fade" id="viewAntibioticModal<?php echo $antibiotic['id']; ?>" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title"><?php echo __('antibiotic_details'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6 class="text-primary"><?php echo __('basic_information'); ?></h6>
                        <table class="table table-sm">
                            <tr>
                                <td><strong><?php echo __('antibiotic_name'); ?>:</strong></td>
                                <td><?php echo htmlspecialchars($antibiotic['antibiotic_name'] ?? __('not_specified')); ?></td>
                            </tr>
                            <tr>
                                <td><strong><?php echo __('generic_name'); ?>:</strong></td>
                                <td><?php echo htmlspecialchars($antibiotic['generic_name'] ?? __('not_specified')); ?></td>
                            </tr>
                            <tr>
                                <td><strong><?php echo __('category'); ?>:</strong></td>
                                <td><?php echo htmlspecialchars($antibiotic['category'] ?? __('not_specified')); ?></td>
                            </tr>
                            <tr>
                                <td><strong><?php echo __('strength'); ?>:</strong></td>
                                <td><?php echo htmlspecialchars($antibiotic['strength'] ?? __('not_specified')); ?></td>
                            </tr>
                            <tr>
                                <td><strong><?php echo __('dosage_form'); ?>:</strong></td>
                                <td><?php echo htmlspecialchars($antibiotic['dosage_form'] ?? $antibiotic['dosage_forms'] ?? __('not_specified')); ?></td>
                            </tr>
                            <tr>
                                <td><strong><?php echo __('route'); ?>:</strong></td>
                                <td><?php echo htmlspecialchars($antibiotic['route'] ?? __('not_specified')); ?></td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h6 class="text-primary"><?php echo __('additional_information'); ?></h6>
                        <table class="table table-sm">
                            <tr>
                                <td><strong><?php echo __('status'); ?>:</strong></td>
                                <td>
                                    <span class="badge bg-<?php echo $antibiotic['is_active'] ? 'success' : 'secondary'; ?>">
                                        <?php echo $antibiotic['is_active'] ? __('active') : __('inactive'); ?>
                                    </span>
                                </td>
                            </tr>
                            <tr>
                                <td><strong><?php echo __('usage_times'); ?>:</strong></td>
                                <td><?php echo $antibiotic['usage_count']; ?></td>
                            </tr>
                            <tr>
                                <td><strong><?php echo __('date_added'); ?>:</strong></td>
                                <td><?php echo date('Y-m-d H:i', strtotime($antibiotic['created_at'])); ?></td>
                            </tr>
                        </table>
                    </div>
                </div>
                
                <?php if (!empty($antibiotic['indication'])): ?>
                <div class="mt-3">
                    <h6 class="text-primary"><?php echo __('indications'); ?></h6>
                    <p class="text-muted"><?php echo nl2br(htmlspecialchars($antibiotic['indication'])); ?></p>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($antibiotic['contraindications'])): ?>
                <div class="mt-3">
                    <h6 class="text-primary"><?php echo __('contraindications'); ?></h6>
                    <p class="text-muted"><?php echo nl2br(htmlspecialchars($antibiotic['contraindications'])); ?></p>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($antibiotic['side_effects'])): ?>
                <div class="mt-3">
                    <h6 class="text-primary"><?php echo __('side_effects'); ?></h6>
                    <p class="text-muted"><?php echo nl2br(htmlspecialchars($antibiotic['side_effects'])); ?></p>
                </div>
                <?php endif; ?>
            </div>
            <div class="modal-footer">
                <a href="edit_antibiotic.php?id=<?php echo $antibiotic['id']; ?>" class="btn btn-warning">
                    <i class="fas fa-edit"></i> <?php echo __('edit'); ?>
                </a>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times"></i> <?php echo __('close'); ?>
                </button>
            </div>
        </div>
    </div>
</div>
<?php endforeach; ?>

<script>
function toggleAntibioticStatus(antibioticId, status) {
    const statusText = status == 'active' ? '<?php echo __('activate'); ?>' : '<?php echo __('deactivate'); ?>';
    if (confirm(`<?php echo __('confirm_toggle_antibiotic'); ?> ${statusText} <?php echo __('this_antibiotic'); ?>`)) {
        // Show loading
        const button = event.target.closest('button');
        const originalHTML = button.innerHTML;
        button.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        button.disabled = true;
        
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="toggle_status">
            <input type="hidden" name="antibiotic_id" value="${antibioticId}">
            <input type="hidden" name="status" value="${status}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

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

// Initialize DataTable
$(document).ready(function() {
    $('#antibioticsTable').DataTable({
        "language": {
            "url": "//cdn.datatables.net/plug-ins/1.10.24/i18n/Arabic.json"
        },
        "pageLength": 25,
        "responsive": true,
        "order": [[0, "asc"]],
        "columnDefs": [
            { "orderable": false, "targets": -1 } // Disable sorting on Actions column
        ]
    });
});
</script>

<script>
function deleteAntibiotic(id) {
    if (confirm('هل أنت متأكد من حذف هذا المضاد الحيوي؟')) {
        window.location.href = 'delete.php?type=antibiotic&id=' + id;
    }
}
</script>

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