<?php

namespace App\Livewire;

use Livewire\Component;
use Livewire\WithPagination;
use App\Models\Party;
use Illuminate\Validation\Rule;

class Parties extends Component
{
    use WithPagination;

    public $search = '';
    public $statusFilter = 'all';
    public $isModalOpen = false;
    
    // Form fields
    public $party_id;
    public $code;
    public $name;
    public $short_name;
    public $reference_number;
    public $document_number;
    public $tax_number;
    public $phone;
    public $email;
    public $address;
    public $notes;
    public $is_active = true;

    // Warnings array for soft validation
    public $duplicate_warnings = [];

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function updatingStatusFilter()
    {
        $this->resetPage();
    }

    public function openModal()
    {
        abort_if(!auth()->user()->can('create records'), 403);
        $this->resetValidation();
        $this->reset([
            'party_id', 'code', 'name', 'short_name', 'reference_number', 
            'document_number', 'tax_number', 'phone', 'email', 'address', 'notes',
            'duplicate_warnings'
        ]);
        $this->is_active = true;
        $this->isModalOpen = true;
    }

    public function closeModal()
    {
        $this->isModalOpen = false;
    }

    public function edit($id)
    {
        abort_if(!auth()->user()->can('update records'), 403);
        $this->resetValidation();
        $party = Party::findOrFail($id);
        
        $this->party_id = $party->id;
        $this->code = $party->code;
        $this->name = $party->name;
        $this->short_name = $party->short_name;
        $this->reference_number = $party->reference_number;
        $this->document_number = $party->document_number;
        $this->tax_number = $party->tax_number;
        $this->phone = $party->phone;
        $this->email = $party->email;
        $this->address = $party->address;
        $this->notes = $party->notes;
        $this->is_active = $party->is_active ? 1 : 0;
        
        $this->duplicate_warnings = [];
        $this->isModalOpen = true;
    }

    public function toggleStatus($id)
    {
        abort_if(!auth()->user()->can('update records'), 403);
        $party = Party::findOrFail($id);
        $party->is_active = !$party->is_active;
        $party->save();
        
        session()->flash('message', $party->is_active ? 'تم تنشيط الطرف بنجاح.' : 'تم إيقاف الطرف بنجاح.');
    }

    protected function rules()
    {
        return [
            'code' => ['required', 'string', 'max:255', Rule::unique('parties')->ignore($this->party_id)],
            'name' => ['required', 'string', 'max:255'],
            'short_name' => ['nullable', 'string', 'max:255'],
            'reference_number' => ['nullable', 'string', 'max:255'],
            'document_number' => ['nullable', 'string', 'max:255'],
            'tax_number' => ['nullable', 'string', 'max:255'],
            'phone' => ['nullable', 'string', 'max:255'],
            'email' => ['nullable', 'email', 'max:255'],
            'address' => ['nullable', 'string'],
            'notes' => ['nullable', 'string'],
            'is_active' => ['boolean'],
        ];
    }

    protected function messages()
    {
        return [
            'code.required' => 'حقل رمز الطرف مطلوب.',
            'code.unique' => 'هذا الرمز مسجل مسبقاً، يرجى اختيار رمز آخر.',
            'name.required' => 'حقل اسم الطرف مطلوب.',
            'email.email' => 'صيغة البريد الإلكتروني غير صحيحة.',
        ];
    }

    public function updated($propertyName, $value)
    {
        $this->validateOnly($propertyName);
        $this->checkDuplicates($propertyName, $value);
    }

    public function checkDuplicates($property, $value)
    {
        if (empty($value)) {
            if (isset($this->duplicate_warnings[$property])) {
                unset($this->duplicate_warnings[$property]);
            }
            return;
        }
        
        $fieldsToCheck = ['reference_number', 'document_number', 'tax_number', 'phone', 'email'];
        
        if (in_array($property, $fieldsToCheck)) {
            $exists = Party::where($property, $value)
                ->when($this->party_id, fn($q) => $q->where('id', '!=', $this->party_id))
                ->exists();
                
            if ($exists) {
                $fieldNames = [
                    'reference_number' => 'الرقم المرجعي',
                    'document_number' => 'رقم الوثيقة/الهوية',
                    'tax_number' => 'الرقم الضريبي',
                    'phone' => 'رقم الهاتف',
                    'email' => 'البريد الإلكتروني'
                ];
                $this->duplicate_warnings[$property] = "تنبيه: " . $fieldNames[$property] . " هذا مسجل مسبقاً لطرف آخر.";
            } else {
                if (isset($this->duplicate_warnings[$property])) {
                    unset($this->duplicate_warnings[$property]);
                }
            }
        }
    }

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

        $data = [
            'code' => $this->code,
            'name' => $this->name,
            'short_name' => $this->short_name,
            'reference_number' => $this->reference_number,
            'document_number' => $this->document_number,
            'tax_number' => $this->tax_number,
            'phone' => $this->phone,
            'email' => $this->email,
            'address' => $this->address,
            'notes' => $this->notes,
            'is_active' => (bool) $this->is_active,
        ];

        if (!$this->party_id) {
            $data['created_by'] = auth()->id();
        }

        Party::updateOrCreate(['id' => $this->party_id], $data);

        session()->flash('message', $this->party_id ? 'تم تحديث بيانات الطرف بنجاح.' : 'تم إضافة الطرف الجديد بنجاح.');
        
        $this->closeModal();
    }

    public function render()
    {
        $query = Party::query();

        if ($this->search) {
            $query->where(function($q) {
                $q->where('name', 'like', '%'.$this->search.'%')
                  ->orWhere('code', 'like', '%'.$this->search.'%')
                  ->orWhere('tax_number', 'like', '%'.$this->search.'%')
                  ->orWhere('document_number', 'like', '%'.$this->search.'%')
                  ->orWhere('phone', 'like', '%'.$this->search.'%');
            });
        }

        if ($this->statusFilter === 'active') {
            $query->where('is_active', true);
        } elseif ($this->statusFilter === 'inactive') {
            $query->where('is_active', false);
        }

        $parties = $query->latest()->paginate(10);

        return view('livewire.parties', [
            'parties' => $parties
        ])->layout('layouts.app');
    }
}
