<?php 
include 'config.php'; 
include 'header.php'; 

// 1. منطق الحفظ والتعديل (PHP)
if(isset($_POST['save_user'])){
    $u_id = $_POST['user_id'] ?? null;
    $name = $_POST['full_name'];
    $user = $_POST['username'];
    $branch = $_POST['branch_id'];
    $selected_pages = $_POST['permissions'] ?? [];

    try {
        if(!empty($u_id)){
            // تحديث بيانات المستخدم
            if(!empty($_POST['password'])){
                $pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("UPDATE users SET username=?, password=?, full_name=?, branch_id=? WHERE id=?");
                $stmt->execute([$user, $pass, $name, $branch, $u_id]);
            } else {
                $stmt = $pdo->prepare("UPDATE users SET username=?, full_name=?, branch_id=? WHERE id=?");
                $stmt->execute([$user, $name, $branch, $u_id]);
            }
            // تحديث الصلاحيات: مسح القديم وإضافة الجديد
            $pdo->prepare("DELETE FROM user_permissions WHERE user_id=?")->execute([$u_id]);
            $target_id = $u_id;
        } else {
            // إضافة مستخدم جديد
            $pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (username, password, full_name, branch_id) VALUES (?,?,?,?)");
            $stmt->execute([$user, $pass, $name, $branch]);
            $target_id = $pdo->lastInsertId();
        }

        // إضافة الصلاحيات المحددة
        foreach($selected_pages as $p_id){
            $stmt_perm = $pdo->prepare("INSERT INTO user_permissions (user_id, page_id) VALUES (?,?)");
            $stmt_perm->execute([$target_id, $p_id]);
        }
        echo "<script>window.location='manage_users.php';</script>";
    } catch (Exception $e) {
        echo "<script>alert('خطأ: " . $e->getMessage() . "');</script>";
    }
}

// جلب البيانات الأساسية
$all_pages = $pdo->query("SELECT * FROM pages")->fetchAll();
$all_branches = $pdo->query("SELECT * FROM branches")->fetchAll();
$users = $pdo->query("SELECT users.*, branches.branch_name FROM users LEFT JOIN branches ON users.branch_id = branches.id")->fetchAll();
?>

<style>
    /* Odoo Style Variables */
    :root {
        --odoo-purple: #714B67;
        --odoo-teal: #008784;
        --odoo-bg: #F8F9FA;
        --odoo-border: #dee2e6;
    }

    body { background-color: var(--odoo-bg); font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }

    /* Modal Layout & Elements */
    .modal-content { border-radius: 4px; border: none; box-shadow: 0 10px 40px rgba(0,0,0,0.2); }
    .modal-header { background: white; border-bottom: 1px solid var(--odoo-border); padding: 12px 25px; }
    .modal-title { color: #4c4c4c; font-size: 1.2rem; font-weight: 600; }
    
    /* Odoo Inputs - Thin bottom border */
    .form-control, .form-select {
        border-radius: 0;
        border: none;
        border-bottom: 1px solid #ccc;
        padding: 8px 2px;
        background-color: transparent !important;
        box-shadow: none !important;
        transition: border-color 0.3s;
    }
    .form-control:focus, .form-select:focus { border-bottom: 2px solid var(--odoo-teal); }
    
    label { color: #666; font-size: 0.9rem; font-weight: 600; margin-bottom: 4px; display: block; }

    /* Custom Buttons */
    .btn-odoo-primary { background-color: var(--odoo-purple); color: white; border-radius: 3px; border: none; padding: 7px 20px; font-weight: 500; }
    .btn-odoo-primary:hover { background-color: #5a3c52; color: white; }
    .btn-odoo-secondary { background-color: white; color: #4c4c4c; border: 1px solid #ccc; border-radius: 3px; padding: 7px 20px; }
    
    .o_form_sheet { padding: 30px; background: white; }
    .o_horizontal_separator {
        color: var(--odoo-teal);
        font-weight: bold;
        font-size: 0.85rem;
        margin: 25px 0 15px 0;
        border-bottom: 1px solid #eee;
        padding-bottom: 5px;
    }

    /* Table Styling */
    .table-container { background: white; border-radius: 2px; border: 1px solid var(--odoo-border); }
    .table thead th { font-weight: 500; color: #666; font-size: 0.85rem; border-top: none; }
</style>

<div class="container-fluid mt-4" dir="rtl">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h4 class="text-muted fw-bold">إدارة المستخدمين</h4>
        <button type="button" class="btn btn-odoo-primary shadow-sm" onclick="openCreateModal()">
            <i class="fa fa-user-plus me-1"></i> إنشاء مستخدم
        </button>
    </div>

    <div class="table-container shadow-sm">
        <table class="table table-hover mb-0 text-end align-middle">
            <thead class="bg-light">
                <tr>
                    <th class="py-3 ps-4">الاسم</th>
                    <th>اسم المستخدم</th>
                    <th>الفرع</th>
                    <th class="text-center">إجراء</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($users as $u): 
                    // جلب الصلاحيات كمصفوفة أرقام لليوزر الحالي
                    $u_perms = $pdo->prepare("SELECT page_id FROM user_permissions WHERE user_id = ?");
                    $u_perms->execute([$u['id']]);
                    $u['perms'] = $u_perms->fetchAll(PDO::FETCH_COLUMN);
                ?>
                <tr onclick='editUser(<?= json_encode($u) ?>)' style="cursor: pointer;">
                    <td class="ps-4 py-2 fw-bold text-dark"><?= $u['full_name'] ?></td>
                    <td class="py-2"><?= $u['username'] ?></td>
                    <td class="py-2"><span class="badge bg-light text-dark border"><?= $u['branch_name'] ?></span></td>
                    <td class="text-center py-2 text-muted"><i class="fa fa-pencil-alt small"></i></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="userModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form method="POST" id="userForm" class="modal-content text-end">
            <div class="modal-header">
                <h5 class="modal-title" id="m_title">تعديل مستخدم</h5>
                <div class="ms-auto d-flex gap-2">
                    <button type="submit" name="save_user" class="btn btn-odoo-primary btn-sm">حفظ</button>
                    <button type="button" class="btn btn-odoo-secondary btn-sm" data-bs-dismiss="modal">تجاهل</button>
                </div>
            </div>
            <div class="modal-body p-0">
                <div class="o_form_sheet">
                    <input type="hidden" name="user_id" id="f_user_id">
                    
                    <div class="row mb-4">
                        <div class="col-md-12">
                            <label>الاسم الكامل</label>
                            <input type="text" name="full_name" id="f_full_name" class="form-control fs-4 fw-bold" placeholder="مثلاً: محمد علي" required>
                        </div>
                    </div>

                    <div class="row g-4">
                        <div class="col-md-6">
                            <label>اسم المستخدم</label>
                            <input type="text" name="username" id="f_username" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label>الفرع المخصص</label>
                            <select name="branch_id" id="f_branch_id" class="form-select">
                                <?php foreach($all_branches as $b): ?>
                                    <option value="<?= $b['id'] ?>"><?= $b['branch_name'] ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-12">
                            <label>كلمة المرور</label>
                            <input type="password" name="password" id="f_password" class="form-control" placeholder="اتركها فارغة للمحافظة على القديمة">
                        </div>
                    </div>

                    <div class="o_horizontal_separator">صلاحيات الوصول والصفحات</div>
                    
                    <div class="row mt-3">
                        <?php foreach($all_pages as $pg): ?>
                        <div class="col-md-4 mb-3">
                            <div class="form-check d-flex align-items-center gap-2">
                                <input class="form-check-input perm-check" type="checkbox" name="permissions[]" value="<?= $pg['id'] ?>" id="p<?= $pg['id'] ?>">
                                <label class="form-check-label text-dark mb-0" for="p<?= $pg['id'] ?>">
                                    <i class="fa <?= $pg['icon'] ?> text-muted me-1 small"></i> <?= $pg['page_name'] ?>
                                </label>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
var uModal;
$(document).ready(function() {
    uModal = new bootstrap.Modal(document.getElementById('userModal'));
});

function openCreateModal() {
    $('#userForm')[0].reset();
    $('#f_user_id').val('');
    $('#m_title').text('إنشاء مستخدم');
    $('#f_password').attr('placeholder', 'كلمة مرور مطلوبة');
    $('.perm-check').prop('checked', false);
    uModal.show();
}

function editUser(data) {
    $('#userForm')[0].reset();
    $('#m_title').text('تعديل: ' + data.full_name);
    $('#f_user_id').val(data.id);
    $('#f_full_name').val(data.full_name);
    $('#f_username').val(data.username);
    $('#f_branch_id').val(data.branch_id);
    $('#f_password').attr('placeholder', 'اتركها فارغة للمحافظة على القديمة');
    
    // ربط الصلاحيات (الحل النهائي)
    const perms = data.perms.map(String); // تحويل الأرقام لنصوص للمطابقة مع قيمة الـ checkbox
    
    $('.perm-check').each(function() {
        const pageId = $(this).val();
        if(perms.includes(pageId)) {
            $(this).prop('checked', true);
        } else {
            $(this).prop('checked', false);
        }
    });

    uModal.show();
}
</script>

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