<?php

namespace Predial\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use Predial\Avaluo;
use Predial\Predio;
use Predial\Tarifa;

class AvaluoController extends Controller{

    public $path = "avaluo.";

    public function index($id_unico){
        if(!empty(session()->get('usuario'))){
            $id      = decrypt($id_unico);
            $predio  = Predio::find($id);
            $data    = DB::table('gr_avaluo as ava')
                        ->select(
                            'ava.id_unico',
                            'ava.valor',
                            'ava.indicador',
                            'ava.anno',
                            'ava.tarifa',
                            'tar.nombre',
                            'tar.codigotarifa',
                            'tar.anio'
                        )
                        ->leftJoin('gr_tarifa as tar', 'ava.tarifa', '=', 'tar.id_unico')
                        ->where('ava.predio', '=', $id)
                        ->get();
            $tarifas = Tarifa::all();
            return view($this->path."index")->with('predio', $predio)->with('tarifas', $tarifas)->with('data', $data);
        }else{
            return redirect("CerrarSesion");
        }
    }

    public function store(Request $request){
        try {
            $predio = decrypt($request->txtPredio);
            $new    = new Avaluo();
            $new->anno      = $request->txtAnno;
            $new->valor     = $request->txtValor;
            $new->indicador = $request->optIndicador;
            $new->tarifa    = $request->sltTarifa;
            $new->predio    = $predio;
            $new->save();

            flash()->overlay('Información guardada correctamente', 'Información');

            return back();
        } catch (Exception $e) {
            return "Fatal Error = ".$e->getMessage();
        }
    }
}
