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

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

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

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

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        // First, create or get patient
        $patient_name = $_POST['patient_name'];
        $mrn = $_POST['mrn'];
        $gender = $_POST['gender'];
        $pharmacy_number = $_POST['pharmacy_number'];
        $units = $_POST['units'] ?? [];
        
        if (empty($units)) {
            throw new Exception(__('select_at_least_one_unit'));
        }
        
        // Check if patient with this MRN already exists
        $stmt = $conn->prepare("SELECT id FROM patients WHERE mrn = ?");
        $stmt->execute([$mrn]);
        $existing_patient = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($existing_patient) {
            $patient_id = $existing_patient['id'];
        } else {
            // Insert new patient
            $stmt = $conn->prepare("INSERT INTO patients (patient_name, mrn, gender, date_of_birth, phone, address, created_by) VALUES (?, ?, ?, NULL, ?, NULL, ?)");
            $stmt->execute([$patient_name, $mrn, $gender, $pharmacy_number, $_SESSION['user_id']]);
            $patient_id = $conn->lastInsertId();
        }
        
        // Get the first selected unit as the main unit_id
        $unit_name = $units[0];
        $stmt = $conn->prepare("SELECT id FROM units WHERE unit_name = ?");
        $stmt->execute([$unit_name]);
        $unit = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$unit) {
            // Create unit if it doesn't exist
            // Generate a unique unit_code from unit_name
            $unit_code = strtoupper(substr(preg_replace('/[^a-zA-Z0-9]/', '', $unit_name), 0, 10));
            if (empty($unit_code)) {
                $unit_code = 'UNIT' . time(); // Fallback to timestamp-based code
            }
            $stmt = $conn->prepare("INSERT INTO units (unit_name, unit_code, is_active) VALUES (?, ?, 1)");
            $stmt->execute([$unit_name, $unit_code]);
            $unit_id = $conn->lastInsertId();
        } else {
            $unit_id = $unit['id'];
        }
        
        // Get other form data
        $drug_type = $_POST['drug_type'] ?? '';
        $antibiotic_id = ($drug_type === 'antibiotic') ? (int)($_POST['antibiotic_id'] ?? 0) : null;
        $other_medication_name = ($drug_type === 'other') ? trim($_POST['other_medication_name'] ?? '') : null;
        
        if (empty($drug_type)) {
            throw new Exception(__('please_select_drug_type'));
        }
        if ($drug_type === 'antibiotic' && empty($antibiotic_id)) {
            throw new Exception(__('please_select_antibiotic'));
        }
        if ($drug_type === 'other' && empty($other_medication_name)) {
            throw new Exception(__('please_enter_medication_name'));
        }
        
        $report_date = $_POST['report_date'];
        
        // Problem authority
        $problem_authority = $_POST['problem_authority'];
        $problem_authority_name = $_POST['problem_authority_name'];
        
        // Problem definitions
        $problem_definitions = $_POST['problem_definition'] ?? [];
        
        // Problem cause (سبب المشكلة)
        $problem_cause = $_POST['problem_cause'] ?? '';
        
        // Antibiotic classification (تصنيف المضاد الحيوي) - only required for antibiotics
        $antibiotic_classification = ($drug_type === 'antibiotic') ? ($_POST['antibiotic_classification'] ?? '') : null;
        
        // Intervention choices
        $intervention_choices = $_POST['intervention_choice'] ?? [];
        
        // Degree of damage
        $degree_of_damage = $_POST['degree_of_damage'] ?? [];
        
        // Result of intervention
        $result_of_intervention = $_POST['result_of_intervention'];
        
        // Corrective action
        $corrective_action = $_POST['corrective_action'];
        $result_of_corrective_action = $_POST['result_of_corrective_action'];
        
        // Recommendations
        $recommendations = $_POST['recommendations'];
        
        // Insert main report
        $stmt = $conn->prepare("
            INSERT INTO antibiotic_reports (
                patient_id, reporting_pharmacist_id, unit_id, antibiotic_id, 
                drug_type, other_medication_name,
                report_date, problem_authority, problem_authority_name,
                problem_cause, antibiotic_classification,
                intervention_choice, degree_of_damage, result_of_intervention,
                corrective_action, result_of_corrective_action, recommendations
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        
        $stmt->execute([
            $patient_id,
            $_SESSION['user_id'],
            $unit_id,
            $antibiotic_id,
            $drug_type,
            $other_medication_name,
            $report_date,
            $problem_authority,
            $problem_authority_name,
            $problem_cause,
            $antibiotic_classification,
            json_encode($intervention_choices),
            json_encode($degree_of_damage),
            $result_of_intervention,
            $corrective_action,
            $result_of_corrective_action,
            $recommendations
        ]);
        
        $report_id = $conn->lastInsertId();
        
        // Insert problem definitions
        if (!empty($problem_definitions)) {
            $stmt = $conn->prepare("INSERT INTO problem_definitions (report_id, problem_type) VALUES (?, ?)");
            foreach ($problem_definitions as $problem) {
                $stmt->execute([$report_id, $problem]);
            }
        }
        
        // Handle file uploads
        if (isset($_FILES['attachments']) && !empty($_FILES['attachments']['name'][0])) {
            $upload_dir = 'uploads/reports/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $stmt = $conn->prepare("INSERT INTO report_attachments (report_id, file_name, file_path, file_type, file_size, uploaded_by) VALUES (?, ?, ?, ?, ?, ?)");
            
            for ($i = 0; $i < count($_FILES['attachments']['name']); $i++) {
                if ($_FILES['attachments']['error'][$i] == 0) {
                    $file_name = $_FILES['attachments']['name'][$i];
                    $file_tmp = $_FILES['attachments']['tmp_name'][$i];
                    $file_size = $_FILES['attachments']['size'][$i];
                    $file_type = $_FILES['attachments']['type'][$i];
                    
                    $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
                    $new_file_name = uniqid() . '.' . $file_extension;
                    $file_path = $upload_dir . $new_file_name;
                    
                    if (move_uploaded_file($file_tmp, $file_path)) {
                        $stmt->execute([$report_id, $file_name, $file_path, $file_type, $file_size, $_SESSION['user_id']]);
                    }
                }
            }
        }
        
        logActivity($conn, $_SESSION['user_id'], __('add_new_report'), 'antibiotic_reports', $report_id);
        $message = __('report_saved_successfully');
        
    } catch (Exception $e) {
        $error = __('error_saving_report') . ': ' . $e->getMessage();
    }
}

// Add new columns if they don't exist (safe migration)
try {
    $conn->exec("ALTER TABLE antibiotic_reports MODIFY COLUMN antibiotic_id INT(11) DEFAULT NULL");
} catch (PDOException $e) { /* Already nullable or error */ }
try {
    $conn->exec("ALTER TABLE antibiotic_reports ADD COLUMN drug_type ENUM('antibiotic','other') DEFAULT 'antibiotic' AFTER antibiotic_id");
} catch (PDOException $e) { /* Column already exists */ }
try {
    $conn->exec("ALTER TABLE antibiotic_reports ADD COLUMN other_medication_name VARCHAR(255) DEFAULT NULL AFTER drug_type");
} catch (PDOException $e) { /* Column already exists */ }

// Get patients, antibiotics, and units for dropdowns
$patients = $conn->query("SELECT id, patient_name, mrn FROM patients WHERE id IN (SELECT DISTINCT patient_id FROM antibiotic_reports) OR id NOT IN (SELECT DISTINCT patient_id FROM antibiotic_reports) ORDER BY patient_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);
$units = $conn->query("SELECT id, unit_name FROM units WHERE is_active = 1 ORDER BY unit_name")->fetchAll(PDO::FETCH_ASSOC);

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

<style>
.form-section {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    overflow: hidden;
}

.form-section h5 {
    background: #6f42c1;
    color: white;
    margin: -20px -20px 20px -20px;
    padding: 15px 20px;
    border-radius: 7px 7px 0 0;
    font-weight: bold;
}

.checkbox-group {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 8px;
    margin-top: 10px;
}

.radio-group {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 8px;
    margin-top: 10px;
}

.form-check {
    margin-bottom: 6px;
    display: flex;
    align-items: center;
    gap: 6px;
    min-width: 0;
}

.form-check-input {
    flex-shrink: 0;
    margin: 0 !important;
}

.form-check-label {
    min-width: 0;
    word-break: break-word;
}

.required-field {
    color: #dc3545;
}

/* Mobile: stack form rows */
@media (max-width: 576px) {
    .form-section .row .col-md-4,
    .form-section .row .col-md-6 {
        width: 100% !important;
        flex: 0 0 100% !important;
        max-width: 100% !important;
    }

    .checkbox-group {
        grid-template-columns: 1fr 1fr;
        gap: 6px;
    }

    .radio-group {
        grid-template-columns: 1fr 1fr;
        gap: 6px;
    }
}
</style>

<!-- Main Content -->
<div class="container-fluid px-3 px-md-4">

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h4 mb-0" style="font-size: clamp(0.9rem, 3vw, 1.3rem); line-height: 1.3;"><?php echo __('clinical_pharmacy_intervention_report'); ?></h1>
        <div class="d-flex flex-wrap gap-2">
            <?php if (PagePermissions::hasPermission($currentPage, 'print_pharmacy')): ?>
            <button type="button" class="btn btn-outline-primary" onclick="window.print()">
                <i class="fas fa-print"></i> <span class="d-none d-sm-inline"><?php echo __('print'); ?></span>
            </button>
            <?php endif; ?>
            
            <?php if (PagePermissions::hasPermission($currentPage, 'export_pharmacy_excel')): ?>
            <button type="button" class="btn btn-outline-success" onclick="exportToExcel()">
                <i class="fas fa-file-excel"></i> <span class="d-none d-sm-inline"><?php echo __('export_excel'); ?></span>
            </button>
            <?php endif; ?>
            
            <a href="reports.php" class="btn btn-secondary">
                <i class="fas fa-arrow-<?php echo Translation::getDirection() == 'rtl' ? 'right' : 'left'; ?>"></i> <span class="d-none d-sm-inline"><?php echo __('back'); ?></span>
            </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" enctype="multipart/form-data" class="needs-validation" novalidate>
        
        <!-- Basic Information -->
        <div class="form-section">
            <h5><?php echo __('basic_patient_info'); ?></h5>
            
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label for="patient_name" class="form-label"><?php echo __('patient_name_label'); ?> <span class="required-field">*</span></label>
                    <input type="text" class="form-control" id="patient_name" name="patient_name" required placeholder="<?php echo __('enter_patient_name'); ?>">
                </div>
                <div class="col-md-4 mb-3">
                    <label for="mrn" class="form-label"><?php echo __('mrn_label'); ?> <span class="required-field">*</span></label>
                    <input type="text" class="form-control" id="mrn" name="mrn" required placeholder="<?php echo __('mrn_example'); ?>">
                </div>
                <div class="col-md-4 mb-3">
                    <label for="pharmacy_number" class="form-label"><?php echo __('pharmacy_number'); ?> <span class="required-field">*</span></label>
                    <input type="text" class="form-control" id="pharmacy_number" name="pharmacy_number" required placeholder="<?php echo __('example_pharmacy_number'); ?>">
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label"><?php echo __('gender_label'); ?> <span class="required-field">*</span></label>
                    <div class="mt-2">
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="gender" id="male" value="male" required>
                            <label class="form-check-label" for="male"><?php echo __('male'); ?></label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="gender" id="female" value="female" required>
                            <label class="form-check-label" for="female"><?php echo __('female'); ?></label>
                        </div>
                    </div>
                </div>
                <div class="col-md-6 mb-3"></div>
            </div>

            <div class="mb-3">
                <label class="form-label"><?php echo __('units_departments'); ?> <span class="required-field">*</span></label>
                <div class="row g-2">
                    <div class="col-md-2 col-sm-3 col-4">
                        <div class="form-check">
                            <input class="form-check-input unit-checkbox" type="checkbox" name="units[]" value="6th Floor" id="6th_floor">
                            <label class="form-check-label" for="6th_floor">6th Floor</label>
                        </div>
                    </div>
                    <div class="col-md-2 col-sm-3 col-4">
                        <div class="form-check">
                            <input class="form-check-input unit-checkbox" type="checkbox" name="units[]" value="5th floor" id="5th_floor">
                            <label class="form-check-label" for="5th_floor">5th floor</label>
                        </div>
                    </div>
                    <div class="col-md-2 col-sm-3 col-4">
                        <div class="form-check">
                            <input class="form-check-input unit-checkbox" type="checkbox" name="units[]" value="4th floor" id="4th_floor">
                            <label class="form-check-label" for="4th_floor">4th floor</label>
                        </div>
                    </div>
                    <div class="col-md-2 col-sm-3 col-4">
                        <div class="form-check">
                            <input class="form-check-input unit-checkbox" type="checkbox" name="units[]" value="4th ICU" id="4th_icu">
                            <label class="form-check-label" for="4th_icu">4th ICU</label>
                        </div>
                    </div>
                    <div class="col-md-2 col-sm-3 col-4">
                        <div class="form-check">
                            <input class="form-check-input unit-checkbox" type="checkbox" name="units[]" value="NICU" id="nicu">
                            <label class="form-check-label" for="nicu">NICU</label>
                        </div>
                    </div>
                    <div class="col-md-2 col-sm-3 col-4">
                        <div class="form-check">
                            <input class="form-check-input unit-checkbox" type="checkbox" name="units[]" value="OR" id="or">
                            <label class="form-check-label" for="or">OR</label>
                        </div>
                    </div>
                    <div class="col-md-2 col-sm-3 col-4">
                        <div class="form-check">
                            <input class="form-check-input unit-checkbox" type="checkbox" name="units[]" value="CCU" id="ccu">
                            <label class="form-check-label" for="ccu">CCU</label>
                        </div>
                    </div>
                    <div class="col-md-2 col-sm-3 col-4">
                        <div class="form-check">
                            <input class="form-check-input unit-checkbox" type="checkbox" name="units[]" value="Cath Lab" id="cath_lab">
                            <label class="form-check-label" for="cath_lab">Cath Lab</label>
                        </div>
                    </div>
                    <div class="col-md-2 col-sm-3 col-4">
                        <div class="form-check">
                            <input class="form-check-input unit-checkbox" type="checkbox" name="units[]" value="CICU" id="cicu">
                            <label class="form-check-label" for="cicu">CICU</label>
                        </div>
                    </div>
                    <div class="col-md-2 col-sm-3 col-4">
                        <div class="form-check">
                            <input class="form-check-input unit-checkbox" type="checkbox" name="units[]" value="KU" id="ku">
                            <label class="form-check-label" for="ku">KU</label>
                        </div>
                    </div>
                    <div class="col-md-2 col-sm-3 col-4">
                        <div class="form-check">
                            <input class="form-check-input unit-checkbox" type="checkbox" name="units[]" value="Day care" id="day_care">
                            <label class="form-check-label" for="day_care">Day care</label>
                        </div>
                    </div>
                    <div class="col-md-2 col-sm-3 col-4">
                        <div class="form-check">
                            <input class="form-check-input unit-checkbox" type="checkbox" name="units[]" value="GIT Lab" id="git_lab">
                            <label class="form-check-label" for="git_lab">GIT Lab</label>
                        </div>
                    </div>
                    <div class="col-md-2 col-sm-3 col-4">
                        <div class="form-check">
                            <input class="form-check-input unit-checkbox" type="checkbox" name="units[]" value="CABG unit" id="cabg">
                            <label class="form-check-label" for="cabg">CABG unit</label>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="drug_type" class="form-label"><?php echo __('drug_type'); ?> <span class="required-field">*</span></label>
                    <select class="form-select" id="drug_type" name="drug_type" required onchange="toggleDrugFields(this.value)">
                        <option value=""><?php echo __('select_drug_type'); ?></option>
                        <option value="antibiotic"><?php echo __('drug_type_antibiotic'); ?></option>
                        <option value="other"><?php echo __('drug_type_other'); ?></option>
                    </select>
                </div>
                <div class="col-md-6 mb-3" id="antibiotic_field" style="display:none;">
                    <label for="antibiotic_id" class="form-label"><?php echo __('antibiotic'); ?> <span class="required-field">*</span></label>
                    <select class="form-select" id="antibiotic_id" name="antibiotic_id">
                        <option value=""><?php echo __('select_antibiotic'); ?></option>
                        <?php foreach ($antibiotics as $antibiotic): ?>
                            <option value="<?php echo $antibiotic['id']; ?>">
                                <?php echo htmlspecialchars($antibiotic['antibiotic_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6 mb-3" id="other_medication_field" style="display:none;">
                    <label for="other_medication_name" class="form-label"><?php echo __('other_medication_name'); ?> <span class="required-field">*</span></label>
                    <input type="text" class="form-control" id="other_medication_name" name="other_medication_name"
                           placeholder="<?php echo __('enter_other_medication_name'); ?>">
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="report_date" class="form-label"><?php echo __('report_date_label'); ?> <span class="required-field">*</span></label>
                    <input type="date" class="form-control" id="report_date" name="report_date" 
                           value="<?php echo date('Y-m-d'); ?>" required>
                </div>
            </div>
        </div>

        <!-- Reported Event Details -->
        <div class="form-section">
            <h5><?php echo __('event_details'); ?></h5>
            
            <div class="mb-3">
                <label class="form-label"><?php echo __('problem_authority'); ?> <span class="required-field">*</span></label>
                <div class="radio-group">
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="problem_authority" value="physicians" id="physicians" required>
                        <label class="form-check-label" for="physicians"><?php echo __('physicians'); ?></label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="problem_authority" value="nurses" id="nurses" required>
                        <label class="form-check-label" for="nurses"><?php echo __('nurses'); ?></label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="problem_authority" value="pharmacist" id="pharmacist" required>
                        <label class="form-check-label" for="pharmacist"><?php echo __('pharmacist'); ?></label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="problem_authority" value="other" id="other_authority" required>
                        <label class="form-check-label" for="other_authority"><?php echo __('other'); ?></label>
                    </div>
                </div>
            </div>
            
            <div class="mb-3">
                <label for="problem_authority_name" class="form-label"><?php echo __('problem_authority_name'); ?></label>
                <input type="text" class="form-control" id="problem_authority_name" name="problem_authority_name" 
                       placeholder="<?php echo __('enter_authority_name'); ?>">
            </div>
        </div>

        <!-- Problem Definition -->
        <div class="form-section">
            <h5><?php echo __('problem_definition'); ?> <span class="required-field">*</span></h5>
            <div class="checkbox-group">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="problem_definition[]" value="medication_dispensing" id="medication_dispensing">
                    <label class="form-check-label" for="medication_dispensing"><?php echo __('medication_dispensing'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="problem_definition[]" value="medication_safety" id="medication_safety">
                    <label class="form-check-label" for="medication_safety"><?php echo __('medication_safety'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="problem_definition[]" value="medication_labelling" id="medication_labelling">
                    <label class="form-check-label" for="medication_labelling"><?php echo __('medication_labelling'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="problem_definition[]" value="wrong_regimen" id="wrong_regimen">
                    <label class="form-check-label" for="wrong_regimen"><?php echo __('wrong_regimen'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="problem_definition[]" value="illegible_hand_writing" id="illegible_hand_writing">
                    <label class="form-check-label" for="illegible_hand_writing"><?php echo __('illegible_hand_writing'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="problem_definition[]" value="arabic_writing" id="arabic_writing">
                    <label class="form-check-label" for="arabic_writing"><?php echo __('arabic_writing'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="problem_definition[]" value="transcription_violation" id="transcription_violation">
                    <label class="form-check-label" for="transcription_violation"><?php echo __('transcription_violation'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="problem_definition[]" value="inappropriate_drug_choice" id="inappropriate_drug_choice">
                    <label class="form-check-label" for="inappropriate_drug_choice"><?php echo __('inappropriate_drug_choice'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="problem_definition[]" value="patient_own_medication" id="patient_own_medication">
                    <label class="form-check-label" for="patient_own_medication"><?php echo __('patient_own_medication'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="problem_definition[]" value="wrong_preparation" id="wrong_preparation">
                    <label class="form-check-label" for="wrong_preparation"><?php echo __('wrong_preparation'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="problem_definition[]" value="wrong_administration" id="wrong_administration">
                    <label class="form-check-label" for="wrong_administration"><?php echo __('wrong_administration'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="problem_definition[]" value="drug_related_problem" id="drug_related_problem">
                    <label class="form-check-label" for="drug_related_problem"><?php echo __('drug_related_problem'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="problem_definition[]" value="illegible_abbreviations" id="illegible_abbreviations">
                    <label class="form-check-label" for="illegible_abbreviations"><?php echo __('illegible_abbreviations'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="problem_definition[]" value="other_problem" id="other_problem">
                    <label class="form-check-label" for="other_problem"><?php echo __('other'); ?></label>
                </div>
            </div>
        </div>

        <!-- Problem Cause -->
        <div class="form-section">
            <h5><?php echo __('problem_cause'); ?> <span class="required-field">*</span></h5>
            <div class="mb-3">
                <textarea class="form-control" name="problem_cause" rows="3" 
                          placeholder="<?php echo __('write_problem_cause_detail'); ?>" required></textarea>
            </div>
        </div>

        <!-- Antibiotic Classification -->
        <div class="form-section" id="antibiotic_classification_section" style="display:none;">
            <h5><?php echo __('antibiotic_classification'); ?> (WHO AWaRe) <span class="required-field">*</span></h5>
            <div class="mb-3">
                <select class="form-select" name="antibiotic_classification" id="antibiotic_classification">
                    <option value=""><?php echo __('select_antibiotic_classification'); ?></option>
                    <option value="access"><?php echo __('access_antibiotics'); ?></option>
                    <option value="watch"><?php echo __('watch_antibiotics'); ?></option>
                    <option value="reserve"><?php echo __('reserve_antibiotics'); ?></option>
                </select>
                <div class="form-text">
                    <small>
                        <strong>Access:</strong> <?php echo __('access_description'); ?><br>
                        <strong>Watch:</strong> <?php echo __('watch_description'); ?><br>
                        <strong>Reserve:</strong> <?php echo __('reserve_description'); ?>
                    </small>
                </div>
            </div>
        </div>

        <!-- Intervention Choice -->
        <div class="form-section">
            <h5><?php echo __('intervention_choice'); ?> <span class="required-field">*</span></h5>
            <div class="checkbox-group">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="intervention_choice[]" value="addition_new_drug" id="addition_new_drug">
                    <label class="form-check-label" for="addition_new_drug"><?php echo __('addition_new_drug'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="intervention_choice[]" value="drug_discontinuation" id="drug_discontinuation">
                    <label class="form-check-label" for="drug_discontinuation"><?php echo __('drug_discontinuation'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="intervention_choice[]" value="changing_another_agent" id="changing_another_agent">
                    <label class="form-check-label" for="changing_another_agent"><?php echo __('changing_another_agent'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="intervention_choice[]" value="changing_administration_route" id="changing_administration_route">
                    <label class="form-check-label" for="changing_administration_route"><?php echo __('changing_administration_route'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="intervention_choice[]" value="monitoring" id="monitoring">
                    <label class="form-check-label" for="monitoring"><?php echo __('monitoring'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="intervention_choice[]" value="dose_adjustment" id="dose_adjustment">
                    <label class="form-check-label" for="dose_adjustment"><?php echo __('dose_adjustment'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="intervention_choice[]" value="other_intervention" id="other_intervention">
                    <label class="form-check-label" for="other_intervention"><?php echo __('other'); ?></label>
                </div>
            </div>
        </div>

        <!-- Degree of Damage -->
        <div class="form-section">
            <h5><?php echo __('degree_of_damage'); ?> <span class="required-field">*</span></h5>
            <div class="checkbox-group">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="degree_of_damage[]" value="degree_damage_presumed" id="degree_damage_presumed">
                    <label class="form-check-label" for="degree_damage_presumed"><?php echo __('degree_damage_presumed'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="degree_of_damage[]" value="no_damage_presumed" id="no_damage_presumed">
                    <label class="form-check-label" for="no_damage_presumed"><?php echo __('no_damage_presumed'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="degree_of_damage[]" value="ability_cause_damage" id="ability_cause_damage">
                    <label class="form-check-label" for="ability_cause_damage"><?php echo __('ability_cause_damage'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="degree_of_damage[]" value="monitoring_required_avoid_damage" id="monitoring_required_avoid_damage">
                    <label class="form-check-label" for="monitoring_required_avoid_damage"><?php echo __('monitoring_required_avoid_damage'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="degree_of_damage[]" value="temporary_damage" id="temporary_damage">
                    <label class="form-check-label" for="temporary_damage"><?php echo __('temporary_damage'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="degree_of_damage[]" value="cause_icu_admission" id="cause_icu_admission">
                    <label class="form-check-label" for="cause_icu_admission"><?php echo __('cause_icu_admission'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="degree_of_damage[]" value="permanent_damage" id="permanent_damage">
                    <label class="form-check-label" for="permanent_damage"><?php echo __('permanent_damage'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="degree_of_damage[]" value="cause_mortality" id="cause_mortality">
                    <label class="form-check-label" for="cause_mortality"><?php echo __('cause_mortality'); ?></label>
                </div>
            </div>
        </div>

        <!-- Result of Intervention -->
        <div class="form-section">
            <h5><?php echo __('result_of_intervention'); ?></h5>
            <div class="radio-group">
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="result_of_intervention" value="accept" id="accept">
                    <label class="form-check-label" for="accept"><?php echo __('accept'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="result_of_intervention" value="reject" id="reject">
                    <label class="form-check-label" for="reject"><?php echo __('reject'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="result_of_intervention" value="postpone" id="postpone">
                    <label class="form-check-label" for="postpone"><?php echo __('postpone'); ?></label>
                </div>
            </div>
        </div>

        <!-- Corrective Action -->
        <div class="form-section">
            <h5><?php echo __('corrective_action'); ?> <span class="required-field">*</span></h5>
            <div class="mb-3">
                <textarea class="form-control" id="corrective_action" name="corrective_action" rows="3" 
                          placeholder="<?php echo __('write_corrective_action'); ?>" required></textarea>
            </div>
            
            <label class="form-label"><?php echo __('result_of_corrective_action'); ?> <span class="required-field">*</span></label>
            <div class="radio-group">
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="result_of_corrective_action" value="damage_avoided" id="damage_avoided" required>
                    <label class="form-check-label" for="damage_avoided"><?php echo __('damage_avoided'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="result_of_corrective_action" value="reported_to_avoid_future_damage" id="reported_avoid_future" required>
                    <label class="form-check-label" for="reported_avoid_future"><?php echo __('reported_to_avoid_future_damage'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="result_of_corrective_action" value="no_corrective_action" id="no_corrective_action" required>
                    <label class="form-check-label" for="no_corrective_action"><?php echo __('no_corrective_action'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="result_of_corrective_action" value="corrective_action_refused" id="corrective_action_refused" required>
                    <label class="form-check-label" for="corrective_action_refused"><?php echo __('corrective_action_refused'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="result_of_corrective_action" value="physician_agree_no_action" id="physician_agree_no_action" required>
                    <label class="form-check-label" for="physician_agree_no_action"><?php echo __('physician_agree_no_action'); ?></label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="result_of_corrective_action" value="other_result" id="other_result" required>
                    <label class="form-check-label" for="other_result"><?php echo __('other'); ?></label>
                </div>
            </div>
        </div>

        <!-- Attachments -->
        <div class="form-section">
            <h5><?php echo __('details_and_attachments'); ?></h5>
            <div class="mb-3">
                <label for="attachments" class="form-label"><?php echo __('upload_files'); ?></label>
                <input type="file" class="form-control" id="attachments" name="attachments[]" multiple 
                       accept=".pdf,.doc,.docx,.jpg,.jpeg,.png,.gif">
                <div class="form-text"><?php echo __('supported_file_types'); ?></div>
            </div>
        </div>

        <!-- Recommendations -->
        <div class="form-section">
            <h5><?php echo __('recommendations'); ?> <span class="required-field">*</span></h5>
            <div class="mb-3">
                <textarea class="form-control" id="recommendations" name="recommendations" rows="4" 
                          placeholder="<?php echo __('write_recommendations'); ?>" required></textarea>
            </div>
        </div>

        <!-- Submit Buttons -->
        <div class="d-flex gap-2 mb-4">
            <?php if (PagePermissions::hasPermission($currentPage, 'add_intervention')): ?>
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-save"></i> <?php echo __('save_report'); ?>
            </button>
            <?php endif; ?>
            
            <a href="reports.php" class="btn btn-secondary">
                <i class="fas fa-times"></i> <?php echo __('cancel'); ?>
            </a>
        </div>
    </form>
</div>

<script>
// Toggle drug fields based on drug type selection
function toggleDrugFields(value) {
    const antibioticField = document.getElementById('antibiotic_field');
    const otherMedField = document.getElementById('other_medication_field');
    const classificationSection = document.getElementById('antibiotic_classification_section');
    const antibioticSelect = document.getElementById('antibiotic_id');
    const otherMedInput = document.getElementById('other_medication_name');
    const classificationSelect = document.getElementById('antibiotic_classification');

    if (value === 'antibiotic') {
        antibioticField.style.display = 'block';
        otherMedField.style.display = 'none';
        classificationSection.style.display = 'block';
        otherMedInput.value = '';
        classificationSelect.required = true;
    } else if (value === 'other') {
        antibioticField.style.display = 'none';
        otherMedField.style.display = 'block';
        classificationSection.style.display = 'none';
        antibioticSelect.value = '';
        classificationSelect.value = '';
        classificationSelect.required = false;
    } else {
        antibioticField.style.display = 'none';
        otherMedField.style.display = 'none';
        classificationSection.style.display = 'none';
        antibioticSelect.value = '';
        otherMedInput.value = '';
        classificationSelect.value = '';
        classificationSelect.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) {
                // Validate drug type
                const drugType = document.getElementById('drug_type').value;
                if (!drugType) {
                    event.preventDefault();
                    event.stopPropagation();
                    alert('<?php echo __('please_select_drug_type'); ?>');
                    document.getElementById('drug_type').focus();
                    return false;
                }
                if (drugType === 'antibiotic' && !document.getElementById('antibiotic_id').value) {
                    event.preventDefault();
                    event.stopPropagation();
                    alert('<?php echo __('please_select_antibiotic'); ?>');
                    document.getElementById('antibiotic_id').focus();
                    return false;
                }
                if (drugType === 'other' && !document.getElementById('other_medication_name').value.trim()) {
                    event.preventDefault();
                    event.stopPropagation();
                    alert('<?php echo __('please_enter_medication_name'); ?>');
                    document.getElementById('other_medication_name').focus();
                    return false;
                }

                // Check if at least one problem definition is selected
                const problemDefs = document.querySelectorAll('input[name="problem_definition[]"]:checked');
                if (problemDefs.length === 0) {
                    event.preventDefault();
                    event.stopPropagation();
                    alert('<?php echo __('select_at_least_one_problem_definition'); ?>');
                    return false;
                }
                
                // Check if problem cause is filled
                const problemCause = document.querySelector('textarea[name="problem_cause"]');
                if (!problemCause.value.trim()) {
                    event.preventDefault();
                    event.stopPropagation();
                    alert('<?php echo __('please_write_problem_cause'); ?>');
                    problemCause.focus();
                    return false;
                }
                
                // Check if antibiotic classification is selected (only required for antibiotics)
                const antibioticClassification = document.getElementById('antibiotic_classification');
                if (drugType === 'antibiotic' && !antibioticClassification.value) {
                    event.preventDefault();
                    event.stopPropagation();
                    alert('<?php echo __('please_select_antibiotic_classification'); ?>');
                    antibioticClassification.focus();
                    return false;
                }
                
                // Check if at least one intervention choice is selected
                const interventions = document.querySelectorAll('input[name="intervention_choice[]"]:checked');
                if (interventions.length === 0) {
                    event.preventDefault();
                    event.stopPropagation();
                    alert('<?php echo __('select_at_least_one_intervention'); ?>');
                    return false;
                }
                
                // Check if at least one degree of damage is selected
                const damages = document.querySelectorAll('input[name="degree_of_damage[]"]:checked');
                if (damages.length === 0) {
                    event.preventDefault();
                    event.stopPropagation();
                    alert('<?php echo __('select_at_least_one_damage_degree'); ?>');
                    return false;
                }
                
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();

// File upload validation
document.getElementById('attachments').addEventListener('change', function() {
    const files = this.files;
    const maxFiles = 5;
    const maxSize = 10 * 1024 * 1024; // 10MB
    
    if (files.length > maxFiles) {
        alert('<?php echo __('max_files_upload'); ?>');
        this.value = '';
        return;
    }
    
    for (let i = 0; i < files.length; i++) {
        if (files[i].size > maxSize) {
            alert('<?php echo __('file_size_too_large'); ?>: ' + files[i].name);
            this.value = '';
            return;
        }
    }
});
</script>

</div> <!-- End container-fluid -->

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