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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    redirect('login.php');
}

// Set current page for permissions
$currentPage = 'units';

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

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

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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action == 'add') {
        $unit_name = trim($_POST['unit_name']);
        $unit_code = trim($_POST['unit_code']);
        $description = trim($_POST['description']);
        
        try {
            // Check if unit_name or unit_code exists
            $stmt = $conn->prepare("SELECT id FROM units WHERE unit_name = ? OR unit_code = ?");
            $stmt->execute([$unit_name, $unit_code]);
            
            if ($stmt->rowCount() > 0) {
                $error = 'اسم القسم أو الكود موجود بالفعل';
            } else {
                $sql = "INSERT INTO units (unit_name, unit_code, description, is_active) VALUES (?, ?, ?, 1)";
                $stmt = $conn->prepare($sql);
                $stmt->execute([$unit_name, $unit_code, $description]);
                
                $new_id = $conn->lastInsertId();
                
                // Log activity - only if user exists in users table
                $user_check = $conn->prepare("SELECT id FROM users WHERE id = ? LIMIT 1");
                $user_check->execute([$_SESSION['user_id']]);
                if ($user_check->rowCount() > 0) {
                    $log_stmt = $conn->prepare("INSERT INTO activity_log (user_id, action, table_name, record_id, ip_address, user_agent) VALUES (?, ?, ?, ?, ?, ?)");
                    $log_stmt->execute([$_SESSION['user_id'], 'إضافة قسم جديد', 'units', $new_id, $_SERVER['REMOTE_ADDR'] ?? null, $_SERVER['HTTP_USER_AGENT'] ?? null]);
                }
                
                $message = 'تم إضافة القسم بنجاح';
            }
        } catch (Exception $e) {
            $error = 'خطأ في إضافة القسم: ' . $e->getMessage();
        }
    }
    
    if ($action == 'edit') {
        $id = intval($_POST['unit_id']);
        $unit_name = trim($_POST['unit_name']);
        $unit_code = trim($_POST['unit_code']);
        $description = trim($_POST['description']);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        try {
            // Check if unit_name or unit_code exists for another unit
            $stmt = $conn->prepare("SELECT id FROM units WHERE (unit_name = ? OR unit_code = ?) AND id != ?");
            $stmt->execute([$unit_name, $unit_code, $id]);
            
            if ($stmt->rowCount() > 0) {
                $error = 'اسم القسم أو الكود موجود بالفعل';
            } else {
                $sql = "UPDATE units SET unit_name=?, unit_code=?, description=?, is_active=? WHERE id=?";
                $stmt = $conn->prepare($sql);
                $stmt->execute([$unit_name, $unit_code, $description, $is_active, $id]);
                
                // Log activity - only if user exists in users table
                $user_check = $conn->prepare("SELECT id FROM users WHERE id = ? LIMIT 1");
                $user_check->execute([$_SESSION['user_id']]);
                if ($user_check->rowCount() > 0) {
                    $log_stmt = $conn->prepare("INSERT INTO activity_log (user_id, action, table_name, record_id, ip_address, user_agent) VALUES (?, ?, ?, ?, ?, ?)");
                    $log_stmt->execute([$_SESSION['user_id'], 'تحديث بيانات القسم', 'units', $id, $_SERVER['REMOTE_ADDR'] ?? null, $_SERVER['HTTP_USER_AGENT'] ?? null]);
                }
                
                $message = 'تم تحديث القسم بنجاح';
            }
        } catch (Exception $e) {
            $error = 'خطأ في التحديث: ' . $e->getMessage();
        }
    }
    
    if ($action == 'delete') {
        $id = intval($_POST['unit_id']);
        
        try {
            // Check for dependencies
            $check_stmt = $conn->prepare("SELECT id FROM antibiotic_reports WHERE unit_id = ? LIMIT 1");
            $check_stmt->execute([$id]);
            
            if ($check_stmt->rowCount() > 0) {
                $error = 'لا يمكن حذف القسم لوجود تقارير مرتبطة به. يمكنك تعطيله بدلاً من ذلك.';
            } else {
                $stmt = $conn->prepare("DELETE FROM units WHERE id = ?");
                $stmt->execute([$id]);
                
                // Log activity - only if user exists in users table
                $user_check = $conn->prepare("SELECT id FROM users WHERE id = ? LIMIT 1");
                $user_check->execute([$_SESSION['user_id']]);
                if ($user_check->rowCount() > 0) {
                    $log_stmt = $conn->prepare("INSERT INTO activity_log (user_id, action, table_name, record_id, ip_address, user_agent) VALUES (?, ?, ?, ?, ?, ?)");
                    $log_stmt->execute([$_SESSION['user_id'], 'حذف قسم', 'units', $id, $_SERVER['REMOTE_ADDR'] ?? null, $_SERVER['HTTP_USER_AGENT'] ?? null]);
                }
                
                $message = 'تم حذف القسم بنجاح';
            }
        } catch (Exception $e) {
            $error = 'خطأ في الحذف: ' . $e->getMessage();
        }
    }
    
    if ($action == 'toggle_status') {
        $id = intval($_POST['unit_id']);
        
        try {
            $stmt = $conn->prepare("UPDATE units SET is_active = NOT is_active WHERE id = ?");
            $stmt->execute([$id]);
            
            // Log activity - only if user exists in users table
            $user_check = $conn->prepare("SELECT id FROM users WHERE id = ? LIMIT 1");
            $user_check->execute([$_SESSION['user_id']]);
            if ($user_check->rowCount() > 0) {
                $log_stmt = $conn->prepare("INSERT INTO activity_log (user_id, action, table_name, record_id, ip_address, user_agent) VALUES (?, ?, ?, ?, ?, ?)");
                $log_stmt->execute([$_SESSION['user_id'], 'تغيير حالة القسم', 'units', $id, $_SERVER['REMOTE_ADDR'] ?? null, $_SERVER['HTTP_USER_AGENT'] ?? null]);
            }
            
            $message = 'تم تغيير حالة القسم بنجاح';
        } catch (Exception $e) {
            $error = 'خطأ في تغيير الحالة: ' . $e->getMessage();
        }
    }
}

// Get all units
try {
    $stmt = $conn->query("SELECT * FROM units ORDER BY unit_name ASC");
    $units = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $units = [];
    $error = 'خطأ في جلب البيانات';
}

// Set page title
$page_title = 'إدارة الأقسام - ' . __('system_name');

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

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0">🏥 إدارة الأقسام</h1>
        <button onclick="openAddModal()" class="btn btn-success">➕ إضافة قسم جديد</button>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            ✅ <?= htmlspecialchars($message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            ❌ <?= htmlspecialchars($error) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="card shadow-sm border-0 rounded-3">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th class="px-4 py-3">اسم القسم</th>
                            <th class="py-3">الكود</th>
                            <th class="py-3">الوصف</th>
                            <th class="py-3 text-center">الحالة</th>
                            <th class="py-3 text-center">الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($units as $unit): ?>
                        <tr>
                            <td class="px-4">
                                <div class="fw-bold"><?= htmlspecialchars($unit['unit_name']) ?></div>
                            </td>
                            <td>
                                <span class="badge bg-secondary"><?= htmlspecialchars($unit['unit_code']) ?></span>
                            </td>
                            <td>
                                <div class="text-muted small"><?= htmlspecialchars($unit['description'] ?: 'لا يوجد وصف') ?></div>
                            </td>
                            <td class="text-center">
                                <form method="POST" class="d-inline">
                                    <input type="hidden" name="action" value="toggle_status">
                                    <input type="hidden" name="unit_id" value="<?= $unit['id'] ?>">
                                    <button type="submit" class="btn btn-sm <?= $unit['is_active'] ? 'btn-success' : 'btn-danger' ?> rounded-pill px-3">
                                        <?= $unit['is_active'] ? 'نشط' : 'معطل' ?>
                                    </button>
                                </form>
                            </td>
                            <td class="text-center">
                                <div class="btn-group">
                                    <button onclick='openEditModal(<?= json_encode($unit) ?>)' class="btn btn-sm btn-outline-primary" title="تعديل">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button onclick="confirmDelete(<?= $unit['id'] ?>, '<?= htmlspecialchars($unit['unit_name']) ?>')" class="btn btn-sm btn-outline-danger" title="حذف">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($units)): ?>
                        <tr>
                            <td colspan="5" class="text-center py-5 text-muted">لا توجد أقسام مضافة حالياً</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add/Edit Modal -->
<div class="modal fade" id="unitModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="modalTitle">إضافة قسم جديد</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" id="formAction" value="add">
                    <input type="hidden" name="unit_id" id="unitId">
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold">اسم القسم</label>
                        <input type="text" name="unit_name" id="unitName" class="form-control" required placeholder="مثال: ICU, 6th Floor">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold">كود القسم</label>
                        <input type="text" name="unit_code" id="unitCode" class="form-control" required placeholder="مثال: ICU, 6TH">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold">الوصف</label>
                        <textarea name="description" id="unitDescription" class="form-control" rows="3" placeholder="وصف اختياري للقسم"></textarea>
                    </div>
                    
                    <div class="mb-3" id="statusField" style="display: none;">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="is_active" id="unitActive" checked>
                            <label class="form-check-label">حالة القسم (نشط)</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn btn-primary" id="saveBtn">حفظ البيانات</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Form (Hidden) -->
<form id="deleteForm" method="POST" style="display: none;">
    <input type="hidden" name="action" value="delete">
    <input type="hidden" name="unit_id" id="deleteUnitId">
</form>

<script>
function openAddModal() {
    document.getElementById('modalTitle').textContent = 'إضافة قسم جديد';
    document.getElementById('formAction').value = 'add';
    document.getElementById('unitId').value = '';
    document.getElementById('unitName').value = '';
    document.getElementById('unitCode').value = '';
    document.getElementById('unitDescription').value = '';
    document.getElementById('statusField').style.display = 'none';
    
    new bootstrap.Modal(document.getElementById('unitModal')).show();
}

function openEditModal(unit) {
    document.getElementById('modalTitle').textContent = 'تعديل قسم: ' + unit.unit_name;
    document.getElementById('formAction').value = 'edit';
    document.getElementById('unitId').value = unit.id;
    document.getElementById('unitName').value = unit.unit_name;
    document.getElementById('unitCode').value = unit.unit_code;
    document.getElementById('unitDescription').value = unit.description || '';
    document.getElementById('unitActive').checked = unit.is_active == 1;
    document.getElementById('statusField').style.display = 'block';
    
    new bootstrap.Modal(document.getElementById('unitModal')).show();
}

function confirmDelete(id, name) {
    if (confirm('هل أنت متأكد من حذف القسم "' + name + '"؟\nسيتم حذف القسم فقط إذا لم يكن مرتبطاً بأي تقارير.')) {
        document.getElementById('deleteUnitId').value = id;
        document.getElementById('deleteForm').submit();
    }
}
</script>

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