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

$currentPage = 'antibiotics';
PagePermissions::requirePageAccess($currentPage);

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

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $antibiotic_name = trim($_POST['antibiotic_name'] ?? '');
    $generic_name    = trim($_POST['generic_name'] ?? '') ?: null;
    $category        = trim($_POST['category'] ?? '') ?: null;
    $dosage_form     = trim($_POST['dosage_form'] ?? '') ?: null;
    $strength        = trim($_POST['strength'] ?? '') ?: null;
    $indication      = trim($_POST['indication'] ?? '') ?: null;
    $contraindications = trim($_POST['contraindications'] ?? '') ?: null;
    $side_effects    = trim($_POST['side_effects'] ?? '') ?: null;

    if (empty($antibiotic_name)) {
        $error = __('antibiotic_name_required', 'يرجى إدخال اسم المضاد الحيوي');
    } else {
        try {
            $stmt = $conn->prepare("SELECT id FROM antibiotics WHERE antibiotic_name = ?");
            $stmt->execute([$antibiotic_name]);

            if ($stmt->fetch()) {
                $error = __('antibiotic_already_exists', 'المضاد الحيوي موجود بالفعل');
            } else {
                $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_form, $strength, $indication, $contraindications, $side_effects]);

                logActivity($conn, $_SESSION['user_id'], __('add_antibiotic_activity', 'إضافة مضاد حيوي'), 'antibiotics', $conn->lastInsertId());
                $message = __('antibiotic_added_successfully', 'تم إضافة المضاد الحيوي بنجاح');
                $_POST = [];
            }
        } catch (PDOException $e) {
            $error = __('error_adding_antibiotic', 'خطأ في الإضافة') . ': ' . $e->getMessage();
        }
    }
}

$page_title = __('add_new_antibiotic', 'إضافة مضاد حيوي جديد') . ' - ' . __('system_name');
include 'includes/header.php';
?>


    <!-- Header -->
    <div class="header no-print">
        <div>
            <h1 class="h3 mb-0"><?php echo __('add_new_antibiotic', 'إضافة مضاد حيوي جديد'); ?></h1>
            <p class="text-muted mb-0"><?php echo __('antibiotic_management', 'إدارة المضادات الحيوية'); ?></p>
        </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>

    <?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 htmlspecialchars($message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></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 htmlspecialchars($error); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="card dashboard-card">
        <div class="card-body">
            <h6 class="section-title"><?php echo __('antibiotic_information', 'معلومات المضاد الحيوي'); ?></h6>
            <form method="POST" class="needs-validation" novalidate>
                <div class="row">
                    <div class="col-md-6 mb-4">
                        <label for="antibiotic_name" class="form-label fw-bold">
                            <?php echo __('antibiotic_name', 'اسم المضاد الحيوي'); ?> <span class="text-danger">*</span>
                        </label>
                        <input type="text" class="form-control" id="antibiotic_name" name="antibiotic_name"
                               value="<?php echo htmlspecialchars($_POST['antibiotic_name'] ?? ''); ?>" required>
                        <div class="invalid-feedback"><?php echo __('please_enter_antibiotic_name', 'يرجى إدخال اسم المضاد الحيوي'); ?></div>
                    </div>

                    <div class="col-md-6 mb-4">
                        <label for="generic_name" class="form-label fw-bold"><?php echo __('generic_name', 'الاسم العلمي'); ?></label>
                        <input type="text" class="form-control" id="generic_name" name="generic_name"
                               value="<?php echo htmlspecialchars($_POST['generic_name'] ?? ''); ?>">
                    </div>

                    <div class="col-md-6 mb-4">
                        <label for="category" class="form-label fw-bold"><?php echo __('category', 'الفئة'); ?></label>
                        <select class="form-select" id="category" name="category">
                            <option value=""><?php echo __('select_category', 'اختر الفئة'); ?></option>
                            <?php
                            $categories = ['Penicillin','Cephalosporin','Macrolide','Fluoroquinolone','Tetracycline','Aminoglycoside','Glycopeptide','Carbapenem','Other'];
                            foreach ($categories as $cat):
                                $sel = (($_POST['category'] ?? '') == $cat) ? 'selected' : '';
                            ?>
                            <option value="<?php echo $cat; ?>" <?php echo $sel; ?>><?php echo $cat; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-6 mb-4">
                        <label for="dosage_form" class="form-label fw-bold"><?php echo __('dosage_form', 'الشكل الصيدلاني'); ?></label>
                        <select class="form-select" id="dosage_form" name="dosage_form">
                            <option value=""><?php echo __('select_dosage_form', 'اختر الشكل'); ?></option>
                            <?php
                            $forms = [
                                'Tablet'     => __('tablet', 'أقراص'),
                                'Capsule'    => __('capsule', 'كبسولات'),
                                'Injection'  => __('injection', 'حقن'),
                                'Syrup'      => __('syrup', 'شراب'),
                                'Suspension' => __('suspension', 'معلق'),
                                'Cream'      => __('cream', 'كريم'),
                                'Ointment'   => __('ointment', 'مرهم'),
                            ];
                            foreach ($forms as $val => $label):
                                $sel = (($_POST['dosage_form'] ?? '') == $val) ? 'selected' : '';
                            ?>
                            <option value="<?php echo $val; ?>" <?php echo $sel; ?>><?php echo $label; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-6 mb-4">
                        <label for="strength" class="form-label fw-bold"><?php echo __('strength', 'التركيز'); ?></label>
                        <input type="text" class="form-control" id="strength" name="strength"
                               value="<?php echo htmlspecialchars($_POST['strength'] ?? ''); ?>"
                               placeholder="<?php echo __('strength_example', 'مثال: 500mg'); ?>">
                    </div>

                    <div class="col-12 mb-4">
                        <label for="indication" class="form-label fw-bold"><?php echo __('indications', 'دواعي الاستعمال'); ?></label>
                        <textarea class="form-control" id="indication" name="indication" rows="3"><?php echo htmlspecialchars($_POST['indication'] ?? ''); ?></textarea>
                    </div>

                    <div class="col-12 mb-4">
                        <label for="contraindications" class="form-label fw-bold"><?php echo __('contraindications', 'موانع الاستعمال'); ?></label>
                        <textarea class="form-control" id="contraindications" name="contraindications" rows="3"><?php echo htmlspecialchars($_POST['contraindications'] ?? ''); ?></textarea>
                    </div>

                    <div class="col-12 mb-4">
                        <label for="side_effects" class="form-label fw-bold"><?php echo __('side_effects', 'الآثار الجانبية'); ?></label>
                        <textarea class="form-control" id="side_effects" name="side_effects" rows="3"><?php echo htmlspecialchars($_POST['side_effects'] ?? ''); ?></textarea>
                    </div>
                </div>

                <div class="d-flex justify-content-end gap-3">
                    <a href="manage_antibiotics.php" class="btn btn-secondary">
                        <i class="fas fa-times"></i> <?php echo __('cancel', 'إلغاء'); ?>
                    </a>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> <?php echo __('add_antibiotic', 'إضافة المضاد'); ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div><!-- end main-content -->

<script>
(function() {
    'use strict';
    document.querySelectorAll('.needs-validation').forEach(function(form) {
        form.addEventListener('submit', function(e) {
            if (!form.checkValidity()) {
                e.preventDefault();
                e.stopPropagation();
            }
            form.classList.add('was-validated');
        });
    });
})();
</script>

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

