<?php

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

namespace Apps\DownloadManager\Helper;

use Core\Utility\Format\Format;
use Core\Utility\File\File;
use Core\Utility\Date\Date;
use Apps\DownloadManager\Entity\DmDocument;
use Apps\DownloadManager\Entity\DmDownload;
use Apps\DownloadManager\Widget\DownloadManagerDocumentForm\DownloadManagerDocumentForm;

class DocumentHelper {

    /**
     * Sauvegarde un document (ajout ou modification)
     */
    public static function SaveDocument($core, $data) {

        $documentForm = new DownloadManagerDocumentForm($core, $data);

        if ($documentForm->Validate($data)) {

            $document = new DmDocument($core);

            if ($data["Id"] != "") {
                $document->GetById($data["Id"]);
            } else {
                $document->Status->Value    = 1;
                $document->DateCreated->Value = Date::Now();
            }

            $document->Code->Value = Format::ReplaceForUrl($data["Name"]);
            
            $documentForm->Populate($document);
    

            $document->Save();

            $id = ($data["Id"] != "") ? $data["Id"] : $core->Db->GetInsertedId();

            // Création des répertoires
            File::CreateDirectory("Data/Apps/DownloadManager");
            File::CreateDirectory("Data/Apps/DownloadManager/Document/");
            File::CreateDirectory("Data/Apps/DownloadManager/Thumbnail/");

            // Sauvegarde du fichier document
            $dirDocument = $document->DirectoryDocument . $id . "/";
            $dirImage = $document->DirectoryImage . $id . "/";
            
            File::CreateDirectory($dirDocument);

            foreach (explode(",", $data["dvUpload-UploadDocumentfileToUpload"]) as $file) {
                if ($file == "") continue;
                $source   = str_replace($core->GetPath("/"), "", $file);
                $filename = explode("/", $source);
                rename($source, $dirDocument . $filename[count($filename) - 1]);
            }

            foreach (explode(",", $data["dvUpload-UploadThumbnailfileToUpload"]) as $file) {
                if ($file == "") continue;
                $source   = str_replace($core->GetPath("/"), "", $file);
                $filename = explode("/", $source);
                rename($source, $dirDocument . "thumb.png");
            }

            return true;
        }

        return false;
    }

    /**
     * Supprime un document
     */
    public static function DeleteDocument($core, $documentId) {
        $document = new DmDocument($core);
        $document->GetById($documentId);
        $document->Delete();
        return true;
    }

    /**
     * Récupère tous les documents actifs
     */
    public static function GetAll($core, $asArray = false) {
        $document = new DmDocument($core);
        $results  = $document->Find("Status=1 ORDER BY DateCreated DESC");

        if ($asArray) {
            $list = [];
            foreach ($results as $doc) {
                $list[] = [
                    "IdEntite"    => $doc->IdEntite,
                    "Name"        => $doc->Name->Value,
                    "Code"        => $doc->Code->Value,
                    "Description" => $doc->Description->Value,
                    "FileType"    => $doc->FileType->Value,
                    "FileSize"    => $doc->FileSize->Value,
                    "DateCreated" => $doc->DateCreated->Value,
                    "Thumbnail"   => $doc->GetThumbnailPath(),
                ];
            }
            return $list;
        }

        return $results;
    }

    /**
     * Récupère un document par son ID
     */
    public static function GetDocument($core, $documentId, $asArray = false) {
        $document = new DmDocument($core);
        $document->GetById($documentId);

        if ($asArray) {
            return [
                "IdEntite"    => $document->IdEntite,
                "Name"        => $document->Name->Value,
                "Code"        => $document->Code->Value,
                "Description" => $document->Description->Value,
                "FileType"    => $document->FileType->Value,
                "FileSize"    => $document->FileSize->Value,
                "DateCreated" => $document->DateCreated->Value,
                "Thumbnail"   => $document->GetThumbnailPath(),
            ];
        }

        return $document;
    }

    /**
     * Récupère les documents par catégorie
     */
    public static function GetByCategory($core, $categoryId, $asArray = false) {
        $document = new DmDocument($core);
        return $document->Find("CategoryId=" . $categoryId . " AND Status=1");
    }

    /**
     * Enregistre un téléchargement avec email
     */
    public static function RegisterDownload($core, $documentId, $email) {

        $download = new DmDownload($core);
        $download->DocumentId->Value   = $documentId;
        $download->Email->Value        = $email;
        $download->DateDownload->Value = Date::Now();
        $download->IpAddress->Value    = $_SERVER['REMOTE_ADDR'] ?? '';
        $download->Save();

        return true;
    }

    /**
     * Génère le token base64 du document (pour le lien de téléchargement)
     */
    public static function GetDownloadToken($documentId) {
        return base64_encode($documentId);
    }

    /**
     * Statistiques de téléchargement par document (admin)
     */
    public static function GetDownloadStats($core) {
        $sql = "SELECT d.Id, d.Name, COUNT(dl.Id) AS DownloadCount
                FROM DmDocument d
                LEFT JOIN DmDownload dl ON dl.DocumentId = d.Id
                GROUP BY d.Id, d.Name
                ORDER BY DownloadCount DESC";

        return $core->Db->GetArray($sql);
    }
}

?>
