<?php
require_once __DIR__ . '/../auth.php';
requireAdmin();
require_once __DIR__ . '/../config.php';
if (function_exists('require_csrf')) require_csrf();

header('Content-Type: application/json; charset=utf-8');

$action = $_GET['action'] ?? $_POST['action'] ?? '';

if ($action === 'list') {
    $r = $conn->query("SELECT id, username, is_admin, can_edit, can_delete, can_export FROM users ORDER BY id");
    $list = [];
    while ($row = $r->fetch_assoc()) $list[] = $row;
    echo json_encode(['success' => true, 'data' => $list]);
    exit;
}

if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $is_admin = isset($_POST['is_admin']) ? 1 : 0;
    $can_edit = isset($_POST['can_edit']) ? 1 : 0;
    $can_delete = isset($_POST['can_delete']) ? 1 : 0;
    $can_export = isset($_POST['can_export']) ? 1 : 0;
    if (empty($username) || strlen($password) < 6) {
        echo json_encode(['success' => false, 'message' => 'اسم المستخدم مطلوب وكلمة المرور 6 أحرف على الأقل']);
        exit;
    }
    $hash = password_hash($password, PASSWORD_DEFAULT);
    $stmt = $conn->prepare("INSERT INTO users (username, password_hash, is_admin, can_edit, can_delete, can_export) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssiiii", $username, $hash, $is_admin, $can_edit, $can_delete, $can_export);
    if ($stmt->execute()) {
        if (function_exists('logActivity')) logActivity('add', 'users', $conn->insert_id, $username);
        echo json_encode(['success' => true, 'id' => $conn->insert_id]);
    } else {
        echo json_encode(['success' => false, 'message' => 'اسم المستخدم موجود مسبقاً']);
    }
    exit;
}

if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id === 1) {
        echo json_encode(['success' => false, 'message' => 'لا يمكن تعديل المدير']);
        exit;
    }
    $is_admin = isset($_POST['is_admin']) ? 1 : 0;
    $can_edit = isset($_POST['can_edit']) ? 1 : 0;
    $can_delete = isset($_POST['can_delete']) ? 1 : 0;
    $can_export = isset($_POST['can_export']) ? 1 : 0;
    $password = trim($_POST['password'] ?? '');
    if ($password) {
        if (strlen($password) < 6) {
            echo json_encode(['success' => false, 'message' => 'كلمة المرور 6 أحرف على الأقل']);
            exit;
        }
        $hash = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $conn->prepare("UPDATE users SET is_admin=?, can_edit=?, can_delete=?, can_export=?, password_hash=? WHERE id=?");
        $stmt->bind_param("iiiisi", $is_admin, $can_edit, $can_delete, $can_export, $hash, $id);
    } else {
        $stmt = $conn->prepare("UPDATE users SET is_admin=?, can_edit=?, can_delete=?, can_export=? WHERE id=?");
        $stmt->bind_param("iiiii", $is_admin, $can_edit, $can_delete, $can_export, $id);
    }
    $ok = $stmt->execute();
    if ($ok && function_exists('logActivity')) logActivity('update', 'users', $id, '');
    echo json_encode(['success' => $ok]);
    exit;
}

if ($action === 'delete') {
    $id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
    if ($id === 1) {
        echo json_encode(['success' => false, 'message' => 'لا يمكن حذف المدير']);
        exit;
    }
    if ($id === $_SESSION['user_id']) {
        echo json_encode(['success' => false, 'message' => 'لا يمكن حذف حسابك']);
        exit;
    }
    $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
    $stmt->bind_param("i", $id);
    $ok = $stmt->execute();
    if ($ok && function_exists('logActivity')) logActivity('delete', 'users', $id, '');
    echo json_encode(['success' => $ok]);
    exit;
}

echo json_encode(['success' => false]);
