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

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

// All logged-in users can edit antibiotics

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: " . (isset($_SERVER["HTTPS"]) ? "https" : "http") . "://" . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER["SCRIPT_NAME"]), "/\\") . "/" . "manage_antibiotics.php");
    exit();
}

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

// Get antibiotic data
$stmt = $conn->prepare("SELECT * FROM antibiotics WHERE id = :id");
$stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$antibiotic = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$antibiotic) {
    header("Location: " . (isset($_SERVER["HTTPS"]) ? "https" : "http") . "://" . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER["SCRIPT_NAME"]), "/\\") . "/" . "manage_antibiotics.php");
    exit();
}

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $stmt = $conn->prepare("
            UPDATE antibiotics SET 
                antibiotic_name = :antibiotic_name,
                generic_name = :generic_name,
                category = :category,
                dosage_form = :dosage_form,
                strength = :strength,
                indication = :indication,
                contraindications = :contraindications,
                side_effects = :side_effects,
                is_active = :is_active,
                updated_at = NOW()
            WHERE id = :id
        ");
        
        $stmt->execute([
            ':antibiotic_name' => $_POST['antibiotic_name'],
            ':generic_name' => $_POST['generic_name'] ?? null,
            ':category' => $_POST['category'] ?? null,
            ':dosage_form' => $_POST['dosage_form'] ?? null,
            ':strength' => $_POST['strength'] ?? null,
            ':indication' => $_POST['indication'] ?? null,
            ':contraindications' => $_POST['contraindications'] ?? null,
            ':side_effects' => $_POST['side_effects'] ?? null,
            ':is_active' => isset($_POST['is_active']) ? 1 : 0,
            ':id' => $_GET['id']
        ]);
        
        logActivity($conn, $_SESSION['user_id'], 'تحديث مضاد حيوي', 'antibiotics', $_GET['id']);
        $message = __('antibiotic_updated_successfully');
        
        // Refresh antibiotic data
        $stmt = $conn->prepare("SELECT * FROM antibiotics WHERE id = :id");
        $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
        $stmt->execute();
        $antibiotic = $stmt->fetch(PDO::FETCH_ASSOC);
        
    } catch (Exception $e) {
        $error = __('error_updating_antibiotic') . ': ' . $e->getMessage();
    }
}

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

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

<!-- Main Content -->

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0"><?php echo __('edit_antibiotic_page'); ?></h1>
        <div>
            <a href="manage_antibiotics.php" class="btn btn-secondary">
                <i class="fas fa-arrow-<?php echo Translation::getDirection() == 'rtl' ? 'right' : 'left'; ?>"></i> <?php echo __('back_to_antibiotics'); ?>
            </a>
        </div>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i>
            <?php echo $message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            <?php echo $error; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="row">
        <!-- Form -->
        <div class="col-md-8">
            <div class="card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary"><?php echo __('antibiotic_information'); ?></h6>
                </div>
                <div class="card-body">
                    <form method="POST" class="needs-validation" novalidate>
                        <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" 
                                       placeholder="<?php echo __('please_enter_antibiotic_name'); ?>" value="<?php echo htmlspecialchars($antibiotic['antibiotic_name']); ?>" required>
                                <div class="invalid-feedback">
                                    <?php echo __('antibiotic_name_required'); ?>
                                </div>
                            </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" 
                                       placeholder="<?php echo __('generic_name'); ?>" value="<?php echo htmlspecialchars($antibiotic['generic_name'] ?? ''); ?>">
                            </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">
                                    <option value=""><?php echo __('select_category_option'); ?></option>
                                    <option value="penicillins" <?php echo $antibiotic['category'] == 'penicillins' ? 'selected' : ''; ?>><?php echo __('penicillins'); ?></option>
                                    <option value="cephalosporins" <?php echo $antibiotic['category'] == 'cephalosporins' ? 'selected' : ''; ?>><?php echo __('cephalosporins'); ?></option>
                                    <option value="macrolides" <?php echo $antibiotic['category'] == 'macrolides' ? 'selected' : ''; ?>><?php echo __('macrolides'); ?></option>
                                    <option value="fluoroquinolones" <?php echo $antibiotic['category'] == 'fluoroquinolones' ? 'selected' : ''; ?>><?php echo __('fluoroquinolones'); ?></option>
                                    <option value="aminoglycosides" <?php echo $antibiotic['category'] == 'aminoglycosides' ? 'selected' : ''; ?>><?php echo __('aminoglycosides'); ?></option>
                                    <option value="tetracyclines" <?php echo $antibiotic['category'] == 'tetracyclines' ? 'selected' : ''; ?>><?php echo __('tetracyclines'); ?></option>
                                    <option value="sulfonamides" <?php echo $antibiotic['category'] == 'sulfonamides' ? 'selected' : ''; ?>><?php echo __('sulfonamides'); ?></option>
                                    <option value="other" <?php echo $antibiotic['category'] == 'other' ? 'selected' : ''; ?>><?php echo __('other'); ?></option>
                                </select>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label for="dosage_form" class="form-label"><?php echo __('dosage_form'); ?></label>
                                <select class="form-select" id="dosage_form" name="dosage_form">
                                    <option value=""><?php echo __('select_dosage_form_option'); ?></option>
                                    <option value="tablet" <?php echo $antibiotic['dosage_form'] == 'tablet' ? 'selected' : ''; ?>><?php echo __('tablet'); ?></option>
                                    <option value="capsule" <?php echo $antibiotic['dosage_form'] == 'capsule' ? 'selected' : ''; ?>><?php echo __('capsule'); ?></option>
                                    <option value="injection" <?php echo $antibiotic['dosage_form'] == 'injection' ? 'selected' : ''; ?>><?php echo __('injection'); ?></option>
                                    <option value="syrup" <?php echo $antibiotic['dosage_form'] == 'syrup' ? 'selected' : ''; ?>><?php echo __('syrup'); ?></option>
                                    <option value="suspension" <?php echo $antibiotic['dosage_form'] == 'suspension' ? 'selected' : ''; ?>><?php echo __('suspension'); ?></option>
                                    <option value="cream" <?php echo $antibiotic['dosage_form'] == 'cream' ? 'selected' : ''; ?>><?php echo __('cream'); ?></option>
                                    <option value="ointment" <?php echo $antibiotic['dosage_form'] == 'ointment' ? 'selected' : ''; ?>><?php echo __('ointment'); ?></option>
                                    <option value="drops" <?php echo $antibiotic['dosage_form'] == 'drops' ? 'selected' : ''; ?>><?php echo __('drops'); ?></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'); ?>" value="<?php echo htmlspecialchars($antibiotic['strength'] ?? ''); ?>">
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="indication" class="form-label"><?php echo __('indications'); ?></label>
                            <textarea class="form-control" id="indication" name="indication" rows="3" 
                                      placeholder="<?php echo __('indications'); ?>"><?php echo htmlspecialchars($antibiotic['indication'] ?? ''); ?></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="3" 
                                      placeholder="<?php echo __('contraindications'); ?>"><?php echo htmlspecialchars($antibiotic['contraindications'] ?? ''); ?></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="3" 
                                      placeholder="<?php echo __('side_effects'); ?>"><?php echo htmlspecialchars($antibiotic['side_effects'] ?? ''); ?></textarea>
                        </div>

                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="is_active" name="is_active" 
                                       <?php echo $antibiotic['is_active'] ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="is_active">
                                    <?php echo __('antibiotic_is_active'); ?>
                                </label>
                            </div>
                            <div class="form-text"><?php echo __('deactivate_note'); ?></div>
                        </div>

                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> <?php echo __('save_changes'); ?>
                            </button>
                            <a href="manage_antibiotics.php" class="btn btn-secondary">
                                <i class="fas fa-times"></i> <?php echo __('cancel'); ?>
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Information Panel -->
        <div class="col-md-4">
            <div class="card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-info">معلومات المضاد الحيوي</h6>
                </div>
                <div class="card-body">
                    <div class="text-center mb-3">
                        <div class="avatar-circle bg-<?php echo $antibiotic['is_active'] ? 'success' : 'secondary'; ?> text-white mb-2">
                            <i class="fas fa-pills fa-2x"></i>
                        </div>
                        <h6 class="mb-0"><?php echo htmlspecialchars($antibiotic['antibiotic_name']); ?></h6>
                        <p class="text-muted small">
                            <span class="badge bg-<?php echo $antibiotic['is_active'] ? 'success' : 'secondary'; ?>">
                                <?php echo $antibiotic['is_active'] ? 'نشط' : 'غير نشط'; ?>
                            </span>
                        </p>
                    </div>

                    <hr>

                    <div class="mb-2">
                        <strong class="text-muted small">الاسم العلمي:</strong>
                        <span class="float-end"><?php echo htmlspecialchars($antibiotic['generic_name'] ?? 'غير محدد'); ?></span>
                    </div>

                    <div class="mb-2">
                        <strong class="text-muted small">الفئة:</strong>
                        <span class="float-end"><?php echo htmlspecialchars($antibiotic['category'] ?? 'غير محدد'); ?></span>
                    </div>

                    <div class="mb-2">
                        <strong class="text-muted small">شكل الجرعة:</strong>
                        <span class="float-end"><?php echo htmlspecialchars($antibiotic['dosage_form'] ?? 'غير محدد'); ?></span>
                    </div>

                    <div class="mb-2">
                        <strong class="text-muted small">القوة:</strong>
                        <span class="float-end"><?php echo htmlspecialchars($antibiotic['strength'] ?? 'غير محدد'); ?></span>
                    </div>

                    <div class="mb-2">
                        <strong class="text-muted small">تاريخ الإضافة:</strong>
                        <span class="float-end"><?php echo date('Y-m-d', strtotime($antibiotic['created_at'])); ?></span>
                    </div>

                    <?php if (isset($antibiotic['updated_at']) && $antibiotic['updated_at']): ?>
                    <div class="mb-2">
                        <strong class="text-muted small">آخر تحديث:</strong>
                        <span class="float-end"><?php echo date('Y-m-d', strtotime($antibiotic['updated_at'])); ?></span>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="card shadow mt-3">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-warning">إرشادات التعديل</h6>
                </div>
                <div class="card-body">
                    <ul class="list-unstyled mb-0 small">
                        <li class="mb-2">
                            <i class="fas fa-info-circle text-info me-2"></i>
                            تأكد من صحة اسم المضاد الحيوي
                        </li>
                        <li class="mb-2">
                            <i class="fas fa-check text-success me-2"></i>
                            أدخل المعلومات الطبية بدقة
                        </li>
                        <li class="mb-2">
                            <i class="fas fa-exclamation-triangle text-warning me-2"></i>
                            إلغاء التفعيل يمنع الاستخدام في التقارير الجديدة
                        </li>
                        <li>
                            <i class="fas fa-history text-primary me-2"></i>
                            سيتم حفظ سجل التعديل تلقائياً
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.avatar-circle {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto;
}
</style>

<script>
// Form validation
(function() {
    'use strict';
    window.addEventListener('load', function() {
        var forms = document.getElementsByClassName('needs-validation');
        var validation = Array.prototype.filter.call(forms, function(form) {
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();
</script>

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