<?php

/*
 * PuzzleApp
 * Webemyos
 * Jérôme Oliva
 * GNU Licence
 */

namespace Apps\DownloadManager;

use Core\Core\Core;
use Core\Core\Request;
use Core\Core\Response;
use Apps\Base\Base;
use Apps\DownloadManager\Helper\DocumentHelper;
use Apps\DownloadManager\Module\Admin\AdminController;
use Apps\DownloadManager\Module\Front\FrontController;
use Apps\DownloadManager\Module\Download\DownloadController;
use Apps\DownloadManager\Widget\AdminDashBoard\AdminDashBoard;
use Apps\DownloadManager\Widget\DownloadManagerEmailDownloadForm\DownloadManagerEmailDownloadForm;
use Apps\DownloadManager\Widget\DownloadManagerButton\DownloadManagerButton;

class DownloadManager extends Base {

    public $Author = 'Webemyos';
    public $Version = '1.0.0.0';

    function __construct($core = "") {
        $this->Core = Core::getInstance();
        parent::__construct($this->Core, "DownloadManager");
    }

    /**
     * Exécution de l'application
     */
    function Run() {
        echo parent::RunApp($this->Core, "DownloadManager", "DownloadManager");
    }

    /**
     * Routes publiques
     */
    function GetRoute($routes = "") {
        parent::GetRoute([
            "downloads/" => "Detail",
            "Detail",
            "DownloadFile",
            "SaveEmailAndDownload",
        ]);
        return $this->Route;
    }

    /**
     * Post-installation
     */
    function PostInstall() {
        \Apps\EeApp\Helper\AppHelper::UpdateAppParams(
                $this->Core,
                "DownloadManager",
                $this->Version,
                "Gestionnaire de téléchargements",
                1,
                0
        );
        \Apps\EeApp\Helper\AppHelper::CreateDataDir("DownloadManager");
    }

    // ─── Pages Front ────────────────────────────────────────────────────────────

    /**
     * Page d'accueil : liste des documents
     */
    function Index() {
        $this->Core->MasterView->Set("Title", $this->Core->GetCode("DownloadManager.HomePageTitle"));
        $frontController = new FrontController($this->Core);
        return $frontController->Index();
    }

    /**
     * Page de détail d'un document
     */
    function Detail($params) {
        if ($params == "") {
            $this->Core->MasterView->Set("Title", $this->Core->GetCode("DownloadManager.HomePageTitle"));
            $frontController = new FrontController($this->Core);
            return $frontController->Index();
        } else {
            $this->Core->MasterView->Set("Title", $this->Core->GetCode("DownloadManager.DocumentDetail"));
            $frontController = new FrontController($this->Core);
            return $frontController->Detail($params);
        }
    }

    // ─── Téléchargement ─────────────────────────────────────────────────────────

    /**
     * Enregistre l'email et prépare le téléchargement (AJAX)
     */
    function SaveEmailAndDownload() {
        $downloadController = new DownloadController($this->Core);
        return $downloadController->SaveEmailAndDownload(Request::GetPosts());
    }

    /**
     * Téléchargement effectif du fichier (route publique)
     */
    function DownloadFile($token) {
        $downloadController = new DownloadController($this->Core);
        return $downloadController->DownloadFile($token);
    }

    // ─── Admin : Documents ───────────────────────────────────────────────────────

    /**
     * Sauvegarde un document (ajout / modification)
     */
    function SaveDocument() {
        if (DocumentHelper::SaveDocument($this->Core, Request::GetPosts())) {
            $adminController = new AdminController($this->Core);
            return Response::Success($adminController->GetTabDocument());
        }
        return Response::Error();
    }

    /**
     * Supprime un document
     */
    function DeleteDocument() {
        if (DocumentHelper::DeleteDocument($this->Core, Request::GetPost("documentId"))) {
            $adminController = new AdminController($this->Core);
            return Response::Success($adminController->GetTabDocument());
        }
        return Response::Error();
    }

    /**
     * Edition d'un document (ouvre le dialogue admin)
     */
    function EditDocument($documentId) {
        // Géré côté JS via DownloadManager.ShowEditDocument()
    }

    // ─── Admin : Catégories ──────────────────────────────────────────────────────

    /**
     * Sauvegarde une catégorie
     */
    function SaveCategory() {

        $adminController = new AdminController($this->Core);
        $result = $adminController->SaveCategory(Request::GetPosts());

        if ($result === true) {
            return Response::Success($adminController->GetTabCategory());
        } else {
            return Response::Error();
        }
    }

    /**
     * Supprime une catégorie
     */
    function DeleteCategory() {
        $category = new \Apps\DownloadManager\Entity\DmCategory($this->Core);
        $category->GetById(Request::GetPost("categoryId"));
        $category->Delete();

        $adminController = new AdminController($this->Core);
        return Response::Success($adminController->GetTabCategory());
    }

    // ─── Upload ──────────────────────────────────────────────────────────────────

    /**
     * Transfert des fichiers uploadés dans le répertoire Tmp
     */
    function DoUploadFile($idElement, $tmpFileName, $fileName, $action) {

        $directory = "Data/Tmp";

        if ($action == "SaveDocumentFile") {
            move_uploaded_file($tmpFileName, $directory . "/" . $fileName);
            echo Response::Success([
                "type" => "DOCUMENT",
                "file" => $directory . "/" . $fileName,
                "Message" => "OK",
            ]);
        } elseif ($action == "SaveThumbnailFile") {
            move_uploaded_file($tmpFileName, $directory . "/" . $idElement . ".jpg");
            echo Response::Success(["type" => "IMAGE", "Message" => "OK"]);
        }
    }

    // ─── Widgets ─────────────────────────────────────────────────────────────────

    /**
     * Retourne un widget
     */
    public function GetWidget($type = "", $params = "") {
        switch ($type) {
            case "AdminDashboard":
                $widget = new AdminDashBoard($this->Core);
                return $widget->Render($params);

            case "EmailDownloadForm":
                $widget = new DownloadManagerEmailDownloadForm($this->Core, $params);
                $widget->Load(["Token" => $params]);
                return $widget->Render();
            case "DownloadButton":
                $widget = new DownloadManagerButton($this->Core, $params);
                return $widget->Render();
        }
    }

    /***
     * Widget can be Added in the Cms App
     */
    function GetListWidget(){
        return array(
                    array("Name" => "DownloadButton", 
                        $this->Core->GetCode("DownloadMananger.DescriptionDownloadButton"),
                         "Parameters"  => $this->GetListDocument()
                        )
        );
    }

        /***
     * List of ressource
     */
    public function GetListDocument(){
        $list = new \Core\Control\EntityListBox\EntityListBox("Data", $this->Core);
        $list->Entity = "\Apps\DownloadManager\Entity\DmDocument"; 
        $list->AddField("Name");
        return $list->Render();
    }

    
    // ─── API (utilisées par le JS front) ─────────────────────────────────────────

    /**
     * Retourne la liste des documents (JSON)
     */
    function GetDocuments() {
        return Response::Success(DocumentHelper::GetAll($this->Core, true));
    }

    /**
     * Retourne un document par son ID (JSON)
     */
    function GetDocument() {
        return Response::Success(DocumentHelper::GetDocument($this->Core, Request::GetPost("documentId"), true));
    }
}

?>
