<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Carrera;
use App\Encabezadopie;
use App\Exports\CarreraExport;
use App\VistaCarreras;
use Barryvdh\DomPDF\Facade\Pdf;
use Maatwebsite\Excel\Facades\Excel;

class CarreraController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = $request->all();
        $carrera = "";
        if (count($data) > 0) {
            //$carrera = Carrera::where('estado', '1');
            $carrera = VistaCarreras::where('estado', '1');

            if ($data['nombre'] != null) {
                $carrera = $carrera->where('nombre', 'like', '%' . $data['nombre'] . '%');
            }
            if ($data['tipo'] != null) {
                $carrera = $carrera->where('tipo', $data['tipo']);
            }

            if ($data['fechaA'] != null) {
                $carrera = $carrera->whereDate('fecha_apertura', $data['fechaA']);
            }
            $carrera = $carrera->get();
        } else {
            $carrera = VistaCarreras::where('estado', '1')->get();

            //$carrera = Carrera::where('estado', '1')->orderBy('nombre')->get();
        }

        return view('carrera.listar', compact('carrera', 'data'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request;
        $calidad = 60;
        $cve = Carrera::latest('id')->first();

        if ($cve == null) {
            $cve = ['id' => 0];
        }
        $log = $request->file('logo');
        if ($log != null) {
            $extension = explode('.', $log->getClientOriginalName());
            if ($extension[count($extension) - 1] == "webp") {

                $log->move(getcwd() . "/img/logo_carreras/" . ($data['nombre']) . "000" . ($cve['id'] + 1) . ".webp");
            } else {
                $image = \Image::make($log);
                $image->save(getcwd() . "/img/logo_carreras/" . ($data['nombre']) . "000" . ($cve['id'] + 1) . ".webp", $calidad);
            }
        }
        if ($log == null) {
            return response()->json(
                ['nombre' => $data['nombre'], 'abreviatura' => $data['abre'], 'tipo' => $data['tipo'], 'estado' => '1', 'logo' => null]
            );
        } else {
            return response()->json(
                ['nombre' => $data['nombre'], 'abreviatura' => $data['abre'], 'tipo' => $data['tipo'], 'estado' => '1', 'logo' => $data['nombre'] . "000" . ($cve['id'] + 1) . ".webp"]
            );
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $car = VistaCarreras::where('id', $id)->first();
        return view('carrera.consultar', compact('car'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $car = Carrera::where('id', $id)->first();
        return view('carrera.modificar', compact('car'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = $request;
        if ($request->file('logo') != null) {
            $calidad = 60;
            $log = $request->file('logo');
            $extension = explode('.', $log->getClientOriginalName());
            if ($extension[count($extension) - 1] == "webp") {

                $log->move(getcwd() . "/img/logo_carreras/" . ($request['nombre']) . "000" . ($id) . ".webp");
            } else {
                $image = \Image::make($log);
                $image->save(getcwd() . "/img/logo_carreras/" . ($request['nombre']) . "000" . ($id) . ".webp", $calidad);
            }

            $car = Carrera::findOrFail($id);
            $car->logo = ($request['nombre']) . "000" . ($id) . ".webp";
            $car->save();
        }

        $car = Carrera::findOrFail($id);

        $car->nombre = $request->nombre;
        $car->abreviatura = $request->abre;
        $car->tipo = $request->tipo;
        $car->save();
        return response()->json(['estado' => 'Exito', 'mensaje' => 'Carrera actualizada con exito!']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $car = Carrera::find($id);
        $car->estado = '0';
        $car->save();

        return response()->json(['estado' => 'Exito', 'mensaje' => 'Carrera eliminada con exito!']);
    }

    public function exportExcel(Request $request)
    {
        $data = $request->all();
        $nombre = $data['nombre'];
        $tipo = $data['tipo'];
        $fecha = $data['fechaA'];
        if ($nombre == null) {
            $nombre = "";
        }
        if ($tipo == null) {
            $tipo = "";
        }
        if ($fecha == null) {
            $fecha = "";
        }

        return Excel::download(new CarreraExport($nombre, $tipo, $fecha), 'carreras.xlsx');
    }

    public function exportPdf(Request $request)
    {
        $data = $request->all();
        $nom = $data['nombre'];
        $tip = $data['tipo'];
        $fechaA = $data['fechaA'];
        $pdf = "";

        $enca = Encabezadopie::max('cve_encpie');
        $enca = Encabezadopie::where('cve_encpie', $enca)->first();
        if ($nom == "" && $tip == "" && $fechaA == "") {
            $periodo = "";
            $pdf = Pdf::loadView('carrera.tablapdf', ['carrera' => Carrera::where('estado', '1')->get(), 'enca' => $enca]);
        } else {
            $carrera = Carrera::where('estado', '1');
            if ($nom != "") {
                $carrera = $carrera->where('nombre', 'like', '%' . $nom . '%');
            }
            if ($tip != "") {
                $carrera = $carrera->where('tipo', $tip);
            }
            if ($fechaA != "") {
                $carrera = $carrera->whereDate('fecha_apertura', $fechaA);
            }
            $carrera = $carrera->get();
            $pdf = Pdf::loadView('carrera.tablapdf', ['carrera' => $carrera, 'enca' => $enca]);
        }

        return $pdf->download('carrera.pdf');
    }
}
