<?php
// POST /api/login

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendError('Method not allowed', 405);
}

$input     = json_decode(file_get_contents('php://input'), true);
$mobile    = trim($input['mobile']    ?? '');
$password  = trim($input['password']  ?? '');
$device_id = trim($input['device_id'] ?? '');

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

$db = getDB();

// Find user
$stmt = $db->prepare("SELECT id, name, employee_id, password, role, status FROM users WHERE mobile = ?");
$stmt->bind_param("s", $mobile);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

// if (!$user || !password_verify($password, $user['password'])) {
//     sendError('Invalid mobile or password', 401);
// }

if (!$user) {
    sendError('Mobile number is incorrect', 401);
}

if (!password_verify($password, $user['password'])) {
    sendError('Password is incorrect', 401);
}

if ($user['status'] === 'INACTIVE') {
    sendError('Account is inactive.', 403);
}

// Remove all previous sessions for this user (single active session)
$stmt = $db->prepare("DELETE FROM devices WHERE user_id = ?");
$stmt->bind_param("i", $user['id']);
$stmt->execute();
$stmt->close();

// Generate token
$token = generateJWT(['user_id' => $user['id'], 'device_id' => $device_id]);

// Store new session
$stmt = $db->prepare("
    INSERT INTO devices (device_id, user_id, token)
    VALUES (?, ?, ?)
    ON DUPLICATE KEY UPDATE user_id = VALUES(user_id), token = VALUES(token)
");
$stmt->bind_param("sis", $device_id, $user['id'], $token);
$stmt->execute();
$stmt->close();

// Fetch permissions for this role
$stmt = $db->prepare("
    SELECT p.name
    FROM role_permissions rp
    JOIN roles r  ON r.id = rp.role_id
    JOIN permissions p ON p.id = rp.permission_id
    WHERE r.name = ?
");
$stmt->bind_param("s", $user['role']);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
$db->close();

$permissions = array_column($rows, 'name');

// Build dynamic menu from permissions
$menu = [];

if (in_array('DASHBOARD_VIEW', $permissions)) {
    $menu[] = ['name' => 'Dashboard', 'path' => 'Dashboard', 'icon' => 'home'];
}

$userMenuChildren = [];
if (in_array('USER_CREATE', $permissions)) $userMenuChildren[] = ['name' => 'Add User',   'path' => 'AddUser'];
if (in_array('USER_EDIT',   $permissions) ||
    in_array('USER_DELETE', $permissions) ||
    in_array('USER_CREATE', $permissions)) {
    $userMenuChildren[] = ['name' => 'User List', 'path' => 'UserList'];
}

if (!empty($userMenuChildren)) {
    $menu[] = ['name' => 'Users', 'path' => 'Users', 'icon' => 'users', 'children' => array_values($userMenuChildren)];
}

if (in_array('READING_VIEW', $permissions)) {
    $menu[] = ['name' => 'Readings', 'path' => 'Readings', 'icon' => 'file-text'];
}

if (in_array('REPORT_VIEW', $permissions)) {
    $menu[] = ['name' => 'Reports', 'path' => 'Reports', 'icon' => 'bar-chart'];
}

if (in_array('ROLE_MANAGE', $permissions)) {
    $menu[] = ['name' => 'Roles', 'path' => 'Roles', 'icon' => 'shield'];
}

$menu[] = ['name' => 'Profile', 'path' => 'Profile', 'icon' => 'user'];

sendSuccess([
    'token' => $token,
    'user'  => [
        'id'          => $user['id'],
        'name'        => $user['name'],
        'employee_id' => $user['employee_id'],
        'role'        => $user['role'],
    ],
    'permissions' => $permissions,
    'menu'        => $menu,
]);
