<?php
// Arquivo: includes/LogoManager.php
// Gerenciador centralizado de logos para todos os painéis

class LogoManager {
    private $db;
    private $panel_type;
    private $panel_user;
    
    public function __construct($panel_type, $panel_user) {
        $this->panel_type = $panel_type; // 'admin', 'revenda', 'sub_revenda'
        $this->panel_user = $panel_user;
        $this->db = new SQLite3(dirname(__DIR__) . '/a/.eggziedb.db');
    }
    
    /**
     * Obtém o caminho da logo atual para o painel
     */
    public function getLogo() {
        $table_check = $this->db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='panel_logos'");
        if (!$table_check->fetchArray()) {
            $this->createLogosTable();
            return $this->getDefaultLogo();
        }
        
        $stmt = $this->db->prepare("SELECT logo_path FROM panel_logos WHERE panel_type = :panel_type AND panel_user = :panel_user");
        $stmt->bindValue(':panel_type', $this->panel_type, SQLITE3_TEXT);
        $stmt->bindValue(':panel_user', $this->panel_user, SQLITE3_TEXT);
        $result = $stmt->execute();
        $row = $result->fetchArray(SQLITE3_ASSOC);
        
        if ($row && !empty($row['logo_path'])) {
            return $row['logo_path'];
        }
        
        return $this->getDefaultLogo();
    }
    
    /**
     * Atualiza a logo do painel
     */
    public function updateLogo($logo_path, $upload_type = 'by_file') {
        $stmt = $this->db->prepare("SELECT id FROM panel_logos WHERE panel_type = :panel_type AND panel_user = :panel_user");
        $stmt->bindValue(':panel_type', $this->panel_type, SQLITE3_TEXT);
        $stmt->bindValue(':panel_user', $this->panel_user, SQLITE3_TEXT);
        $result = $stmt->execute();
        $existing = $result->fetchArray(SQLITE3_ASSOC);
        
        if ($existing) {
            $stmt = $this->db->prepare("UPDATE panel_logos SET logo_path = :logo_path, upload_type = :upload_type, updated_at = CURRENT_TIMESTAMP WHERE panel_type = :panel_type AND panel_user = :panel_user");
        } else {
            $stmt = $this->db->prepare("INSERT INTO panel_logos (panel_type, panel_user, logo_path, upload_type) VALUES (:panel_type, :panel_user, :logo_path, :upload_type)");
        }
        
        $stmt->bindValue(':panel_type', $this->panel_type, SQLITE3_TEXT);
        $stmt->bindValue(':panel_user', $this->panel_user, SQLITE3_TEXT);
        $stmt->bindValue(':logo_path', $logo_path, SQLITE3_TEXT);
        $stmt->bindValue(':upload_type', $upload_type, SQLITE3_TEXT);
        
        return $stmt->execute() !== false;
    }
    
    /**
     * Salva a configuração da logo para o aplicativo
     * CORREÇÃO: Salva em TODOS os possíveis JSONs usados pelo app, com URL absoluta
     */
    public function saveAppLogo($logo_data) {
        // Garantir que o ImageName seja uma URL absoluta (já deve vir pronta)
        $logo_url = $logo_data['ImageName'];
        
        // Definir os arquivos JSON que o aplicativo pode ler
        $json_paths = [];
        
        if ($this->panel_type == 'admin') {
            $json_paths[] = dirname(__DIR__) . '/a/rtx/logo_filenames.json';
            $json_paths[] = dirname(__DIR__) . '/a/rtx/image_filenames.json';
            $json_paths[] = dirname(__DIR__) . '/a/rtx/logo_filenames_admin.json';
            $json_paths[] = dirname(__DIR__) . '/a/rtx/image_filenames_admin.json';
        } else {
            $user = $this->panel_user;
            $json_paths[] = dirname(__DIR__) . "/a/rtx/logo_filenames_{$user}.json";
            $json_paths[] = dirname(__DIR__) . "/a/rtx/image_filenames_{$user}.json";
        }
        
        $success = true;
        foreach ($json_paths as $path) {
            $dir = dirname($path);
            if (!file_exists($dir)) {
                mkdir($dir, 0777, true);
            }
            $data_to_save = [["ImageName" => $logo_url, "Upload_type" => $logo_data['Upload_type']]];
            if (file_put_contents($path, json_encode($data_to_save, JSON_PRETTY_PRINT)) === false) {
                $success = false;
            }
        }
        return $success;
    }
    
    /**
     * Cria a tabela de logos se não existir
     */
    private function createLogosTable() {
        $this->db->exec("CREATE TABLE IF NOT EXISTS panel_logos (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            panel_type TEXT NOT NULL,
            panel_user TEXT NOT NULL,
            logo_path TEXT,
            upload_type TEXT DEFAULT 'by_file',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            UNIQUE(panel_type, panel_user)
        )");
        
        $this->db->exec("CREATE INDEX IF NOT EXISTS idx_panel_logos ON panel_logos(panel_type, panel_user)");
    }
    
    /**
     * Retorna o caminho da logo padrão
     */
    private function getDefaultLogo() {
        $default_logos = [
            'admin' => '../img/logo.png',
            'revenda' => '../img/logo1.png',
            'sub_revenda' => '../img/logo1.png'
        ];
        
        return $default_logos[$this->panel_type] ?? '../img/logo.png';
    }
    
    public function close() {
        if ($this->db) {
            $this->db->close();
        }
    }
    
    public function __destruct() {
        $this->close();
    }
}
?>