<?php
namespace Controllers;
require_once __DIR__ . '/../_Core/bootstrap.php';
class AuthController {
  public function tokenLogin($input){
    $username = $input['username'] ?? ''; $password = $input['password'] ?? ''; $device_id = $input['device_id'] ?? ''; $device_label = $input['device_label'] ?? ''; $platform = $input['platform'] ?? '';
    if (!$username || !$password) return ['status'=>0,'error'=>'missing_credentials'];
    $pdo = Database::getConnection();
    $stmt = $pdo->prepare('SELECT user_id, password_hash, role FROM users WHERE username = ? LIMIT 1');
    $stmt->execute([$username]); $user = $stmt->fetch(\PDO::FETCH_ASSOC);
    if (!$user) return ['status'=>0,'error'=>'invalid_credentials'];
    if (!password_verify($password, $user['password_hash'])) return ['status'=>0,'error'=>'invalid_credentials'];
    if (!$device_id) $device_id = bin2hex(random_bytes(12));
    $refresh = bin2hex(random_bytes(64)); $refresh_hash = hash_hmac('sha256', $refresh, $GLOBALS['CONFIG']['jwt_secret']);
    $now = date('Y-m-d H:i:s');
    $ins = $pdo->prepare('INSERT INTO user_devices (user_id, device_id, device_label, platform, user_agent, ip, refresh_token_hash, revoked, created_at, last_seen) VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?) ON DUPLICATE KEY UPDATE device_label=VALUES(device_label), platform=VALUES(platform), user_agent=VALUES(user_agent), ip=VALUES(ip), refresh_token_hash=VALUES(refresh_token_hash), revoked=0, last_seen=VALUES(last_seen)');
    $ins->execute([$user['user_id'], $device_id, $device_label, $platform, $_SERVER['HTTP_USER_AGENT'], $_SERVER['REMOTE_ADDR'], $refresh_hash, $now, $now]);
    $payload = json_encode(['uid'=>$user['user_id'],'did'=>$device_id,'iat'=>time(),'exp'=>time()+900]);
    $sig = hash_hmac('sha256', $payload, $GLOBALS['CONFIG']['jwt_secret']);
    $access = base64_encode($payload) . '.' . $sig;
    return ['status'=>1,'token'=>$access,'refresh_token'=>$refresh,'role'=>$user['role'],'user_id'=>$user['user_id'],'device_id'=>$device_id];
  }

  public function refreshToken($input){
    $refresh = $input['refresh'] ?? ''; $device_id = $input['device_id'] ?? '';
    if (!$refresh || !$device_id) return ['status'=>0,'error'=>'missing_params'];
    $pdo = Database::getConnection();
    $refresh_hash = hash_hmac('sha256', $refresh, $GLOBALS['CONFIG']['jwt_secret']);
    $stmt = $pdo->prepare('SELECT user_id, revoked FROM user_devices WHERE device_id = ? AND refresh_token_hash = ? LIMIT 1');
    $stmt->execute([$device_id, $refresh_hash]); $row = $stmt->fetch(\PDO::FETCH_ASSOC);
    if (!$row) return ['status'=>0,'error'=>'invalid_refresh'];
    if ($row['revoked']) return ['status'=>0,'error'=>'device_revoked'];
    $new_refresh = bin2hex(random_bytes(64)); $new_refresh_hash = hash_hmac('sha256', $new_refresh, $GLOBALS['CONFIG']['jwt_secret']);
    $upd = $pdo->prepare('UPDATE user_devices SET refresh_token_hash = ?, last_seen = ? WHERE device_id = ? AND user_id = ?');
    $upd->execute([$new_refresh_hash, date('Y-m-d H:i:s'), $device_id, $row['user_id']]);
    $payload = json_encode(['uid'=>$row['user_id'],'did'=>$device_id,'iat'=>time(),'exp'=>time()+900]);
    $sig = hash_hmac('sha256', $payload, $GLOBALS['CONFIG']['jwt_secret']);
    $access = base64_encode($payload) . '.' . $sig;
    return ['status'=>1,'token'=>$access,'refresh_token'=>$new_refresh,'user_id'=>$row['user_id']];
  }

  public function listDevices(){
    $user_id = $_SERVER['AUTH_USER_ID'] ?? null;
    if (!$user_id) return ['status'=>0,'error'=>'not_authed'];
    $pdo = Database::getConnection();
    $stmt = $pdo->prepare('SELECT device_id, device_label, platform, ip, app_version, last_seen, revoked FROM user_devices WHERE user_id = ? ORDER BY last_seen DESC');
    $stmt->execute([$user_id]); $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
    return ['status'=>1,'devices'=>$rows];
  }

  public function revokeDevice($input){
    $user_id = $_SERVER['AUTH_USER_ID'] ?? null; if (!$user_id) return ['status'=>0,'error'=>'not_authed'];
    $device_id = $input['device_id'] ?? ''; if (!$device_id) return ['status'=>0,'error'=>'missing_device'];
    $pdo = Database::getConnection();
    $upd = $pdo->prepare('UPDATE user_devices SET revoked = 1 WHERE user_id = ? AND device_id = ?'); $upd->execute([$user_id, $device_id]);
    return ['status'=>1,'revoked_device'=>$device_id];
  }
}
?>