<?php
/*=========================================================================================
    App Name  : PPID PTUN Kupang
    File Name : FrontEndController
    --------------------------------------------------------------------------------------
    Author    : Fuad Auliya Rohman
    Email     : fuad.dev16@gmail.com
==========================================================================================*/

namespace App\Http\Controllers;

use App\Models\Article;
use App\Models\ReportFile;
use Illuminate\Http\Request;
use Modules\Artikel\Services\ArtikelServiceInterface;
use Modules\Laporan\Services\LaporanServiceInterface;

class FrontEndController extends Controller
{
    protected $FileLoc = 'pages.frontend.';
    protected $table = 'FrontEndTable';
    protected $targetModal = 'app-modal';
    protected $artikelService, $laporanService;

    public function __construct(ArtikelServiceInterface $artikelService, LaporanServiceInterface $laporanService)
    {
        $this->artikelService = $artikelService;
        $this->laporanService = $laporanService;
    }

    public function home()
    {
        $Menu = get_main_menu();

        ///dd($Menu);

        return view($this->FileLoc. 'home');
    }

    public function page(string $slug)
    {
        $Slug = $slug;
        $Article = $this->artikelService->findBy('slug', $Slug);

        if (!$Article || !$Article->slug) {
            return redirect()->route('home');
        }

        $bc = breadcrumbFrontend(array(
            ['link' => '#', 'page' => $Article->tittle],
        ));

        $Article->update(['hits' => ($Article->hits == NULL)? '1':$Article->hits+1 ]);

        return view($this->FileLoc . 'page',[
            'bc' => $bc,
            'Article' => $Article,
        ]);
    }

    public function report(string $slug)
    {
        $Slug = $slug;
        $Report = $this->laporanService->findBy('slug', $Slug);
        $ReportFile = ReportFile::where('reports_id', $Report->id)->OrderBy('id','asc')->get();

        if (!$Report || !$Report->slug) {
            return redirect()->route('home');
        }

        $bc = breadcrumbFrontend(array(
            ['link' => '#', 'page' => $Report->tittle],
        ));

        $Report->update(['hits' => ($Report->hits == NULL)? '1': $Report->hits+1 ]);

        return view($this->FileLoc . 'report',[
            'bc' => $bc,
            'Report' => $Report,
            'ReportFile' => $ReportFile,
        ]);
    }

    public function download(string $hash_id)
    {
        $id = decryptString($hash_id);

        if (empty($hash_id)) {
            return redirect()->back();
        }

        $File = ReportFile::findOrFail($id);

        if (!$File) {
            return redirect()->back()->with("error", __('messages.data_not_found'));
        }

        $FileLocation = public_path('storage/' . config('ppid.upload_path') . config('ppid.laporan'));

        return response()->download($FileLocation . $File->file);
    }
}
