<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\ContratoAseguradora;
use App\Models\Docs;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class ContratoAseguradorasController extends Controller
{
    var $timestampUnique = 0;
    var $meses = [];
    public function __construct()
    {
        //Los registros tengan la misma fecha y hora exacta
        $this->timestampUnique = Carbon::now('GMT-6');
	    $this->meses    = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
    }
    
    public function store(Request $request){

        DB::transaction(function() use($request) {

            $contrato = new ContratoAseguradora();
            $contrato->insurance_subsection = $request->subseccion;
            $contrato->fk_insurance = $request->aseguradora;
            $contrato->insurance_startup_date = $request->inicio_contrato;
            $contrato->insurance_expiration_date = $request->expiracion_contrato;
            $contrato->fk_entity_company = $request->corporativo;
            $contrato->anual_contract_fee = $request->costo_anual;
            $contrato->fk_vehicle = $request->fk_vehicle;
            $contrato->save();


            $docs = new Docs();
            $docs->fk_vehicle = $request->fk_vehicle;
            $docs->document_module = 'CONTRATO ASEGURADORA';
            if($request->file('fileContract')) {
                $doc_file = $request->file('fileContract');
                $docs->name_file = $doc_file->getClientOriginalName();
                $docs->created_at = Carbon::now();
                $filePath = env('FOLDER_DIRECTIVE_AWS').'/Activos/vehiculos/'.$request->fk_vehicle.'/PolizaAseguramiento/'.date("Y").'/'.$this->meses[date('m') - 1];
                $url_s3 = Storage::disk('s3')->put($filePath, $doc_file, 'public');
                $docs->url_file = $url_s3;

                //ALTA EN TABLA HISTORICO POLIZAS ASEGURAMIENTO
                DB::table('historico_polizas_aseguramiento')->insert([
                    'fk_vehicle' => $request->fk_vehicle,
                    'fk_user' => $request->id_usuario,
                    'url_file' => $url_s3,
                    'fecha_transaccion' => $this->timestampUnique,
                ]);
                //ALTA EN TABLA HISTORICO POLIZAS ASEGURAMIENTO
            }
            $docs->save();
        });
        return response("success", 200);
    }

    public function update(Request $request, $id){

        DB::transaction(function() use($request) {

            $DocumentoExist = Docs::where('fk_vehicle', $request->fk_vehicle)
            ->where('document_module', 'CONTRATO ASEGURADORA')->get();
            if($DocumentoExist){
                Docs::where('fk_vehicle', $request->fk_vehicle)
                ->where('document_module', 'CONTRATO ASEGURADORA')->update([
                    'status' => false,
                ]);
            }

            ContratoAseguradora::where('pk_insurance_contract', $request->pk_insurance_contract)
                ->update([
                    'insurance_subsection' => $request->edit_subseccion,
                    'fk_insurance' => $request->aseguradora,
                    'insurance_startup_date' => $request->edit_inicio_contrato,
                    'insurance_expiration_date' => $request->edit_expiracion_contrato,
                    'fk_entity_company' => $request->corporativo,
                    'anual_contract_fee' => $request->edit_costo_anual,
                ]);

            $docs = new Docs();
            $docs->fk_vehicle = $request->fk_vehicle;
            $docs->document_module = 'CONTRATO ASEGURADORA';
            Log::info("antes de entrar");
            if($request->file('fileContract')) {
                Log::info("despues de entrar");
                $doc_file = $request->file('fileContract');
                $docs->name_file = $doc_file->getClientOriginalName();
                $docs->created_at = Carbon::now();
                $filePath = env('FOLDER_DIRECTIVE_AWS').'/Activos/vehiculos/'.$request->fk_vehicle.'/PolizaAseguramiento/'.date("Y").'/'.$this->meses[date('m') - 1];
                $url_s3 = Storage::disk('s3')->put($filePath, $doc_file, 'public');
                $docs->url_file = $url_s3;

                //ALTA EN TABLA HISTORICO POLIZAS ASEGURAMIENTO
                DB::table('historico_polizas_aseguramiento')->insert([
                    'fk_vehicle' => $request->fk_vehicle,
                    'fk_user' => $request->id_usuario,
                    'url_file' => $url_s3,
                    'fecha_transaccion' => $this->timestampUnique,
                ]);
                //ALTA EN TABLA HISTORICO POLIZAS ASEGURAMIENTO
            }
            Log::info("antes de terminar");
            $docs->save();
        });
        return response($request->all(), 200);
    }

    public function findByVehicle($id){
        $contratoInfo = ContratoAseguradora::where('fk_vehicle', $id)->get();
        return response($contratoInfo, 200);
    }
}
