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

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

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

// إنشاء اتصال قاعدة البيانات
$db = new Database();
$conn = $db->getConnection();

// إنشاء الجداول المطلوبة إذا لم تكن موجودة
try {
    // التحقق من وجود جدول users أولاً
    $stmt = $conn->query("SHOW TABLES LIKE 'users'");
    if ($stmt->rowCount() == 0) {
        // إنشاء جدول المستخدمين إذا لم يكن موجوداً
        $conn->exec("CREATE TABLE users (
            id INT AUTO_INCREMENT PRIMARY KEY,
            username VARCHAR(50) UNIQUE NOT NULL,
            email VARCHAR(100) UNIQUE NOT NULL,
            password VARCHAR(255) NOT NULL,
            full_name VARCHAR(100) NOT NULL,
            role ENUM('admin', 'pharmacist', 'user') DEFAULT 'user',
            is_active BOOLEAN DEFAULT TRUE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )");
    }
    
    // جدول محاضر الكسر
    $conn->exec("CREATE TABLE IF NOT EXISTS breakage_reports (
        id INT AUTO_INCREMENT PRIMARY KEY,
        report_date DATE NOT NULL,
        item_name VARCHAR(255) NOT NULL,
        quantity INT NOT NULL,
        reason TEXT,
        reported_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_breakage_date (report_date),
        INDEX idx_breakage_reported_by (reported_by)
    )");
    
    // جدول محاضر إعدام الأدوية المخدرة
    $conn->exec("CREATE TABLE IF NOT EXISTS narcotic_disposal_reports (
        id INT AUTO_INCREMENT PRIMARY KEY,
        report_date DATE NOT NULL,
        drug_name VARCHAR(255) NOT NULL,
        quantity INT NOT NULL,
        disposal_reason ENUM('expired', 'damaged', 'contaminated', 'other') DEFAULT 'expired',
        notes TEXT,
        reported_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_narcotic_date (report_date),
        INDEX idx_narcotic_reported_by (reported_by)
    )");
    
    // جدول محاضر إعدام الأدوية منتهية الصلاحية
    $conn->exec("CREATE TABLE IF NOT EXISTS expired_drugs_disposal (
        id INT AUTO_INCREMENT PRIMARY KEY,
        report_date DATE NOT NULL,
        drug_name VARCHAR(255) NOT NULL,
        quantity INT NOT NULL,
        expiry_date DATE,
        batch_number VARCHAR(100),
        notes TEXT,
        reported_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_expired_date (report_date),
        INDEX idx_expired_reported_by (reported_by)
    )");
} catch (PDOException $e) {
    // تجاهل الأخطاء إذا كانت الجداول موجودة بالفعل
}

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

// معالجة النماذج
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        if (isset($_POST['form_type'])) {
            switch ($_POST['form_type']) {
                case 'breakage_report':
                    $stmt = $conn->prepare("INSERT INTO breakage_reports (report_date, item_name, quantity, reason, reported_by) VALUES (?, ?, ?, ?, ?)");
                    $stmt->execute([
                        $_POST['report_date'],
                        $_POST['item_name'],
                        $_POST['quantity'],
                        $_POST['reason'],
                        $_SESSION['user_id']
                    ]);
                    $message = __('breakage_success');
                    break;
                    
                case 'narcotic_disposal':
                    $stmt = $conn->prepare("INSERT INTO narcotic_disposal_reports (report_date, drug_name, quantity, disposal_reason, notes, reported_by) VALUES (?, ?, ?, ?, ?, ?)");
                    $stmt->execute([
                        $_POST['report_date'],
                        $_POST['drug_name'],
                        $_POST['quantity'],
                        $_POST['disposal_reason'],
                        $_POST['notes'],
                        $_SESSION['user_id']
                    ]);
                    $message = __('narcotic_success');
                    break;
                    
                case 'expired_disposal':
                    $stmt = $conn->prepare("INSERT INTO expired_drugs_disposal (report_date, drug_name, quantity, expiry_date, batch_number, notes, reported_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([
                        $_POST['report_date'],
                        $_POST['drug_name'],
                        $_POST['quantity'],
                        $_POST['expiry_date'],
                        $_POST['batch_number'],
                        $_POST['notes'],
                        $_SESSION['user_id']
                    ]);
                    $message = __('expired_success');
                    break;
                    
                case 'operations_data':
                    // إدخال بيانات العمليات في جدول antibiotic_reports
                    $stmt = $conn->prepare("INSERT INTO antibiotic_reports (
                        patient_id, reporting_pharmacist_id, unit_id, antibiotic_id, 
                        report_date, intervention_choice, degree_of_damage, status
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                    
                    $stmt->execute([
                        $_POST['patient_id'],
                        $_SESSION['user_id'],
                        $_POST['unit_id'],
                        $_POST['antibiotic_id'],
                        $_POST['report_date'],
                        $_POST['intervention_choice'],
                        $_POST['degree_of_damage'],
                        $_POST['status']
                    ]);
                    $message = __('operation_data_success');
                    break;
            }
        }
        
        // معالجة الحذف
        if (isset($_POST['delete_record'])) {
            $table = $_POST['table'];
            $id = $_POST['id'];
            
            $allowed_tables = ['breakage_reports', 'narcotic_disposal_reports', 'expired_drugs_disposal'];
            if (in_array($table, $allowed_tables)) {
                $stmt = $conn->prepare("DELETE FROM $table WHERE id = ?");
                $stmt->execute([$id]);
                $message = __('record_deleted_success');
            }
        }
        
    } catch (PDOException $e) {
        $error = __('error_occurred') . ": " . $e->getMessage();
    }
}

// جلب البيانات للعرض
try {
    // محاضر الكسر
    $breakage_stmt = $conn->prepare("
        SELECT br.*, u.full_name as reporter_name 
        FROM breakage_reports br 
        LEFT JOIN users u ON br.reported_by = u.id 
        ORDER BY br.created_at DESC 
        LIMIT 10
    ");
    $breakage_stmt->execute();
    $breakage_reports = $breakage_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // محاضر إعدام الأدوية المخدرة
    $narcotic_stmt = $conn->prepare("
        SELECT ndr.*, u.full_name as reporter_name 
        FROM narcotic_disposal_reports ndr 
        LEFT JOIN users u ON ndr.reported_by = u.id 
        ORDER BY ndr.created_at DESC 
        LIMIT 10
    ");
    $narcotic_stmt->execute();
    $narcotic_reports = $narcotic_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // محاضر إعدام الأدوية منتهية الصلاحية
    $expired_stmt = $conn->prepare("
        SELECT edd.*, u.full_name as reporter_name 
        FROM expired_drugs_disposal edd 
        LEFT JOIN users u ON edd.reported_by = u.id 
        ORDER BY edd.created_at DESC 
        LIMIT 10
    ");
    $expired_stmt->execute();
    $expired_reports = $expired_stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    $error = __('error_fetching_data') . ": " . $e->getMessage();
    $breakage_reports = [];
    $narcotic_reports = [];
    $expired_reports = [];
}

include 'includes/header.php';
?>

<style>
.form-card {
    border: none;
    border-radius: 15px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    margin-bottom: 30px;
    overflow: hidden;
}

.form-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 20px;
    margin: -20px -20px 20px -20px;
}

.form-header h5 {
    margin: 0;
    font-weight: bold;
}

.form-group label {
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 8px;
}

.form-control, .form-select {
    border-radius: 10px;
    border: 2px solid #e9ecef;
    padding: 12px 15px;
    transition: all 0.3s ease;
}

.form-control:focus, .form-select:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
}

.btn-submit {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    border-radius: 25px;
    padding: 12px 30px;
    color: white;
    font-weight: 600;
    transition: all 0.3s ease;
}

.btn-submit:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
    color: white;
}

.alert {
    border-radius: 10px;
    border: none;
}

.nav-tabs .nav-link {
    border-radius: 10px 10px 0 0;
    border: 1px solid #cbd5e1 !important;
    background: #f1f5f9 !important;
    color: #475569 !important;
    font-weight: 700;
    margin-right: 5px;
    padding: 12px 25px;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 8px;
}

.nav-tabs .nav-link:hover {
    background: #e2e8f0 !important;
    color: #1e293b !important;
}

.nav-tabs .nav-link.active {
    background: linear-gradient(135deg, #5e35b1 0%, #4c2c92 100%) !important;
    color: white !important;
    border-color: #5e35b1 !important;
}

.toggle-btn {
    background: #f1f5f9;
    border: 2px solid #cbd5e1;
    color: #475569;
    padding: 12px 25px;
    border-radius: 25px;
    font-weight: 700;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 15px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.toggle-btn.active {
    background: linear-gradient(135deg, #5e35b1 0%, #4c2c92 100%);
    color: white !important;
    border-color: #5e35b1;
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(94, 53, 177, 0.3);
}

.toggle-btn i, .nav-link i {
    color: inherit !important;
}

.toggle-btn:hover:not(.active) {
    background: #f1f5f9;
    color: #334155;
    border-color: #cbd5e1;
}

.toggle-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.content-section {
    display: none;
}

.content-section.active {
    display: block;
}

.card {
    border: none;
    border-radius: 15px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    transition: all 0.3s ease;
    margin-bottom: 20px;
}

.card-header {
    border-radius: 15px 15px 0 0 !important;
    background: linear-gradient(135deg, #5e35b1 0%, #4c2c92 100%) !important;
}

.action-btn {
    border-radius: 25px;
    padding: 12px 30px;
    font-weight: 600;
    margin: 5px;
    transition: all 0.3s ease;
    border: none;
}

.action-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

.table-section {
    margin-top: 30px;
}

.table-section h5 {
    color: #495057;
    margin-bottom: 15px;
    font-weight: 600;
}

@media print {
    .no-print { display: none; }
}
</style>


    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4 no-print">
        <div>
            <h1 class="h3 mb-0" style="color: #667eea;">
                <i class="fas fa-clipboard-check me-2"></i>
                <?php echo __('operations_management_title'); ?>
            </h1>
            <p class="text-muted mb-0"><?php echo __('operations_management_subtitle'); ?></p>
        </div>
        <div>
            <?php if (PagePermissions::hasPermission($currentPage, 'view_operations')): ?>
            <a href="operations_team_report.php" class="btn btn-info me-2">
                <i class="fas fa-chart-line me-2"></i> <?php echo __('view_report'); ?>
            </a>
            <?php endif; ?>
            
            <?php if (PagePermissions::hasPermission($currentPage, 'print_operations')): ?>
            <button type="button" class="btn btn-outline-primary action-btn" onclick="window.print()">
                <i class="fas fa-print me-2"></i> <?php echo __('print'); ?>
            </button>
            <?php endif; ?>
            
            <?php if (PagePermissions::hasPermission($currentPage, 'export_operations_excel')): ?>
            <button type="button" class="btn btn-outline-success action-btn" onclick="exportToExcel()">
                <i class="fas fa-file-excel me-2"></i> <?php echo __('export_excel'); ?>
            </button>
            <?php endif; ?>
            
            <a href="index.php" class="btn btn-outline-secondary action-btn">
                <i class="fas fa-arrow-<?php echo Translation::getDirection() == 'rtl' ? 'right' : 'left'; ?> me-2"></i> <?php echo __('back'); ?>
            </a>
        </div>
    </div>

    <!-- Toggle Buttons -->
    <div class="toggle-buttons no-print">
        <?php if (PagePermissions::hasPermission($currentPage, 'add_operation')): ?>
        <button class="toggle-btn active" onclick="showSection('create')">
            <i class="fas fa-plus me-2"></i>
            <?php echo __('enter_new_data'); ?>
        </button>
        <?php endif; ?>
        
        <?php if (PagePermissions::hasPermission($currentPage, 'view_operations')): ?>
        <button class="toggle-btn" onclick="showSection('view')">
            <i class="fas fa-eye me-2"></i>
            <?php echo __('view_saved_reports'); ?>
        </button>
        <?php endif; ?>
    </div>

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

    <?php if (!empty($error)): ?>
        <div class="alert alert-danger alert-dismissible fade show no-print">
            <i class="fas fa-exclamation-circle me-2"></i>
            <?php echo $error; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Create Section -->
    <div id="create-section" class="content-section active">
        <!-- التبويبات -->
        <ul class="nav nav-tabs" id="operationsTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="breakage-tab" data-bs-toggle="tab" data-bs-target="#breakage" type="button" role="tab">
                    <i class="fas fa-broken-image me-2"></i><?php echo __('breakage_report'); ?>
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="narcotic-tab" data-bs-toggle="tab" data-bs-target="#narcotic" type="button" role="tab">
                    <i class="fas fa-skull-crossbones me-2"></i><?php echo __('narcotic_disposal'); ?>
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="expired-tab" data-bs-toggle="tab" data-bs-target="#expired" type="button" role="tab">
                    <i class="fas fa-calendar-times me-2"></i><?php echo __('expired_disposal'); ?>
                </button>
            </li>
           
        </ul>

        <div class="tab-content" id="operationsTabsContent">
            <!-- محاضر الكسر -->
            <div class="tab-pane fade show active" id="breakage" role="tabpanel">
                <form method="POST" action="">
                    <input type="hidden" name="form_type" value="breakage_report">
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="breakage_date"><?php echo __('report_date_field'); ?></label>
                                <input type="date" class="form-control" id="breakage_date" name="report_date" value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="item_name"><?php echo __('item_name'); ?></label>
                                <input type="text" class="form-control" id="item_name" name="item_name" placeholder="<?php echo __('example_insulin_ampoules'); ?>" required>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="quantity"><?php echo __('quantity'); ?></label>
                                <input type="number" class="form-control" id="quantity" name="quantity" min="1" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="reason"><?php echo __('reason'); ?></label>
                                <select class="form-select" id="reason" name="reason" required>
                                    <option value=""><?php echo __('select_reason'); ?></option>
                                    <option value="كسر أثناء النقل"><?php echo __('broken_during_transport'); ?></option>
                                    <option value="سقوط من الرف"><?php echo __('fell_from_shelf'); ?></option>
                                    <option value="خطأ في التعامل"><?php echo __('handling_error'); ?></option>
                                    <option value="عيب في التصنيع"><?php echo __('manufacturing_defect'); ?></option>
                                    <option value="أخرى"><?php echo __('other'); ?></option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-submit">
                        <i class="fas fa-save me-2"></i><?php echo __('save_breakage_report'); ?>
                    </button>
                </form>
            </div>

            <!-- إعدام أدوية مخدرة -->
            <div class="tab-pane fade" id="narcotic" role="tabpanel">
                <form method="POST" action="">
                    <input type="hidden" name="form_type" value="narcotic_disposal">
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="narcotic_date"><?php echo __('report_date_field'); ?></label>
                                <input type="date" class="form-control" id="narcotic_date" name="report_date" value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="drug_name"><?php echo __('drug_name'); ?></label>
                                <input type="text" class="form-control" id="drug_name" name="drug_name" placeholder="<?php echo __('example_morphine_ampoules'); ?>" required>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="narcotic_quantity"><?php echo __('quantity'); ?></label>
                                <input type="number" class="form-control" id="narcotic_quantity" name="quantity" min="1" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="disposal_reason"><?php echo __('disposal_reason'); ?></label>
                                <select class="form-select" id="disposal_reason" name="disposal_reason" required>
                                    <option value=""><?php echo __('select_reason'); ?></option>
                                    <option value="expired"><?php echo __('expired'); ?></option>
                                    <option value="damaged"><?php echo __('damaged'); ?></option>
                                    <option value="contaminated"><?php echo __('contaminated'); ?></option>
                                    <option value="other"><?php echo __('other'); ?></option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group mb-3">
                                <label for="notes"><?php echo __('notes'); ?></label>
                                <textarea class="form-control" id="notes" name="notes" rows="3" placeholder="<?php echo __('additional_notes'); ?>"></textarea>
                            </div>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-submit">
                        <i class="fas fa-save me-2"></i><?php echo __('save_narcotic_disposal_report'); ?>
                    </button>
                </form>
            </div>

            <!-- إعدام أدوية منتهية الصلاحية -->
            <div class="tab-pane fade" id="expired" role="tabpanel">
                <form method="POST" action="">
                    <input type="hidden" name="form_type" value="expired_disposal">
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="expired_date"><?php echo __('report_date_field'); ?></label>
                                <input type="date" class="form-control" id="expired_date" name="report_date" value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="expired_drug_name"><?php echo __('drug_name'); ?></label>
                                <input type="text" class="form-control" id="expired_drug_name" name="drug_name" placeholder="<?php echo __('example_amoxicillin_capsules'); ?>" required>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label for="expired_quantity"><?php echo __('quantity'); ?></label>
                                <input type="number" class="form-control" id="expired_quantity" name="quantity" min="1" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label for="expiry_date"><?php echo __('expiry_date'); ?></label>
                                <input type="date" class="form-control" id="expiry_date" name="expiry_date" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label for="batch_number"><?php echo __('batch_number'); ?></label>
                                <input type="text" class="form-control" id="batch_number" name="batch_number" placeholder="<?php echo __('batch_number'); ?>">
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group mb-3">
                                <label for="expired_notes"><?php echo __('notes'); ?></label>
                                <textarea class="form-control" id="expired_notes" name="notes" rows="3" placeholder="<?php echo __('additional_notes'); ?>"></textarea>
                            </div>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-submit">
                        <i class="fas fa-save me-2"></i><?php echo __('save_disposal_report'); ?>
                    </button>
                </form>
            </div>

            <!-- بيانات العمليات -->
            <div class="tab-pane fade" id="operations" role="tabpanel">
                <form method="POST" action="">
                    <input type="hidden" name="form_type" value="operations_data">
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="operation_date"><?php echo __('operation_date'); ?></label>
                                <input type="date" class="form-control" id="operation_date" name="report_date" value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="patient_id"><?php echo __('patient'); ?></label>
                                <select class="form-select" id="patient_id" name="patient_id" required>
                                    <option value=""><?php echo __('select_patient'); ?></option>
                                    <?php
                                    // جلب المرضى من قاعدة البيانات
                                    try {
                                        $patients_stmt = $conn->query("SELECT id, patient_name, mrn FROM patients ORDER BY patient_name");
                                        $patients = $patients_stmt->fetchAll(PDO::FETCH_ASSOC);
                                        foreach ($patients as $patient): ?>
                                            <option value="<?php echo $patient['id']; ?>">
                                                <?php echo $patient['patient_name'] . ' - ' . $patient['mrn']; ?>
                                            </option>
                                        <?php endforeach;
                                    } catch (PDOException $e) {
                                        // في حالة عدم وجود الجدول
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="unit_id"><?php echo __('department'); ?></label>
                                <select class="form-select" id="unit_id" name="unit_id" required>
                                    <option value=""><?php echo __('select_department'); ?></option>
                                    <?php
                                    // جلب الأقسام من قاعدة البيانات
                                    try {
                                        $units_stmt = $conn->query("SELECT id, unit_name FROM units WHERE is_active = 1 ORDER BY unit_name");
                                        $units = $units_stmt->fetchAll(PDO::FETCH_ASSOC);
                                        foreach ($units as $unit): ?>
                                            <option value="<?php echo $unit['id']; ?>"><?php echo $unit['unit_name']; ?></option>
                                        <?php endforeach;
                                    } catch (PDOException $e) {
                                        // في حالة عدم وجود الجدول
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="antibiotic_id"><?php echo __('antibiotic'); ?></label>
                                <select class="form-select" id="antibiotic_id" name="antibiotic_id" required>
                                    <option value=""><?php echo __('select_antibiotic'); ?></option>
                                    <?php
                                    // جلب المضادات الحيوية من قاعدة البيانات
                                    try {
                                        $antibiotics_stmt = $conn->query("SELECT id, antibiotic_name FROM antibiotics WHERE is_active = 1 ORDER BY antibiotic_name");
                                        $antibiotics = $antibiotics_stmt->fetchAll(PDO::FETCH_ASSOC);
                                        foreach ($antibiotics as $antibiotic): ?>
                                            <option value="<?php echo $antibiotic['id']; ?>"><?php echo $antibiotic['antibiotic_name']; ?></option>
                                        <?php endforeach;
                                    } catch (PDOException $e) {
                                        // في حالة عدم وجود الجدول
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="intervention_choice"><?php echo __('intervention_type'); ?></label>
                                <select class="form-select" id="intervention_choice" name="intervention_choice" required>
                                    <option value=""><?php echo __('select_intervention_type'); ?></option>
                                    <option value="injection"><?php echo __('injection'); ?></option>
                                    <option value="catheter"><?php echo __('catheter'); ?></option>
                                    <option value="dental"><?php echo __('dental'); ?></option>
                                    <option value="oral"><?php echo __('oral'); ?></option>
                                    <option value="topical"><?php echo __('topical'); ?></option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="degree_of_damage"><?php echo __('anesthesia_type'); ?></label>
                                <select class="form-select" id="degree_of_damage" name="degree_of_damage" required>
                                    <option value=""><?php echo __('select_anesthesia_type'); ?></option>
                                    <option value="general"><?php echo __('general_anesthesia'); ?></option>
                                    <option value="spinal"><?php echo __('spinal_anesthesia'); ?></option>
                                    <option value="local"><?php echo __('local_anesthesia'); ?></option>
                                    <option value="none"><?php echo __('no_anesthesia'); ?></option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="status"><?php echo __('follow_up_status'); ?></label>
                                <select class="form-select" id="status" name="status" required>
                                    <option value=""><?php echo __('select_status'); ?></option>
                                    <option value="pending"><?php echo __('pending'); ?></option>
                                    <option value="in_progress"><?php echo __('in_progress'); ?></option>
                                    <option value="completed"><?php echo __('completed'); ?></option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-submit">
                        <i class="fas fa-save me-2"></i><?php echo __('save_operation_data'); ?>
                    </button>
                </form>
            </div>
        </div>
    </div>
    <!-- View Section -->
    <div id="view-section" class="content-section">
        <!-- محاضر الكسر -->
        <div class="table-section">
            <div class="card">
                <div class="card-header text-white">
                    <h5 class="mb-0">
                        <i class="fas fa-broken-image me-2"></i>
                        <?php echo __('breakage_reports'); ?>
                    </h5>
                </div>
                <div class="card-body">
                    <?php if (count($breakage_reports) > 0): ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead class="table-dark">
                                <tr>
                                    <th><?php echo __('date'); ?></th>
                                    <th><?php echo __('item_name'); ?></th>
                                    <th><?php echo __('quantity'); ?></th>
                                    <th><?php echo __('reason'); ?></th>
                                    <th><?php echo __('reporter'); ?></th>
                                    <th><?php echo __('actions'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($breakage_reports as $report): ?>
                                <tr>
                                    <td><?php echo date('d/m/Y', strtotime($report['report_date'])); ?></td>
                                    <td><?php echo htmlspecialchars($report['item_name']); ?></td>
                                    <td><span class="badge bg-warning"><?php echo $report['quantity']; ?></span></td>
                                    <td><?php echo htmlspecialchars($report['reason'] ?? __('not_specified')); ?></td>
                                    <td><?php echo htmlspecialchars($report['reporter_name'] ?? __('not_specified')); ?></td>
                                    <td>
                                        <form method="POST" style="display: inline;" 
                                              onsubmit="return confirm('<?php echo __('confirm_delete_record'); ?>')">
                                            <input type="hidden" name="delete_record" value="1">
                                            <input type="hidden" name="table" value="breakage_reports">
                                            <input type="hidden" name="id" value="<?php echo $report['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-danger">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php else: ?>
                    <div class="text-center py-4">
                        <i class="fas fa-broken-image fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted"><?php echo __('no_breakage_reports'); ?></h5>
                        <p class="text-muted"><?php echo __('no_breakage_reports_message'); ?></p>
                        <div class="d-flex gap-2 justify-content-center">
                            <button class="btn btn-primary" onclick="showSection('create')">
                                <i class="fas fa-plus me-1"></i> <?php echo __('add_breakage_report'); ?>
                            </button>
                            <a href="operations_team_report.php" class="btn btn-info">
                                <i class="fas fa-chart-line me-1"></i> <?php echo __('view_report'); ?>
                            </a>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- محاضر إعدام الأدوية المخدرة -->
        <div class="table-section">
            <div class="card">
                <div class="card-header text-white">
                    <h5 class="mb-0">
                        <i class="fas fa-pills me-2"></i>
                        <?php echo __('narcotic_disposal_reports'); ?>
                    </h5>
                </div>
                <div class="card-body">
                    <?php if (count($narcotic_reports) > 0): ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead class="table-dark">
                                <tr>
                                    <th><?php echo __('date'); ?></th>
                                    <th><?php echo __('drug_name'); ?></th>
                                    <th><?php echo __('quantity'); ?></th>
                                    <th><?php echo __('disposal_reason'); ?></th>
                                    <th><?php echo __('reporter'); ?></th>
                                    <th><?php echo __('actions'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($narcotic_reports as $report): ?>
                                <tr>
                                    <td><?php echo date('d/m/Y', strtotime($report['report_date'])); ?></td>
                                    <td><?php echo htmlspecialchars($report['drug_name']); ?></td>
                                    <td><span class="badge bg-danger"><?php echo $report['quantity']; ?></span></td>
                                    <td>
                                        <?php 
                                        $reasons = [
                                            'expired' => __('expired'),
                                            'damaged' => __('damaged'),
                                            'contaminated' => __('contaminated'),
                                            'other' => __('other')
                                        ];
                                        echo $reasons[$report['disposal_reason']] ?? $report['disposal_reason'];
                                        ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($report['reporter_name'] ?? __('not_specified')); ?></td>
                                    <td>
                                        <form method="POST" style="display: inline;" 
                                              onsubmit="return confirm('<?php echo __('confirm_delete_record'); ?>')">
                                            <input type="hidden" name="delete_record" value="1">
                                            <input type="hidden" name="table" value="narcotic_disposal_reports">
                                            <input type="hidden" name="id" value="<?php echo $report['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-danger">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php else: ?>
                    <div class="text-center py-4">
                        <i class="fas fa-pills fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted"><?php echo __('no_narcotic_disposal'); ?></h5>
                        <p class="text-muted"><?php echo __('no_narcotic_disposal_message'); ?></p>
                        <div class="d-flex gap-2 justify-content-center">
                            <button class="btn btn-primary" onclick="showSection('create')">
                                <i class="fas fa-plus me-1"></i> <?php echo __('add_disposal_report'); ?>
                            </button>
                            <a href="operations_team_report.php" class="btn btn-info">
                                <i class="fas fa-chart-line me-1"></i> <?php echo __('view_report'); ?>
                            </a>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- محاضر إعدام الأدوية منتهية الصلاحية -->
        <div class="table-section">
            <div class="card">
                <div class="card-header text-white">
                    <h5 class="mb-0">
                        <i class="fas fa-calendar-times me-2"></i>
                        <?php echo __('expired_disposal_reports'); ?>
                    </h5>
                </div>
                <div class="card-body">
                    <?php if (count($expired_reports) > 0): ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead class="table-dark">
                                <tr>
                                    <th><?php echo __('date'); ?></th>
                                    <th><?php echo __('drug_name'); ?></th>
                                    <th><?php echo __('quantity'); ?></th>
                                    <th><?php echo __('expiry_date'); ?></th>
                                    <th><?php echo __('batch_number'); ?></th>
                                    <th><?php echo __('reporter'); ?></th>
                                    <th><?php echo __('actions'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($expired_reports as $report): ?>
                                <tr>
                                    <td><?php echo date('d/m/Y', strtotime($report['report_date'])); ?></td>
                                    <td><?php echo htmlspecialchars($report['drug_name']); ?></td>
                                    <td><span class="badge bg-warning"><?php echo $report['quantity']; ?></span></td>
                                    <td>
                                        <?php echo $report['expiry_date'] ? date('d/m/Y', strtotime($report['expiry_date'])) : __('not_specified'); ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($report['batch_number'] ?? __('not_specified')); ?></td>
                                    <td><?php echo htmlspecialchars($report['reporter_name'] ?? __('not_specified')); ?></td>
                                    <td>
                                        <form method="POST" style="display: inline;" 
                                              onsubmit="return confirm('<?php echo __('confirm_delete_record'); ?>')">
                                            <input type="hidden" name="delete_record" value="1">
                                            <input type="hidden" name="table" value="expired_drugs_disposal">
                                            <input type="hidden" name="id" value="<?php echo $report['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-danger">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php else: ?>
                    <div class="text-center py-4">
                        <i class="fas fa-calendar-times fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted"><?php echo __('no_expired_disposal'); ?></h5>
                        <p class="text-muted"><?php echo __('no_expired_disposal_message'); ?></p>
                        <div class="d-flex gap-2 justify-content-center">
                            <button class="btn btn-primary" onclick="showSection('create')">
                                <i class="fas fa-plus me-1"></i> <?php echo __('add_disposal_report'); ?>
                            </button>
                            <a href="operations_team_report.php" class="btn btn-info">
                                <i class="fas fa-chart-line me-1"></i> <?php echo __('view_report'); ?>
                            </a>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function showSection(section) {
    // Hide all sections
    document.querySelectorAll('.content-section').forEach(function(el) {
        el.classList.remove('active');
    });
    
    // Remove active class from all buttons
    document.querySelectorAll('.toggle-btn').forEach(function(btn) {
        btn.classList.remove('active');
    });
    
    // Show selected section
    document.getElementById(section + '-section').classList.add('active');
    
    // Add active class to clicked button
    event.target.classList.add('active');
}

document.addEventListener('DOMContentLoaded', function() {
    // إضافة تأثيرات بصرية للنماذج
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            const submitBtn = form.querySelector('.btn-submit');
            if (submitBtn) {
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i><?php echo __('saving'); ?>...';
                submitBtn.disabled = true;
            }
        });
    });

    // تحديث التاريخ تلقائياً عند تغيير التبويب
    const tabButtons = document.querySelectorAll('[data-bs-toggle="tab"]');
    tabButtons.forEach(button => {
        button.addEventListener('shown.bs.tab', function() {
            const activePane = document.querySelector(button.getAttribute('data-bs-target'));
            const dateInput = activePane.querySelector('input[type="date"]');
            if (dateInput && !dateInput.value) {
                dateInput.value = new Date().toISOString().split('T')[0];
            }
        });
    });
    
    // التحقق من صحة النماذج
    forms.forEach(function(form) {
        form.addEventListener('submit', function(event) {
            const requiredFields = form.querySelectorAll('[required]');
            let isValid = true;
            
            requiredFields.forEach(function(field) {
                if (!field.value.trim()) {
                    isValid = false;
                    field.classList.add('is-invalid');
                } else {
                    field.classList.remove('is-invalid');
                }
            });
            
            if (!isValid) {
                event.preventDefault();
                alert('<?php echo __('fill_required_fields'); ?>');
            }
        });
    });
});
</script>

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