<?php

namespace App\Livewire\Dashboard\Client;

use Livewire\Component;
use App\Models\Client;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class Save extends Component
{
    public $client;
    public $user_id;
    public $amount_owed;
    public $daily_payment;
    public $start_date;
    public $end_date;
    public $status;

    public function mount(?int $id = null)
    {
        if ($id != null) {
            $this->client = Client::findOrFail($id);

            $this->user_id = $this->client->user_id;
            $this->amount_owed = $this->client->amount_owed;
            $this->daily_payment = $this->client->daily_payment;
            $this->start_date = $this->client->start_date;
            $this->end_date = $this->client->end_date;
            $this->status = $this->client->status;

            // Verificar acceso solo si el usuario no es super_admin
            if (Auth::user()->role !== 'super_admin' && Auth::user()->company_id !== $this->client->user->company_id) {
                session()->flash('error', 'No tienes acceso a esta página.');
                return redirect()->route('d-client-index');
            }
        }
    }

    public function render()
    {
        $users = User::all();
        return view('livewire.dashboard.client.save', compact('users'))->layout('layouts.app');
    }

    public function submit()
    {
        // Validar los datos
        $this->validate([
            'user_id' => ['required', 'integer', 'exists:users,id'],
            'amount_owed' => ['required', 'numeric', 'min:0'],
            'daily_payment' => ['required', 'numeric', 'min:0'],
            'start_date' => ['required', 'date'],
            'end_date' => ['required', 'date'],
            'status' => ['required', 'string', 'in:activo,inactivo'],
        ]);

        if ($this->client) {
            // Actualizar cliente existente
            $this->client->update([
                'user_id' => $this->user_id,
                'amount_owed' => $this->amount_owed,
                'daily_payment' => $this->daily_payment,
                'start_date' => $this->start_date,
                'end_date' => $this->end_date,
                'status' => $this->status,
            ]);

            $this->dispatch('updated');
        } else {
            // Crear nuevo cliente
            Client::create([
                'user_id' => $this->user_id,
                'amount_owed' => $this->amount_owed,
                'daily_payment' => $this->daily_payment,
                'start_date' => $this->start_date,
                'end_date' => $this->end_date,
                'status' => $this->status,
            ]);

            // Emitir mensaje de éxito
            session()->flash('success', 'Cliente guardado exitosamente.');

            // Resetear los campos del formulario
            $this->reset(['user_id', 'amount_owed', 'daily_payment', 'start_date', 'end_date', 'status']);
        }
    }
}
