<?php

namespace App\Http\Controllers\Admin;

use App\Facades\ReportManager;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ReportController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $reports = ReportManager::all();

        return view('admin.reports.index', compact('reports'));
    }

    /**
     * Display the specified resource.
     *
     * @param string $reportName
     * @return \Symfony\Component\HttpFoundation\StreamedResponse
     */
    public function show(string $reportName)
    {
        return ReportManager::download($reportName);
    }

      /**
     * Display the specified resource.
     *
     * @param string $reportName
     * @return \Symfony\Component\HttpFoundation\StreamedResponse
     */
    public function delete(string $reportName)
    {
         ReportManager::delete($reportName);

         return redirect()->route('admin.reports.index')
            ->with('success', 'Извештај успешно обрисан.');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Respons
     */
    public function store(Request $request)
    {
        return ReportManager::generateAndDownload();
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Respons
     */
    public function generate(string $reportName)
    {
        $name = "Izvestaj" . Carbon::now('Europe/Belgrade')->format("dmY") . ".doc";
        $headers = array(
            "Content-type"=>"text\html",
            "Content-Disposition"=>"attachment;Filename=${name}"
        );
      
        $path = storage_path() . "/app/public/reports/${reportName}";
        $contents = file_get_contents($path);

        $docx = \Response::make($contents,200, $headers);
        $pathdocx = "reports/" . $name;
        Storage::disk('public')->put($pathdocx, $docx);
        
        //
        //file_put_contents($pathdocx, $docx);
    
        return redirect("/reports");
    }

    public function reset()
    {
        ReportManager::clear();

        return redirect()->route('admin.reports.index')
            ->with('success', 'Анкета је ресетована.');
    }

    public function destroy()
    {
        return ReportManager::archive();
    }
}
