<?php

namespace App\Http\Controllers\Webprofile\Front;

use App\Http\Controllers\Controller;
use App\Models\Webprofile\Categories;
use App\Models\Webprofile\CategoriesFile;
use App\Models\Webprofile\Design;
use App\Models\Webprofile\File;
use App\Models\Webprofile\Menu;
use App\Models\Webprofile\Posts;
use App\Repositories\Webprofile\FileRepository;

class DownloadController extends Controller
{
    public function index()
    {
        $categoriesFile = CategoriesFile::where('is_active', 1)->orderBy('created_at', 'DESC')->with(['rFile'])->get();
        $setting = webprofilesetting();
        $menu = Menu::orderby('urutan', 'asc')->get();
        $hot = Posts::where('post_status', '1')->orderby('viewer', 'desc')->limit('5')->get();
        $categories = Categories::where('is_active', '1')->get();
        $widget_right = Design::where('name_design', 'widget_right')->orderBy('urutan', 'ASC')->get();
        $widget_left = Design::where('name_design', 'widget_left')->orderBy('urutan', 'ASC')->get();
        $footer = Design::where('name_design', 'like', '%footer_row%')->get();

        $data = [
            'categoriesFile' => $categoriesFile,
            'setting' => $setting,
            'menu' => $menu,
            'hot' => $hot,
            'categories' => $categories,
            'widget_right' => $widget_right,
            'widget_left' => $widget_left,
            'footer' => $footer,
        ];

        return view('webprofile.front.'.$setting['theme'].'.download', $data);
    }

    public function downloadFile($id)
    {
        $setting = webprofilesetting();

        $fileModel = new File();
        $fileRepo = new FileRepository($fileModel);

        $dbfile = File::find($id);

        if ($setting['external_storage'] == 1) {
            $file = $setting['url_static'].'/'.$setting['directory'].'/file/'.$dbfile->file;
        } else {
            $file = url('/storage/file/'.$dbfile->file);
        }

        $fileRepo->countDownload($dbfile);

        // if ($fileRepo->is_url_exist($file)) {
        $filename = $dbfile->slug;
         $tempImage = tempnam(sys_get_temp_dir(), $filename);
         stream_context_set_default([
                 'ssl' => [
                     'verify_peer' => false,
                     'verify_peer_name' => false,
                 ],
             ]);
         copy($file, $tempImage);


        return response()->download($tempImage, $filename)->deleteFileAfterSend(true);
        // } else {
        //     Alert::error('File tidak ditemukan');
        //     return redirect()->back();
        // }
    }
}
