<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);

require_once __DIR__."/includes/db.php";
require_once __DIR__."/includes/security.php";
require_once __DIR__."/includes/auth.php";
require_once __DIR__."/includes/functions.php";

ensure_manager();

$page_title = "إدارة المستخدمين";
require_once "includes/header.php";

$restaurant_id = $_SESSION['restaurant_id'];

/* ============================================================
   إصلاح بيانات قديمة: أي مستخدم بدون restaurant_id نربطه بالمطعم الحالي
   (يحدث فقط مع المستخدم الأساسي القديم)
============================================================ */
db()->prepare("
    UPDATE managers 
    SET restaurant_id=? 
    WHERE restaurant_id IS NULL OR restaurant_id=0
")->execute([$restaurant_id]);

/* ============================================================
   جلب جميع المستخدمين المرتبطين بالمطعم
============================================================ */
$managers = fetch_all("
    SELECT * FROM managers
    WHERE restaurant_id = ?
    ORDER BY id ASC
", [$restaurant_id]);


/* ============================================================
   إضافة مستخدم
============================================================ */
if(isset($_POST['add_manager'])){

    $name  = clean($_POST['name']);
    $email = clean($_POST['email']);
    $role  = clean($_POST['role']);
    $pass  = password_hash($_POST['password'], PASSWORD_BCRYPT);

    // منع تكرار الإيميل داخل نفس المطعم
    $chk = fetch_one("
        SELECT id FROM managers 
        WHERE email = ? AND restaurant_id = ?
    ", [$email, $restaurant_id]);

    if($chk){
        header("Location: users.php?exists=1");
        exit;
    }

    db()->prepare("
        INSERT INTO managers (restaurant_id, name, email, password, role)
        VALUES (?, ?, ?, ?, ?)
    ")->execute([$restaurant_id, $name, $email, $pass, $role]);

    header("Location: users.php?added=1");
    exit;
}

/* ============================================================
   تعديل مستخدم
============================================================ */
if(isset($_POST['edit_manager'])){

    $id    = intval($_POST['id']);
    $name  = clean($_POST['name']);
    $email = clean($_POST['email']);
    $role  = clean($_POST['role']);

    db()->prepare("
        UPDATE managers
        SET name=?, email=?, role=?
        WHERE id=? AND restaurant_id=?
    ")->execute([$name, $email, $role, $id, $restaurant_id]);

    // تغيير كلمة السر إذا وُجدت
    if(trim($_POST['password']) !== ''){
        $pass = password_hash($_POST['password'], PASSWORD_BCRYPT);
        db()->prepare("UPDATE managers SET password=? WHERE id=?")
          ->execute([$pass, $id]);
    }

    header("Location: users.php?updated=1");
    exit;
}

/* ============================================================
   حذف مستخدم
============================================================ */
if(isset($_GET['delete'])){
    $id = intval($_GET['delete']);

    // منع حذف أول مستخدم مرتبط بهذا المطعم
    $owner = fetch_one("SELECT id FROM managers WHERE restaurant_id=? ORDER BY id ASC LIMIT 1", [$restaurant_id]);
    if($owner && $owner['id'] == $id){
        header("Location: users.php?blocked=1");
        exit;
    }

    db()->prepare("
        DELETE FROM managers 
        WHERE id = ? AND restaurant_id = ?
    ")->execute([$id, $restaurant_id]);

    header("Location: users.php?deleted=1");
    exit;
}
?>


<style>
.settings-card{
    background:#1c1c1c;padding:20px;border-radius:12px;
    border:1px solid #333;margin-bottom:25px;
}
.settings-card h3{
    color:#ffbe6a;margin-top:0;font-weight:600;
    border-bottom:1px solid #444;padding-bottom:6px;
}
input, select{
    width:100%;padding:10px;border-radius:7px;
    background:#111;border:1px solid #444;color:#fff;margin-top:6px;
}
.btn-save{
    background:#ff7a00;color:#fff;padding:12px 22px;
    border:none;border-radius:10px;font-size:16px;cursor:pointer;
}
.msg-success{
    background:#13a813;padding:12px;border-radius:10px;
    color:#fff;margin-bottom:12px;text-align:center;
}
.msg-error{
    background:#e30000;padding:12px;border-radius:10px;
    color:#fff;margin-bottom:12px;text-align:center;
}
.table{
    width:100%;margin-top:20px;border-collapse:collapse;color:#fff;
}
.table th,.table td{
    padding:10px;border-bottom:1px solid #333;
}
.btn-sm{
    background:#555;color:#fff;padding:5px 10px;border-radius:6px;
}
.btn-delete{
    background:#b00000;color:#fff;padding:6px 12px;border-radius:6px;
    text-decoration:none;margin-left:6px;
}
.overlay{
    position:fixed;top:0;left:0;width:100%;height:100%;
    background:#000a;display:none;justify-content:center;align-items:center;z-index:999;
}
.popup{
    width:350px;background:#1c1c1c;padding:20px;border-radius:12px;
    border:1px solid #333;
}
</style>

<div class="settings-card">

    <h3>إدارة المستخدمين</h3>

    <?php if(isset($_GET['added']))  echo '<div class="msg-success">تم إضافة المستخدم</div>'; ?>
    <?php if(isset($_GET['updated'])) echo '<div class="msg-success">تم تحديث المستخدم</div>'; ?>
    <?php if(isset($_GET['deleted'])) echo '<div class="msg-success">تم حذف المستخدم</div>'; ?>
    <?php if(isset($_GET['blocked'])) echo '<div class="msg-error">لا يمكن حذف المدير الأساسي</div>'; ?>
    <?php if(isset($_GET['exists']))  echo '<div class="msg-error">هذا البريد موجود مسبقاً</div>'; ?>

    <!-- نموذج إضافة مستخدم -->
    <form method="post" class="box">
        <h3>إضافة مستخدم</h3>

        <label>الاسم</label>
        <input type="text" name="name" required>

        <label>البريد الإلكتروني</label>
        <input type="email" name="email" required>

        <label>كلمة المرور</label>
        <input type="password" name="password" required>

        <label>الصلاحية</label>
        <select name="role">
            <option value="manager">مدير</option>
            <option value="editor">محرر</option>
        </select>

        <button class="btn-save" name="add_manager">إضافة</button>
    </form>

    <!-- جدول المستخدمين -->
    <h3>جميع المستخدمين</h3>

    <table class="table">
        <tr>
            <th>الاسم</th>
            <th>البريد</th>
            <th>الصلاحية</th>
            <th>خيارات</th>
        </tr>

        <?php foreach($managers as $m): ?>
        <tr>
            <td><?= htmlspecialchars($m['name']) ?></td>
            <td><?= htmlspecialchars($m['email']) ?></td>
            <td><?= $m['role']=="manager" ? "مدير" : "محرر" ?></td>
            <td>
                <button class="btn-sm" onclick="editUser(<?= $m['id'] ?>,'<?= $m['name'] ?>','<?= $m['email'] ?>','<?= $m['role'] ?>')">تعديل</button>

                <?php if($m['id'] != 1): ?>
                    <a href="?delete=<?= $m['id'] ?>" class="btn-delete" onclick="return confirm('حذف المستخدم؟')">حذف</a>
                <?php endif; ?>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>

<!-- نافذة التعديل -->
<div id="editBox" class="overlay">
<div class="popup">
    <h3>تعديل مستخدم</h3>
    <form method="post">

        <input type="hidden" name="id" id="edit_id">

        <label>الاسم</label>
        <input type="text" name="name" id="edit_name" required>

        <label>البريد الإلكتروني</label>
        <input type="email" name="email" id="edit_email" required>

        <label>الصلاحية</label>
        <select name="role" id="edit_role">
            <option value="manager">مدير</option>
            <option value="editor">محرر</option>
        </select>

        <label>كلمة مرور جديدة (اختياري)</label>
        <input type="password" name="password">

        <button class="btn-save" name="edit_manager">تعديل</button>
        <button class="btn-delete" type="button" onclick="document.getElementById('editBox').style.display='none'">إغلاق</button>

    </form>
</div>
</div>

<script>
function editUser(id, name, email, role){
    document.getElementById('edit_id').value = id;
    document.getElementById('edit_name').value = name;
    document.getElementById('edit_email').value = email;
    document.getElementById('edit_role').value = role;
    document.getElementById('editBox').style.display = 'flex';
}
</script>

<?php require_once "includes/footer.php"; ?>
