<?php

namespace App\Http\Controllers;

use App\Models\Sedes;
use Illuminate\Http\Request;

class SedesController extends Controller
{
    public function getSedesContrato(Request $request) {
        return Sedes::on('costos_principal')
                    ->selectRaw('sed_pk_id as ser_pk_id, con_fk_id, ins_fk_id, sed_nombre_sede as ser_nombre_sede,
                                 sed_direccion as ser_direccion, sedes.dep_fk_id, dep_nombre, mun_fk_id, mun_nombre')
                    ->leftJoin('departamentos', 'dep_pk_id', 'sedes.dep_fk_id')
                    ->leftJoin('municipios', 'mun_pk_id', 'mun_fk_id')
                    ->where('sedes.con_fk_id', $request->input('con_fk_id'))
                    ->where('sedes.ins_fk_id', $request->input('ins_fk_id'))
                    ->get()->toArray();
    }

    public function crearSedeContrato(Request $request) {
        $id = null;

        \DB::transaction(function() use($request, &$id) {
            $idSede = Sedes::on('costos_principal')
                           /*->where('con_fk_id', $request->input('con_fk_id'))
                           ->where('ins_fk_id', $request->input('ins_fk_id'))*/
                           ->orderBy('sed_pk_id', 'desc')
                           ->first()['sed_pk_id'];

            $id = Sedes::on('costos_principal')->create(
                [
                    "sed_pk_id" => $idSede + 1,
                    "con_fk_id" => $request->input('con_fk_id'),
                    "ins_fk_id" => $request->input('ins_fk_id'),
                    "sed_nombre_sede" => $request->input('sed_nombre_sede'),
                    "sed_direccion" => $request->input('sed_direccion'),
                    "dep_fk_id" => $request->input('dep_fk_id'),
                    "mun_fk_id" => $request->input('mun_fk_id')
                ]
            )->sed_pk_id;
        });

        return array("response" => $id);
    }

    public function actualizarSedeContrato(Request $request) {
        Sedes::on('costos_principal')->where('sed_pk_id', $request->input('sed_pk_id'))
                                     ->where('con_fk_id', $request->input('con_fk_id'))
        ->update(
            [
                "sed_nombre_sede" => $request->input('sed_nombre_sede'),
                "sed_direccion" => $request->input('sed_direccion'),
                "dep_fk_id" => $request->input('dep_fk_id'),
                "mun_fk_id" => $request->input('mun_fk_id')
            ]
        );

        return array("response" => 1);
    }
}
