<?php
// GET /api/users  — list with pagination & search
// POST /api/users — create user

$db = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $page   = max(1, (int)($_GET['page']  ?? 1));
    $limit  = max(1, (int)($_GET['limit'] ?? 10));
    $search = trim($_GET['search'] ?? '');
    $offset = ($page - 1) * $limit;

    if ($search) {
        $like = "%$search%";
        $stmt = $db->prepare("
            SELECT id, name, employee_id, mobile, role, status
            FROM users
            WHERE name LIKE ? OR employee_id LIKE ? OR mobile LIKE ?
            ORDER BY id DESC LIMIT ? OFFSET ?
        ");
        $stmt->bind_param("sssii", $like, $like, $like, $limit, $offset);
        $stmt->execute();
        $users = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();

        $stmt2 = $db->prepare("
            SELECT COUNT(*) AS cnt FROM users
            WHERE name LIKE ? OR employee_id LIKE ? OR mobile LIKE ?
        ");
        $stmt2->bind_param("sss", $like, $like, $like);
        $stmt2->execute();
        $total = $stmt2->get_result()->fetch_assoc()['cnt'];
        $stmt2->close();
    } else {
        $stmt = $db->prepare("
            SELECT id, name, employee_id, mobile, role, status
            FROM users ORDER BY id DESC LIMIT ? OFFSET ?
        ");
        $stmt->bind_param("ii", $limit, $offset);
        $stmt->execute();
        $users = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();

        $total = $db->query("SELECT COUNT(*) AS cnt FROM users")->fetch_assoc()['cnt'];
    }

    $db->close();
    sendSuccess([
        'data'       => $users,
        'pagination' => ['page' => $page, 'limit' => $limit, 'total' => (int)$total],
    ]);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input    = json_decode(file_get_contents('php://input'), true);
    $name     = trim($input['name']     ?? '');
    $mobile   = trim($input['mobile']   ?? '');
    $password = trim($input['password'] ?? '');
    $role     = trim($input['role']     ?? 'EMPLOYEE');

    if (!$name || !$mobile || !$password) {
        sendError('name, mobile and password are required');
    }

    $allowed_roles = ['SUPER_ADMIN', 'EMPLOYEE'];
    if (!in_array($role, $allowed_roles)) {
        sendError('Invalid role');
    }

    // Auto-generate employee_id
    $last = $db->query("SELECT employee_id FROM users ORDER BY id DESC LIMIT 1")->fetch_assoc();
    $nextNum = 1;
    if ($last) {
        preg_match('/\d+$/', $last['employee_id'], $m);
        $nextNum = (int)($m[0] ?? 0) + 1;
    }
    $employee_id = 'EMP' . str_pad($nextNum, 3, '0', STR_PAD_LEFT);

    $hashed = password_hash($password, PASSWORD_DEFAULT);

    $stmt = $db->prepare("
        INSERT INTO users (name, employee_id, mobile, password, role, status)
        VALUES (?, ?, ?, ?, ?, 'ACTIVE')
    ");
    $stmt->bind_param("sssss", $name, $employee_id, $mobile, $hashed, $role);

    if (!$stmt->execute()) {
        if ($db->errno === 1062) {
            sendError('Mobile number already exists', 409);
        }
        sendError('Failed to create user', 500);
    }
    $stmt->close();
    $db->close();

    sendSuccess([], 'User created successfully');
}

sendError('Method not allowed', 405);
