<?php

namespace App\Http\Livewire;

use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use App\Http\Middleware\TenantMiddleware;

class Causal extends Component
{
    public $recordsIn, $recordsOut, $parent_id,  $name, $enabled, $corrispettivo_fiscale, $no_receipt, $money, $user_status, $no_first, $no_records, $no_reports, $type, $dataId, $update = false, $add = false;

    public $corrispettivo_causal_id = 0;

    public $parent = '';
    public $showHidden = false;

    protected $rules = [
        'name' => 'required',
        'type' => 'required'
    ];

    protected $messages = [
        'name.required' => 'Il nome è obbligatorio'
    ];

    public function boot()
    {
        app(TenantMiddleware::class)->setupTenantConnection();
    }

    public function mount()
    {
        $this->loadRecords();
    }

    public function hide($id)
    {
        try {
            \App\Models\Causal::whereId($id)->update(['hidden' => true]);
            session()->flash('success', 'Causale nascosta');
            $this->loadRecords(); // Refresh the data
        } catch (\Exception $ex) {
            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
        }
    }

    public function show($id)
    {
        try {
            \App\Models\Causal::whereId($id)->update(['hidden' => false]);
            session()->flash('success', 'Causale ripristinata');
            $this->loadRecords(); // Refresh the data
        } catch (\Exception $ex) {
            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
        }
    }

    public function toggleHidden()
    {
        $this->showHidden = !$this->showHidden;
        $this->loadRecords();
    }

    public function loadRecords()
    {
        if ($this->showHidden) {
            // Show all records including hidden ones
            $this->recordsIn = \App\Models\Causal::where('type', 'IN')
                ->where('parent_id', null)
                ->with(['childs'])
                ->orderBy('name')
                ->get();

            $this->recordsOut = \App\Models\Causal::where('type', 'OUT')
                ->where('parent_id', null)
                ->with(['childs'])
                ->orderBy('name')
                ->get();
        } else {
            // Show only non-hidden records
            $this->recordsIn = \App\Models\Causal::where('type', 'IN')
                ->where('parent_id', null)
                ->where(function ($query) {
                    $query->where('hidden', false)->orWhereNull('hidden');
                })
                ->with(['childs' => function ($query) {
                    $query->where(function ($q) {
                        $q->where('hidden', false)->orWhereNull('hidden');
                    });
                }])
                ->orderBy('name')
                ->get();

            $this->recordsOut = \App\Models\Causal::where('type', 'OUT')
                ->where('parent_id', null)
                ->where(function ($query) {
                    $query->where('hidden', false)->orWhereNull('hidden');
                })
                ->with(['childs' => function ($query) {
                    $query->where(function ($q) {
                        $q->where('hidden', false)->orWhereNull('hidden');
                    });
                }])
                ->orderBy('name')
                ->get();
        }
    }

    public function resetFields()
    {
        $this->name = '';
        $this->parent_id = null;
        $this->parent = '';
        $this->type = null;
        $this->money = false;
        $this->corrispettivo_fiscale = false;
        $this->no_receipt = false;
        $this->user_status = false;
        $this->no_first = false;
        $this->no_records = false;
        $this->no_reports = false;
        $this->enabled = true;
    }

    public function render()
    {
        // Remove the duplicate queries - loadRecords() already handles this
        // and make sure it respects the showHidden state
        if (!isset($this->recordsIn) || !isset($this->recordsOut)) {
            $this->loadRecords();
        }

        return view('livewire.causal');
    }

    public function add()
    {
        $this->resetFields();
        $this->add = true;
        $this->update = false;
    }

    public function addLevel($parent_id)
    {
        $this->resetFields();
        $this->parent_id = $parent_id;
        $p = \App\Models\Causal::findOrFail($parent_id);
        $this->type = $p->type;
        $this->parent = $p->name;
        $this->add = true;
        $this->update = false;
    }

    public function store()
    {
        $this->validate();
        try {
            \App\Models\Causal::create([
                'name' => $this->name,
                'type' => $this->type,
                'parent_id' => $this->parent_id,
                'money' => $this->money,
                'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
                'no_receipt' => $this->no_receipt,
                'user_status' => $this->user_status,
                'no_first' => $this->no_first,
                'no_records' => $this->no_records,
                'no_reports' => $this->no_reports,
                'enabled' => $this->enabled
            ]);
            session()->flash('success', 'Causale creata');
            $this->resetFields();
            $this->add = false;
            $this->loadRecords();
        } catch (\Exception $ex) {
            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
        }
    }

    public function edit($id)
    {
        try {
            $causal = \App\Models\Causal::findOrFail($id);
            if (!$causal) {
                session()->flash('error', 'Causale non trovata');
            } else {
                $this->name = $causal->name;
                $this->money = $causal->money;
                $this->no_receipt = $causal->no_receipt;
                $this->user_status = $causal->user_status;
                $this->no_first = $causal->no_first;
                $this->no_records = $causal->no_records;
                $this->no_reports = $causal->no_reports;
                $this->enabled = $causal->enabled;
                $this->corrispettivo_fiscale = $causal->corrispettivo_fiscale;
                $this->type = $causal->type;
                $this->parent_id = $causal->parent_id;
                $this->dataId = $causal->id;
                $this->update = true;
                $this->add = false;
            }
        } catch (\Exception $ex) {
            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
        }
    }

    public function update()
    {
        $this->validate();
        try {
            \App\Models\Causal::whereId($this->dataId)->update([
                'name' => $this->name,
                'type' => $this->type,
                'parent_id' => $this->parent_id,
                'user_status' => $this->user_status,
                'no_first' => $this->no_first,
                'no_records' => $this->no_records,
                'no_reports' => $this->no_reports,
                'money' => $this->money,
                'no_receipt' => $this->no_receipt,
                'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
                'enabled' => $this->enabled
            ]);
            session()->flash('success', 'Causale aggiornata');
            $this->resetFields();
            $this->update = false;
            $this->loadRecords();
        } catch (\Exception $ex) {
            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
        }
    }

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

    public function duplicate($id)
    {
        $old = \App\Models\Causal::find($id);
        $new = $old->replicate();
        $new->name = $new->name . ' - COPIA';
        $new->save();

        $this->duplicateRecursive($old, $new);
        $this->loadRecords(); // Refresh after duplicate
    }

    public function duplicateRecursive($old, $new)
    {
        foreach ($old->childs as $c) {
            $old1 = \App\Models\Causal::find($c->id);
            $new1 = $old1->replicate();
            $new1->parent_id = $new->id;
            $new1->save();

            $this->duplicateRecursive($old1, $new1);
        }
    }

    public function reorder()
    {
        $this->loadRecords(); // Refresh after reorder
    }
}
