<?php

// Incluir arquivos necessários
include "../../autoload.php";
include "../../configuracoes/functions.php";

class AppBackgroundHandler {
    private $appId;
    private $userId;
    private $apiClass;

    public function __construct() {
        $this->apiClass = new Api(conexaoPDOlocal());
    }

    public function validateParameters() {
        if (!isset($_GET["app_id"]) || !isset($_GET["user_id"])) {
            $this->returnErrorResponse();
            return false;
        }
        
        $this->appId = intval($_GET["app_id"]);
        $this->userId = intval($_GET["user_id"]);
        return true;
    }

    public function process() {
        $appInfo = $this->getAppInfo();
        if (!$appInfo) {
            $this->returnAccessDenied();
            return;
        }

        $appSettings = $this->getAppSettings($appInfo);
        $bgImageUrl = $appSettings["app_bg_canais"] ?? '';

        if (empty($bgImageUrl)) {
            $this->returnTransparentImage();
            return;
        }

        $this->outputImage($bgImageUrl);
    }

    private function getAppInfo() {
        return $this->apiClass->getAppsByIDAndOwnerID($this->appId, $this->userId);
    }

    private function getAppSettings($appInfo) {
        return json_decode($appInfo["app_settings"], true) ?? [];
    }

    private function returnErrorResponse() {
        http_response_code(400);
        echo json_encode(["status" => false, "msg" => "Parâmetros faltando na requisição"]);
        exit;
    }

    private function returnAccessDenied() {
        http_response_code(403);
        header('Content-Type: application/json');
        echo json_encode(["code" => -11, "result" => "Access Denied: You do not have permission"]);
        exit;
    }

    private function returnTransparentImage() {
        header('Content-Type: image/png');
        $img = imagecreatetruecolor(1, 1);
        imagesavealpha($img, true);
        $transparent = imagecolorallocatealpha($img, 0, 0, 0, 127);
        imagefill($img, 0, 0, $transparent);
        imagepng($img);
        imagedestroy($img);
        exit;
    }

    private function outputImage($url) {
        $contentType = $this->getImageContentType($url);
        header("Content-Type: $contentType");

        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false
        ));

        $imageData = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200 || empty($imageData)) {
            $this->returnTransparentImage();
            return;
        }

        echo $imageData;
        exit;
    }

    private function getImageContentType($url) {
        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => true,
            CURLOPT_NOBODY => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false
        ));
        
        curl_exec($ch);
        $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
        curl_close($ch);
        
        return $contentType ?: 'image/png';
    }
}

$backgroundHandler = new AppBackgroundHandler();
if ($backgroundHandler->validateParameters()) {
    $backgroundHandler->process();
}
?>
