<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use App\Http\Middleware\TenantMiddleware;
class Supplier extends Component
{
    public $records, $name, $fiscal_code, $vat, $address, $zip_code, $nation_id, $province_id, $city_id, $referent, $website, $phone, $email, $enabled, $dataId, $update = false, $add = false;
    public $referent_first_name, $referent_last_name, $referent_email, $referent_phone, $referent_mobile, $showReset = false;
    public $isItaly = true;

    public $searchTxt;
    public $search;
    public $showArchived = false;
    protected $rules = [
        'name' => 'required',
        'vat' => 'nullable|unique:suppliers,vat',
        'fiscal_code' => 'nullable|unique:suppliers,fiscal_code'
    ];

    protected $messages = [
        'name.required' => 'Il nome è obbligatorio',
        'vat.unique' => 'Un fornitore con questa Partita IVA esiste già',
        'fiscal_code.unique' => 'Un fornitore con questo Codice Fiscale esiste già'
    ];
    public function boot()
    {
        app(TenantMiddleware::class)->setupTenantConnection();
    }


    public function resetFields()
    {
        $this->name = '';
        $this->fiscal_code = '';
        $this->vat = '';
        $this->address = '';
        $this->zip_code = '';
        $this->nation_id = null;
        $this->province_id = null;
        $this->city_id = null;
        $this->referent = '';
        $this->website = '';
        $this->phone = '';
        $this->email = '';
        $this->enabled = true;
        $this->referent_first_name = '';
        $this->referent_last_name = '';
        $this->referent_email = '';
        $this->referent_phone = '';
        $this->referent_mobile = '';
        $this->emit('load-data-table');
    }

    public $sortField = 'name';
    public $sortAsc = true;

    public function sortBy($field)
    {
        if ($this->sortField === $field) {
            $this->sortAsc = ! $this->sortAsc;
        } else {
            $this->sortAsc = true;
        }

        $this->sortField = $field;
    }

    public function mount()
    {
        if (Auth::user()->level != env('LEVEL_ADMIN', 0))
            return redirect()->to('/dashboard');

        if (isset($_GET["new"]))
            $this->add();
    }

    public function search()
    {
        if ($this->searchTxt != '') {
            $this->search = $this->searchTxt;
            $this->showReset = true;
        }
    }

    public function resetSearch()
    {
        $this->showReset = false;
        $this->searchTxt = '';
        $this->search = $this->searchTxt;
    }

    public function render()
    {
        if ($this->showArchived) {
            // Show all suppliers including archived ones
            $this->records = \App\Models\Supplier::orderBy('name')->get();
        } else {
            // Show only non-archived suppliers
            $this->records = \App\Models\Supplier::where(function($query) {
                $query->where('archived', 0)->orWhereNull('archived');
            })->orderBy('name')->get();
        }

        return view('livewire.supplier');
    }
    public function hydrate()
    {
        $this->emit('load-select');
    }

    public function checkIsItaly()
    {
        $n = \App\Models\Nation::findOrFail($this->nation_id);
        $this->isItaly = $n->is_italy;
    }

    public function add()
    {
        $this->resetFields();
        $this->emit('load-select');
        $this->add = true;
        $this->update = false;
        $this->emit('setEdit', true);
    }

    private function cleanEmptyFields()
    {
        $this->vat = trim($this->vat) === '' ? null : trim($this->vat);
        $this->fiscal_code = trim($this->fiscal_code) === '' ? null : trim($this->fiscal_code);
    }

    public function store()
    {
        $this->validate();

        $vatToCheck = trim($this->vat);
        $existingSupplier = \App\Models\Supplier::where('vat', $vatToCheck)->first();

        Log::info('VAT validation detailed debug', [
            'vat_input' => $this->vat,
            'vat_trimmed' => $vatToCheck,
            'vat_empty_check' => empty($vatToCheck),
            'existing_supplier_id' => $existingSupplier ? $existingSupplier->id : null,
            'existing_supplier_name' => $existingSupplier ? $existingSupplier->name : null,
            'existing_supplier_vat' => $existingSupplier ? $existingSupplier->vat : null,
            'validation_rules' => $this->rules
        ]);

        if (!empty($vatToCheck)) {
            $duplicateCount = \App\Models\Supplier::where('vat', $vatToCheck)->count();
            if ($duplicateCount > 0) {
                Log::info('VAT duplicate found, adding error');
                $this->addError('vat', 'Già esiste un fornitore con questa Partita IVA');
                return;
            }
        }

        $fiscalCodeToCheck = trim($this->fiscal_code);
        if (!empty($fiscalCodeToCheck)) {
            $duplicateFiscalCount = \App\Models\Supplier::where('fiscal_code', $fiscalCodeToCheck)->count();
            if ($duplicateFiscalCount > 0) {
                Log::info('Fiscal code duplicate found, adding error');
                $this->addError('fiscal_code', 'Già esiste un fornitore con questo codice fiscale ');
                return;
            }
        }

        try {
            \App\Models\Supplier::create([
                'name' => $this->name,
                'fiscal_code' => !empty($fiscalCodeToCheck) ? $fiscalCodeToCheck : null,
                'vat' => !empty($vatToCheck) ? $vatToCheck : null,
                'address' => $this->address,
                'zip_code' => $this->zip_code,
                'nation_id' => $this->nation_id,
                'province_id' => $this->province_id > 0 ? $this->province_id : null,
                'city_id' => $this->city_id > 0 ? $this->city_id : null,
                'referent' => $this->referent,
                'website' => $this->website,
                'phone' => $this->phone,
                'email' => $this->email,
                'referent_first_name' => $this->referent_first_name,
                'referent_last_name' => $this->referent_last_name,
                'referent_email' => $this->referent_email,
                'referent_phone' => $this->referent_phone,
                'referent_mobile' => $this->referent_mobile,
                'enabled' => $this->enabled
            ]);
            session()->flash('success', 'Fornitore creato');
            $this->resetFields();
            $this->add = false;
            $this->emit('setEdit', false);
        } catch (\Exception $ex) {
            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
        }
    }

    public function edit($id)
    {
        $this->emit('load-select');
        try {
            $supplier = \App\Models\Supplier::findOrFail($id);
            if (!$supplier) {
                session()->flash('error', 'Fornitore non trovato');
            } else {
                $this->name = $supplier->name;
                $this->fiscal_code = $supplier->fiscal_code;
                $this->vat = $supplier->vat;
                $this->address = $supplier->address;
                $this->zip_code = $supplier->zip_code;
                $this->nation_id = $supplier->nation_id;
                $this->province_id = $supplier->province_id;
                $this->city_id = $supplier->city_id;
                $this->referent = $supplier->referent;
                $this->website = $supplier->website;
                $this->phone = $supplier->phone;
                $this->email = $supplier->email;
                $this->referent_first_name = $supplier->referent_first_name;
                $this->referent_last_name = $supplier->referent_last_name;
                $this->referent_email = $supplier->referent_email;
                $this->referent_phone = $supplier->referent_phone;
                $this->referent_mobile = $supplier->referent_mobile;
                $this->enabled = $supplier->enabled;
                $this->dataId = $supplier->id;
                $this->update = true;
                $this->add = false;
                $this->checkIsItaly();
                $this->emit('load-provinces', $this->nation_id, 'provinceClass');
                $this->emit('load-cities', $this->province_id, 'cityClass');

                $this->emit('setEdit', true);
            }
        } catch (\Exception $ex) {
            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
        }
    }

    public function cancel()
    {
        $this->add = false;
        $this->update = false;
        $this->resetFields();
        $this->emit('setEdit', false);
    }

    // Replace delete method with anonymize method
    public function anonymize($id)
    {
        try {
            $supplier = \App\Models\Supplier::findOrFail($id);

            // Anonymize all fields
            $supplier->update([
                'name' => 'Fornitore Anonimizzato',
                'fiscal_code' => null,
                'vat' => null,
                'address' => null,
                'zip_code' => null,
                'nation_id' => null,
                'province_id' => null,
                'city_id' => null,
                'referent' => null,
                'website' => null,
                'phone' => null,
                'email' => null,
                'referent_first_name' => null,
                'referent_last_name' => null,
                'referent_email' => null,
                'referent_phone' => null,
                'referent_mobile' => null,
                'archived' => true, // Mark as archived
                'enabled' => false // Also disable the supplier
            ]);

            session()->flash('success', "Fornitore anonimizzato");
            return redirect(request()->header('Referer'));
        } catch (\Exception $e) {
            session()->flash('error', 'Errore (' . $e->getMessage() . ')');
        }
    }

    public function getNation($nation)
    {
        if ($nation > 0) {
            $ret = \App\Models\Nation::findOrFail($nation);
            return $ret->name;
        }
        return "";
    }

    public function getProvince($province)
    {
        if ($province > 0) {
            $ret = \App\Models\Province::findOrFail($province);
            return $ret->name;
        }
        return "";
    }

    public function getCity($city)
    {
        if ($city > 0) {
            $ret = \App\Models\City::findOrFail($city);
            return $ret->name;
        }
        return "";
    }

    protected function getRulesForUpdate()
    {
        return [
            'name' => 'required',
            'vat' => 'nullable|unique:suppliers,vat,' . $this->dataId,
            'fiscal_code' => 'nullable|unique:suppliers,fiscal_code,' . $this->dataId
        ];
    }

    public function update()
    {
        // Clean empty fields first
        $this->cleanEmptyFields();

        $this->validate($this->getRulesForUpdate());

        try {
            \App\Models\Supplier::whereId($this->dataId)->update([
                'name' => $this->name,
                'fiscal_code' => $this->fiscal_code,
                'vat' => $this->vat,
                'address' => $this->address,
                'zip_code' => $this->zip_code,
                'nation_id' => $this->nation_id,
                'province_id' => $this->province_id > 0 ? $this->province_id : null,
                'city_id' => $this->city_id > 0 ? $this->city_id : null,
                'referent' => $this->referent,
                'website' => $this->website,
                'phone' => $this->phone,
                'email' => $this->email,
                'referent_first_name' => $this->referent_first_name,
                'referent_last_name' => $this->referent_last_name,
                'referent_email' => $this->referent_email,
                'referent_phone' => $this->referent_phone,
                'referent_mobile' => $this->referent_mobile,
                'enabled' => $this->enabled
            ]);
            session()->flash('success', 'Fornitore aggiornato');
            $this->resetFields();
            $this->update = false;

            $this->emit('setEdit', false);
        } catch (\Exception $ex) {
            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
        }
    }
}
