<?php

namespace App\Middleware;

use App\Utils\JWT;
use App\Utils\Env;
use App\Config\Database;
use PDO;

class AdminMiddleware {
    public static function authenticate() {
        // 1. Try Session Auth (For Admin Panel)
        if (isset($_SESSION['admin_id'])) {
            $db = Database::getInstance()->getConnection();
            $stmt = $db->prepare("SELECT id, role FROM admin_users WHERE id = ?");
            $stmt->execute([$_SESSION['admin_id']]);
            $admin = $stmt->fetch();
            if ($admin) return $admin;
        }

        // 2. Try Bearer Token (For API Clients)
        $headers = getallheaders();
        $authHeader = isset($headers['Authorization']) ? $headers['Authorization'] : '';

        if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
            $token = $matches[1];
            $secret = Env::get('JWT_SECRET');
            $payload = JWT::decode($token, $secret);

            if ($payload) {
                // Check if admin exists in DB
                $db = Database::getInstance()->getConnection();
                $stmt = $db->prepare("SELECT id, role FROM admin_users WHERE id = ?");
                $stmt->execute([$payload['sub']]);
                $admin = $stmt->fetch();

                if ($admin) return $admin;
            }
        }

        // Failed both
        http_response_code(401);
        echo json_encode(['error' => 'Unauthorized']);
        exit;
    }
}
