<?php

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

namespace Apps\DownloadManager\Module\Download;

use Core\Controller\Controller;
use Core\Core\Request;
use Apps\DownloadManager\Entity\DmDocument;
use Apps\DownloadManager\Helper\DocumentHelper;

class DownloadController extends Controller {

    function _construct($core = "") {
        $this->Core = $core;
    }

    function Create() {}
    function Init()   {}

    function Show($all = true) {
        return $this->Index();
    }

    function Index() {}

    /**
     * Enregistre l'email et déclenche le téléchargement
     * Appelé en AJAX depuis EmailDownloadForm.js
     */
    function SaveEmailAndDownload($data) {

        $token      = $data["Token"];
        $email      = $data["Email"];
        $documentId = base64_decode($token);

        // Validation email basique
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return \Core\Core\Response::Error(["message" => "Invalid email"]);
        }

        $document = new DmDocument($this->Core);
        $document->GetById($documentId);

        if ($document->IdEntite != "") {

            // Enregistrement du téléchargement
            DocumentHelper::RegisterDownload($this->Core, $documentId, $email);

            // Retourne le token pour que le JS redirige vers DownloadFile
            return \Core\Core\Response::Success(["token" => $token]);
        }

        return \Core\Core\Response::Error(["message" => "Document not found"]);
    }

    /**
     * Téléchargement effectif du fichier
     * Route publique : /DownloadManager/DownloadFile/{token}
     */
    function DownloadFile($token) {

        $documentId = base64_decode($token);

        $document = new DmDocument($this->Core);
        $document->GetById($documentId);

        if ($document->IdEntite != "") {

            $directory = $document->DirectoryDocument . $document->IdEntite . "/";
            $files     = glob($directory . "*");

            $files = array_filter($files, function ($file) {
                return strtolower(pathinfo($file, PATHINFO_EXTENSION)) !== 'png' && strtolower(pathinfo($file, PATHINFO_EXTENSION)) !== 'jpg';
            });

            //Pour reindex a partir de 0
            $files = array_values($files);
            
            
            if (count($files) > 0) {
                $filePath = $files[0];
                $info     = explode("/", $filePath);
                
                $fileName = $info[count($info) - 1];

                header("Content-Type: application/octet-stream");
                header("Content-Disposition: attachment; filename=" . $fileName);
                header("Content-Length: " . filesize($filePath));

                readfile($filePath);
                ob_flush();
                exit;
            }
        }

        $this->Core->Redirect("/Home");
    }
}

?>
