<?php

namespace App\Http\Controllers;

use App\Models\Nps;
use Dompdf\Dompdf;
use Dompdf\Options;
use Illuminate\Http\Request;

class RelatoriosController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $status = $request['status'];
        $unidade = $request['unidade'];
        $dtInicio = $request['date_inicial'];
        $dtFinal = $request['date_final'];

        $nps = Nps::where('status', $status)->where('updated_at', '>=', $dtInicio)->where('updated_at', '<=', $dtFinal)->orderBy('updated_at', 'asc')->get();

        if($unidade != "Todas as unidades"){
            $nps = Nps::where('status', $status)->where('cidade', $unidade)->where('updated_at', '>=', $dtInicio)->where('updated_at', '<=', $dtFinal)->orderBy('updated_at', 'asc')->get();
        }

        $total = 0;

        foreach ($nps as $nota) {
            $total += $nota->previsto;
        }

        $options = new Options();
        $options->set('isRemoteEnabled', TRUE);

        $pdf = new Dompdf($options);

        $pdf->loadHtml(view('pdfs.relatorio', compact(['nps', 'status', 'unidade', 'dtInicio', 'dtFinal', 'total'])));
        $pdf->setPaper('A4');
        $pdf->setBasePath(public_path()); // This line resolve
        $pdf->render();
        ob_get_clean();
        $pdf->stream("", array("Attachment" => false));

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

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

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
