<?php
/**
 * Auth Controller — Login, Logout, Session Management
 */

use Firebase\JWT\JWT;

class AuthController {
    private PDO $db;

    public function __construct(PDO $db) {
        $this->db = $db;
    }

    /**
     * POST /auth/login
     * Authenticates user and returns JWT token.
     */
    public function login(array $data): void {
        Validator::check($data, [
            'username' => 'required|string',
            'password' => 'required|string'
        ]);

        // Find user
        $stmt = $this->db->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$data['username']]);
        $user = $stmt->fetch();

        if (!$user || !password_verify($data['password'], $user['password_hash'])) {
            Response::unauthorized('یوزر نیم یا پاس ورڈ غلط ہے۔');
        }

        if ($user['status'] !== 'active') {
            Response::forbidden('آپ کا اکاؤنٹ بلاک ہے۔ ایڈمن سے رابطہ کریں۔');
        }

        // Generate JWT
        $payload = [
            'user_id'  => $user['id'],
            'username' => $user['username'],
            'role'     => $user['role'],
            'iat'      => time(),
            'exp'      => time() + Database::JWT_EXPIRY
        ];

        $token = JWT::encode($payload, Database::JWT_SECRET, 'HS256');

        // Store session
        $tokenHash = hash('sha256', $token);
        $stmt = $this->db->prepare("
            INSERT INTO user_sessions (user_id, token_hash, ip_address, user_agent) 
            VALUES (?, ?, ?, ?)
        ");
        $stmt->execute([
            $user['id'],
            $tokenHash,
            $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
        ]);

        // Get permissions
        $permStmt = $this->db->prepare("SELECT module, can_view, can_create, can_edit, can_delete, can_print FROM permissions WHERE user_id = ?");
        $permStmt->execute([$user['id']]);
        $permissions = [];
        foreach ($permStmt->fetchAll() as $p) {
            $permissions[$p['module']] = [
                'view'   => (bool) $p['can_view'],
                'create' => (bool) $p['can_create'],
                'edit'   => (bool) $p['can_edit'],
                'delete' => (bool) $p['can_delete'],
                'print'  => (bool) $p['can_print']
            ];
        }

        // Audit log
        AuditLogger::log($this->db, $user['id'], 'LOGIN', 'users', $user['id']);

        Response::success([
            'token' => $token,
            'user'  => [
                'id'          => $user['id'],
                'username'    => $user['username'],
                'full_name'   => $user['full_name'],
                'department'  => $user['department'],
                'role'        => $user['role'],
                'permissions' => $permissions
            ]
        ], 'خوش آمدید! لاگ ان کامیاب ہے۔');
    }

    /**
     * POST /auth/logout
     * Invalidates the current session.
     */
    public function logout(object $user): void {
        $headers = getallheaders();
        $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
        preg_match('/Bearer\s(\S+)/', $authHeader, $matches);
        $token = $matches[1] ?? '';
        $tokenHash = hash('sha256', $token);

        $stmt = $this->db->prepare("
            UPDATE user_sessions 
            SET is_active = 0, logout_at = NOW() 
            WHERE user_id = ? AND token_hash = ?
        ");
        $stmt->execute([$user->id, $tokenHash]);

        AuditLogger::log($this->db, $user->id, 'LOGOUT', 'users', $user->id);

        Response::success(null, 'لاگ آؤٹ کامیاب ہے۔');
    }
}
