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

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

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

// Get report details
$stmt = $conn->prepare("
    SELECT ar.*, p.patient_name, p.mrn, u.unit_name, 
           COALESCE(a.antibiotic_name, ar.other_medication_name, 'غير محدد') as antibiotic_name
    FROM antibiotic_reports ar
    JOIN patients p ON ar.patient_id = p.id
    JOIN units u ON ar.unit_id = u.id
    LEFT JOIN antibiotics a ON ar.antibiotic_id = a.id
    WHERE ar.id = :id
");
$stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$report = $stmt->fetch(PDO::FETCH_ASSOC);

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

// Get all patients, units, and antibiotics for dropdowns
$patients = $conn->query("SELECT id, patient_name, mrn FROM patients ORDER BY patient_name")->fetchAll(PDO::FETCH_ASSOC);
$units = $conn->query("SELECT id, unit_name FROM units WHERE is_active = 1 ORDER BY unit_name")->fetchAll(PDO::FETCH_ASSOC);
$antibiotics = $conn->query("SELECT id, antibiotic_name FROM antibiotics WHERE is_active = 1 ORDER BY antibiotic_name")->fetchAll(PDO::FETCH_ASSOC);

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $conn->beginTransaction();
        
        $drug_type = $_POST['drug_type'] ?? 'antibiotic';
        $antibiotic_id = ($drug_type === 'antibiotic') ? ($_POST['antibiotic_id'] ?? null) : null;
        $other_medication_name = ($drug_type === 'other') ? ($_POST['other_medication_name'] ?? null) : null;
        
        $stmt = $conn->prepare("
            UPDATE antibiotic_reports SET
                patient_id = :patient_id,
                unit_id = :unit_id,
                antibiotic_id = :antibiotic_id,
                drug_type = :drug_type,
                other_medication_name = :other_medication_name,
                report_date = :report_date,
                problem_authority = :problem_authority,
                problem_authority_name = :problem_authority_name,
                intervention_choice = :intervention_choice,
                degree_of_damage = :degree_of_damage,
                result_of_intervention = :result_of_intervention,
                corrective_action = :corrective_action,
                result_of_corrective_action = :result_of_corrective_action,
                recommendations = :recommendations,
                status = :status,
                updated_at = NOW()
            WHERE id = :id
        ");
        
        $stmt->execute([
            ':patient_id' => $_POST['patient_id'],
            ':unit_id' => $_POST['unit_id'],
            ':antibiotic_id' => $antibiotic_id,
            ':drug_type' => $drug_type,
            ':other_medication_name' => $other_medication_name,
            ':report_date' => $_POST['report_date'],
            ':problem_authority' => $_POST['problem_authority'],
            ':problem_authority_name' => $_POST['problem_authority_name'] ?? null,
            ':intervention_choice' => $_POST['intervention_choice'] ?? null,
            ':degree_of_damage' => implode(', ', $_POST['degree_of_damage'] ?? []),
            ':result_of_intervention' => $_POST['result_of_intervention'] ?? 'accept',
            ':corrective_action' => $_POST['corrective_action'] ?? null,
            ':result_of_corrective_action' => $_POST['result_of_corrective_action'] ?? null,
            ':recommendations' => $_POST['recommendations'] ?? null,
            ':status' => $_POST['status'] ?? 'pending',
            ':id' => $_GET['id']
        ]);
        
        // Update problem definitions
        $conn->prepare("DELETE FROM problem_definitions WHERE report_id = ?")->execute([$_GET['id']]);
        
        if (!empty($_POST['problem_definitions'])) {
            $stmt = $conn->prepare("INSERT INTO problem_definitions (report_id, problem_type, description) VALUES (?, ?, ?)");
            foreach ($_POST['problem_definitions'] as $problem) {
                $stmt->execute([$_GET['id'], $problem, $_POST['problem_description'][$problem] ?? null]);
            }
        }
        
        $conn->commit();
        logActivity($conn, $_SESSION['user_id'], 'تحديث التقرير', 'antibiotic_reports', $_GET['id']);
        
        $message = 'تم تحديث التقرير بنجاح!';
        
        // Refresh report data
        $stmt = $conn->prepare("
            SELECT ar.*, p.patient_name, p.mrn, u.unit_name, 
                   COALESCE(a.antibiotic_name, ar.other_medication_name, 'غير محدد') as antibiotic_name
            FROM antibiotic_reports ar
            JOIN patients p ON ar.patient_id = p.id
            JOIN units u ON ar.unit_id = u.id
            LEFT JOIN antibiotics a ON ar.antibiotic_id = a.id
            WHERE ar.id = :id
        ");
        $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
        $stmt->execute();
        $report = $stmt->fetch(PDO::FETCH_ASSOC);
        
    } catch (Exception $e) {
        $conn->rollBack();
        $error = 'حدث خطأ أثناء تحديث التقرير: ' . $e->getMessage();
    }
}

// Get existing problem definitions
$stmt = $conn->prepare("SELECT * FROM problem_definitions WHERE report_id = ?");
$stmt->execute([$_GET['id']]);
$existing_problems = $stmt->fetchAll(PDO::FETCH_ASSOC);
$selected_problems = array_column($existing_problems, 'problem_type');

// Parse degree of damage
$selected_damage = explode(', ', $report['degree_of_damage'] ?? '');

// Set page title
$page_title = __('edit_report_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_report_page'); ?> #<?php echo $report['id']; ?></h1>
        <div>
            <a href="reports.php?id=<?php echo $report['id']; ?>" class="btn btn-info me-2">
                <i class="fas fa-eye"></i> <?php echo __('view_report'); ?>
            </a>
            <a href="reports.php" class="btn btn-secondary">
                <i class="fas fa-arrow-<?php echo Translation::getDirection() == 'rtl' ? 'right' : 'left'; ?>"></i> <?php echo __('back_to_reports'); ?>
            </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; ?>

    <form method="POST" class="needs-validation" novalidate>
        <div class="row">
            <!-- Basic Information -->
            <div class="col-md-6 mb-4">
                <div class="card shadow">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">المعلومات الأساسية</h6>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label for="patient_id" class="form-label">المريض *</label>
                            <select class="form-select" id="patient_id" name="patient_id" required>
                                <option value="">اختر المريض</option>
                                <?php foreach ($patients as $patient): ?>
                                <option value="<?php echo $patient['id']; ?>" <?php echo $report['patient_id'] == $patient['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($patient['patient_name'] . ' - ' . $patient['mrn']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label for="unit_id" class="form-label">القسم *</label>
                            <select class="form-select" id="unit_id" name="unit_id" required>
                                <option value="">اختر القسم</option>
                                <?php foreach ($units as $unit): ?>
                                <option value="<?php echo $unit['id']; ?>" <?php echo $report['unit_id'] == $unit['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($unit['unit_name']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label for="drug_type" class="form-label">نوع الدواء *</label>
                            <select class="form-select" id="drug_type" name="drug_type" required onchange="toggleDrugFields(this.value)">
                                <option value="">اختر نوع الدواء</option>
                                <option value="antibiotic" <?php echo ($report['drug_type'] ?? 'antibiotic') == 'antibiotic' ? 'selected' : ''; ?>>مضاد حيوي</option>
                                <option value="other" <?php echo ($report['drug_type'] ?? 'antibiotic') == 'other' ? 'selected' : ''; ?>>دواء آخر</option>
                            </select>
                        </div>

                        <div class="mb-3" id="antibiotic_field" style="display: <?php echo ($report['drug_type'] ?? 'antibiotic') == 'antibiotic' ? 'block' : 'none'; ?>;">
                            <label for="antibiotic_id" class="form-label">المضاد الحيوي *</label>
                            <select class="form-select" id="antibiotic_id" name="antibiotic_id">
                                <option value="">اختر المضاد الحيوي</option>
                                <?php foreach ($antibiotics as $antibiotic): ?>
                                <option value="<?php echo $antibiotic['id']; ?>" <?php echo $report['antibiotic_id'] == $antibiotic['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($antibiotic['antibiotic_name']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="mb-3" id="other_medication_field" style="display: <?php echo ($report['drug_type'] ?? 'antibiotic') == 'other' ? 'block' : 'none'; ?>;">
                            <label for="other_medication_name" class="form-label">اسم الدواء *</label>
                            <input type="text" class="form-control" id="other_medication_name" name="other_medication_name" 
                                   value="<?php echo htmlspecialchars($report['other_medication_name'] ?? ''); ?>">
                        </div>

                        <div class="mb-3">
                            <label for="report_date" class="form-label">تاريخ التقرير *</label>
                            <input type="date" class="form-control" id="report_date" name="report_date" 
                                   value="<?php echo $report['report_date']; ?>" required>
                        </div>

                        <div class="mb-3">
                            <label for="status" class="form-label"><?php echo __('status'); ?></label>
                            <select class="form-select" id="status" name="status">
                                <option value="pending" <?php echo $report['status'] == 'pending' ? 'selected' : ''; ?>><?php echo __('pending'); ?></option>
                                <option value="completed" <?php echo $report['status'] == 'completed' ? 'selected' : ''; ?>><?php echo __('completed'); ?></option>
                                <option value="cancelled" <?php echo $report['status'] == 'cancelled' ? 'selected' : ''; ?>><?php echo __('cancelled'); ?></option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Problem Authority -->
            <div class="col-md-6 mb-4">
                <div class="card shadow">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">سلطة المشكلة</h6>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">سلطة المشكلة *</label>
                            <div class="mt-2">
                                <?php 
                                $authorities = [
                                    'physician' => 'طبيب',
                                    'pharmacist' => 'صيدلي',
                                    'nurse' => 'ممرض',
                                    'secretary' => 'سكرتارية',
                                    'pharmacy_assistant' => 'مساعد صيدلي',
                                    'system' => 'النظام',
                                    'other' => 'أخرى'
                                ];
                                ?>
                                <?php foreach ($authorities as $value => $label): ?>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="problem_authority" 
                                           value="<?php echo $value; ?>" id="authority_<?php echo $value; ?>"
                                           <?php echo $report['problem_authority'] == $value ? 'checked' : ''; ?> required>
                                    <label class="form-check-label" for="authority_<?php echo $value; ?>">
                                        <?php echo $label; ?>
                                    </label>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="problem_authority_name" class="form-label">اسم المسؤول</label>
                            <input type="text" class="form-control" id="problem_authority_name" name="problem_authority_name" 
                                   placeholder="اسم الشخص المسؤول عن المشكلة" 
                                   value="<?php echo htmlspecialchars($report['problem_authority_name'] ?? ''); ?>">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Problem Definitions -->
        <div class="row">
            <div class="col-12 mb-4">
                <div class="card shadow">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">تعريف المشكلة</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <?php 
                            $problem_types = [
                                'wrong_drug' => 'دواء خاطئ',
                                'wrong_dose' => 'جرعة خاطئة',
                                'wrong_route' => 'طريق إعطاء خاطئ',
                                'wrong_time' => 'توقيت خاطئ',
                                'drug_interaction' => 'تفاعل دوائي',
                                'contraindication' => 'موانع استعمال',
                                'allergy' => 'حساسية',
                                'other' => 'أخرى'
                            ];
                            ?>
                            <?php foreach ($problem_types as $value => $label): ?>
                            <div class="col-md-3 mb-2">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="problem_definitions[]" 
                                           value="<?php echo $value; ?>" id="problem_<?php echo $value; ?>"
                                           <?php echo in_array($value, $selected_problems) ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="problem_<?php echo $value; ?>">
                                        <?php echo $label; ?>
                                    </label>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Intervention and Results -->
        <div class="row">
            <div class="col-md-6 mb-4">
                <div class="card shadow">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">التدخل والنتائج</h6>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label for="intervention_choice" class="form-label">اختيار التدخل</label>
                            <select class="form-select" id="intervention_choice" name="intervention_choice">
                                <option value="">اختر نوع التدخل</option>
                                <option value="stop_medication" <?php echo $report['intervention_choice'] == 'stop_medication' ? 'selected' : ''; ?>>إيقاف الدواء</option>
                                <option value="change_medication" <?php echo $report['intervention_choice'] == 'change_medication' ? 'selected' : ''; ?>>تغيير الدواء</option>
                                <option value="adjust_dose" <?php echo $report['intervention_choice'] == 'adjust_dose' ? 'selected' : ''; ?>>تعديل الجرعة</option>
                                <option value="change_route" <?php echo $report['intervention_choice'] == 'change_route' ? 'selected' : ''; ?>>تغيير طريق الإعطاء</option>
                                <option value="monitoring" <?php echo $report['intervention_choice'] == 'monitoring' ? 'selected' : ''; ?>>مراقبة إضافية</option>
                                <option value="other" <?php echo $report['intervention_choice'] == 'other' ? 'selected' : ''; ?>>أخرى</option>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">درجة الضرر</label>
                            <div class="mt-2">
                                <?php 
                                $damage_levels = [
                                    'no_harm' => 'لا ضرر',
                                    'mild' => 'خفيف',
                                    'moderate' => 'متوسط',
                                    'severe' => 'شديد',
                                    'life_threatening' => 'يهدد الحياة'
                                ];
                                ?>
                                <?php foreach ($damage_levels as $value => $label): ?>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="degree_of_damage[]" 
                                           value="<?php echo $value; ?>" id="damage_<?php echo $value; ?>"
                                           <?php echo in_array($value, $selected_damage) ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="damage_<?php echo $value; ?>">
                                        <?php echo $label; ?>
                                    </label>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">نتيجة التدخل</label>
                            <div class="mt-2">
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="result_of_intervention" 
                                           value="accept" id="result_accept" 
                                           <?php echo $report['result_of_intervention'] == 'accept' ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="result_accept">مقبول</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="result_of_intervention" 
                                           value="reject" id="result_reject"
                                           <?php echo $report['result_of_intervention'] == 'reject' ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="result_reject">مرفوض</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Additional Information -->
            <div class="col-md-6 mb-4">
                <div class="card shadow">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">معلومات إضافية</h6>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label for="corrective_action" class="form-label">الإجراء التصحيحي</label>
                            <textarea class="form-control" id="corrective_action" name="corrective_action" rows="3" 
                                      placeholder="وصف الإجراء التصحيحي المتخذ"><?php echo htmlspecialchars($report['corrective_action'] ?? ''); ?></textarea>
                        </div>

                        <div class="mb-3">
                            <label for="result_of_corrective_action" class="form-label">نتيجة الإجراء التصحيحي</label>
                            <textarea class="form-control" id="result_of_corrective_action" name="result_of_corrective_action" rows="3" 
                                      placeholder="وصف نتيجة الإجراء التصحيحي"><?php echo htmlspecialchars($report['result_of_corrective_action'] ?? ''); ?></textarea>
                        </div>

                        <div class="mb-3">
                            <label for="recommendations" class="form-label">التوصيات</label>
                            <textarea class="form-control" id="recommendations" name="recommendations" rows="3" 
                                      placeholder="التوصيات لتجنب تكرار المشكلة"><?php echo htmlspecialchars($report['recommendations'] ?? ''); ?></textarea>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Submit Buttons -->
        <div class="row">
            <div class="col-12">
                <div class="card shadow">
                    <div class="card-body text-center">
                        <button type="submit" class="btn btn-primary btn-lg me-3">
                            <i class="fas fa-save"></i> حفظ التغييرات
                        </button>
                        <a href="reports.php?id=<?php echo $report['id']; ?>" class="btn btn-info btn-lg me-3">
                            <i class="fas fa-eye"></i> عرض التقرير
                        </a>
                        <a href="reports.php" class="btn btn-secondary btn-lg">
                            <i class="fas fa-times"></i> إلغاء
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
// Toggle drug fields based on drug type
function toggleDrugFields(drugType) {
    var antibioticField = document.getElementById('antibiotic_field');
    var otherMedicationField = document.getElementById('other_medication_field');
    var antibioticSelect = document.getElementById('antibiotic_id');
    var otherMedicationInput = document.getElementById('other_medication_name');

    if (drugType === 'antibiotic') {
        antibioticField.style.display = 'block';
        otherMedicationField.style.display = 'none';
        antibioticSelect.required = true;
        otherMedicationInput.required = false;
    } else if (drugType === 'other') {
        antibioticField.style.display = 'none';
        otherMedicationField.style.display = 'block';
        antibioticSelect.required = false;
        otherMedicationInput.required = true;
    } else {
        antibioticField.style.display = 'none';
        otherMedicationField.style.display = 'none';
        antibioticSelect.required = false;
        otherMedicationInput.required = false;
    }
}

// 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'; ?>
