<?php
/**
 * cashiers.php - إدارة الكاشير (نسخة محسنة)
 */

require_once 'config.php';
checkAdminAuth(); // تأكد من أن هذه الدالة موجودة في config.php

// ============================================
// إضافة كاشير
// ============================================
if (isPost() && isset($_POST['add'])) {
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $branch = $_POST['branch'];

    // استخدام prepared statements لمنع SQL Injection
    $stmt = $conn->prepare("INSERT INTO cashiers (name, phone, password, branch, created_at) VALUES (?, ?, ?, ?, NOW())");
    $stmt->bind_param("ssss", $name, $phone, $password, $branch);

    if ($stmt->execute()) {
        $cache->clear();
        $_SESSION['success'] = 'تم إضافة الكاشير بنجاح';
    } else {
        $_SESSION['error'] = 'حدث خطأ أثناء الإضافة';
    }
    $stmt->close();

    header('Location: cashiers.php');
    exit();
}

// ============================================
// تعديل كاشير
// ============================================
if (isPost() && isset($_POST['edit'])) {
    $id = (int)$_POST['id'];
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $branch = $_POST['branch'];

    if (!empty($_POST['password'])) {
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $stmt = $conn->prepare("UPDATE cashiers SET name=?, phone=?, branch=?, password=? WHERE id=?");
        $stmt->bind_param("ssssi", $name, $phone, $branch, $password, $id);
    } else {
        $stmt = $conn->prepare("UPDATE cashiers SET name=?, phone=?, branch=? WHERE id=?");
        $stmt->bind_param("sssi", $name, $phone, $branch, $id);
    }

    if ($stmt->execute()) {
        $cache->clear();
        $_SESSION['success'] = 'تم تعديل الكاشير';
    } else {
        $_SESSION['error'] = 'حدث خطأ أثناء التعديل';
    }
    $stmt->close();

    header('Location: cashiers.php');
    exit();
}

// ============================================
// تفعيل وتعطيل
// ============================================
if (isPost() && isset($_POST['toggle'])) {
    $id = (int)$_POST['id'];

    // استخدم prepared statement هنا أيضاً
    $stmt = $conn->prepare("UPDATE cashiers SET status = IF(status='active', 'inactive', 'active') WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->close();

    $cache->clear();
    header('Location: cashiers.php');
    exit();
}

// ============================================
// حذف
// ============================================
if (isPost() && isset($_POST['delete'])) {
    $id = (int)$_POST['id'];

    $stmt = $conn->prepare("DELETE FROM cashiers WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->close();

    $cache->clear();
    $_SESSION['success'] = 'تم حذف الكاشير';
    header('Location: cashiers.php');
    exit();
}

// ============================================
// جلب كاشير للتعديل (API)
// ============================================
if (isset($_GET['get_cashier'])) {
    $id = (int)$_GET['get_cashier'];

    // استبعاد كلمة المرور من النتائج
    $stmt = $conn->prepare("SELECT id, name, phone, branch FROM cashiers WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $cashier = $result->fetch_assoc();
    $stmt->close();

    header('Content-Type: application/json');
    echo json_encode($cashier ?: []); // إرجاع مصفوفة فارغة إذا لم يتم العثور على الكاشير
    exit();
}

// ============================================
// جلب البيانات (مع أو بدون Cache)
// ============================================
$cashiers = $cache->get('cashiers_list');

if (!$cashiers) {
    // استخدام query عادي لأنه استعلام بسيط، ولكن يمكنك استخدام prepared statements إذا أردت تمرير متغيرات
    $result = $conn->query("SELECT id, name, phone, branch, status, created_at FROM cashiers ORDER BY id DESC LIMIT 200");
    $cashiers = [];
    while ($row = $result->fetch_assoc()) {
        $cashiers[] = $row;
    }
    $cache->set('cashiers_list', $cashiers, 300); // تخزين لمدة 5 دقائق
}

$page_title = 'الكاشير';
include 'includes/header.php';
include 'includes/sidebar.php';
?>

<div class="main-content">
    <div class="top-bar">
        <i class="bi bi-person-workspace text-primary fs-4 me-2"></i>
        <strong>إدارة الكاشير</strong>
        <span class="ms-auto text-muted small"><?php echo count($cashiers); ?> كاشير</span>
    </div>

    <div class="d-flex justify-content-end mb-3">
        <button class="btn btn-primary" onclick="openAddModal()">
            <i class="bi bi-plus-lg"></i> إضافة كاشير
        </button>
    </div>

    <div class="card">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>الاسم</th>
                        <th>الهاتف</th>
                        <th>الفرع</th>
                        <th>الحالة</th>
                        <th>التاريخ</th>
                        <th>الإجراءات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $i=1; foreach($cashiers as $c): ?>
                    <tr>
                        <td><?php echo $i++; ?></td>
                        <td><?php echo e($c['name']); ?></td>
                        <td><?php echo e($c['phone']); ?></td>
                        <td><?php echo e($c['branch']); ?></td>
                        <td>
                            <span class="badge bg-<?php echo $c['status']=='active'?'success':'secondary'; ?>">
                                <?php echo $c['status']=='active'?'نشط':'غير نشط'; ?>
                            </span>
                        </td>
                        <td><?php echo date('Y-m-d', strtotime($c['created_at'])); ?></td>
                        <td>
                            <!-- زر التفعيل/التعطيل -->
                            <form method="POST" class="d-inline">
                                <input type="hidden" name="id" value="<?php echo $c['id']; ?>">
                                <button name="toggle" class="btn btn-sm btn-warning" title="تغيير الحالة">
                                    <i class="bi bi-power"></i>
                                </button>
                            </form>

                            <!-- زر التعديل -->
                            <button class="btn btn-sm btn-primary" onclick="editCashier(<?php echo $c['id']; ?>)" title="تعديل">
                                <i class="bi bi-pencil"></i>
                            </button>

                            <!-- زر الحذف -->
                            <form method="POST" class="d-inline" onsubmit="return confirm('تأكيد الحذف؟')">
                                <input type="hidden" name="id" value="<?php echo $c['id']; ?>">
                                <button name="delete" class="btn btn-sm btn-danger" title="حذف">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal for Add Cashier -->
<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title">إضافة كاشير جديد</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">الاسم</label>
                        <input type="text" name="name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">رقم الهاتف</label>
                        <input type="text" name="phone" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">كلمة المرور</label>
                        <input type="password" name="password" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">الفرع</label>
                        <input type="text" name="branch" class="form-control">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" name="add" class="btn btn-primary">حفظ</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal for Edit Cashier -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="id" id="edit_id">
                <div class="modal-header">
                    <h5 class="modal-title">تعديل بيانات الكاشير</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">الاسم</label>
                        <input type="text" name="name" id="edit_name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">رقم الهاتف</label>
                        <input type="text" name="phone" id="edit_phone" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">الفرع</label>
                        <input type="text" name="branch" id="edit_branch" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">كلمة المرور (اتركها فارغة إذا لم ترد التغيير)</label>
                        <input type="password" name="password" class="form-control">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" name="edit" class="btn btn-primary">تحديث</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function openAddModal() {
    new bootstrap.Modal(document.getElementById('addModal')).show();
}

function editCashier(id) {
    fetch('cashiers.php?get_cashier=' + id)
        .then(r => r.json())
        .then(data => {
            if (data && data.id) {
                document.getElementById('edit_id').value = data.id;
                document.getElementById('edit_name').value = data.name;
                document.getElementById('edit_phone').value = data.phone;
                document.getElementById('edit_branch').value = data.branch;
                new bootstrap.Modal(document.getElementById('editModal')).show();
            } else {
                alert('لم يتم العثور على الكاشير');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('حدث خطأ في جلب البيانات');
        });
}
</script>

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