<?php

namespace App\Http\Livewire;

use App\Models\Contract;
use App\Models\Plan;
use Livewire\Component;

class ContractDetailController extends Component
{
    public $id_contract, $name_contract, $description_contract, $type_contract, $sub_type_contract, $content_contract, $status_contract;
    public $breadcrumb_show = true;

    public function mount($id)
    {
        UserAuthPermission('Contract_index');
        $this->id_contract = $id;
        $this->pageTitle = 'Contratos';
        $this->componentName = 'Editar';
        $contract = Contract::find($this->id_contract);

        if ($contract == null) {
            return redirect()->route('contratos');
        }
        $this->name_contract = $contract->name;
        $this->description_contract = $contract->description;
        $this->type_contract = $contract->type;
        $this->sub_type_contract = $contract->sub_type;
        $this->status_contract = $contract->status;
        $this->content_contract = $contract->content;
    }

    public function render()
    {
        $plans = Plan::all();
        return view('livewire.contracts.detail.component',compact('plans'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    protected $listeners = ['refreshContracts' => 'refresh'];

    public function Update()
    {

        $rules =[
            'name_contract' => "required|max:99|unique:contracts,name,{$this->id_contract}",
            'description_contract' => 'required|max:255',
            'type_contract' => 'required',
            'sub_type_contract' => 'required',
            'status_contract' => 'required',
        ];
        $messages =[
            'name_contract.required' => 'El campo nombre es obligatorio',
            'name_contract.max' => 'El campo nombre debe tener máximo 99 caracteres',
            'name_contract.unique' => 'El nombre del contrato ya existe',
            'description_contract.required' => 'El campo descripción es obligatorio',
            'description_contract.max' => 'El campo descripción debe tener máximo 255 caracteres',
            'type_contract.required' => 'El campo tipo de contratoes obligatorio',
            'sub_type_contract.required' => 'El campo sub tipo de contrato es obligatorio',
            'status_contract.required' => 'El campo estado es obligatorio',
        ];
        $this->validate($rules,$messages);
        debug($this->id_contract);
        $contract = Contract::find($this->id_contract);
        $contract->update([
            'name' => $this->name_contract,
            'description' => $this->description_contract,
            'type' => $this->type_contract,
            'sub_type' => $this->sub_type_contract,
            'status' => $this->status_contract,
            'content' => $this->content_contract,
        ]);
        $this->emit('contract-updated','Contrato actualizado correctamente');
    }
}
