<?php

namespace App\Livewire\Settings;

use App\Domain\Identity\Models\Branch;
use App\Domain\POS\Models\ReceiptTemplate;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('إعدادات الإيصال')]
class ReceiptSettings extends Component
{
    public ?int $selectedBranchId = null;
    public array $visibleFields = [];
    public array $sections = [];
    public array $settings = [];
    public bool $saved = false;

    public function mount(): void
    {
        $this->authorize('settings.manage');

        $this->selectedBranchId = session('active_branch_id', auth()->user()->branch_id);

        $this->loadTemplate();
    }

    public function updatedSelectedBranchId(): void
    {
        $this->loadTemplate();
    }

    public function loadTemplate(): void
    {
        $template = $this->selectedBranchId
            ? ReceiptTemplate::resolveFor($this->selectedBranchId, 'pos')
            : null;

        $this->visibleFields = $template?->visible_fields ?? ReceiptTemplate::defaultPosFields();
        $this->sections = $template?->sections ?? ReceiptTemplate::defaultPosSections();
        $this->settings = $template?->settings ?? ReceiptTemplate::defaultSettings();
        $this->saved = false;
    }

    public function toggleField(string $key): void
    {
        $this->visibleFields[$key] = !($this->visibleFields[$key] ?? true);
        $this->saved = false;
    }

    public function toggleSection(int $index): void
    {
        if (isset($this->sections[$index])) {
            $this->sections[$index]['enabled'] = !$this->sections[$index]['enabled'];
            $this->saved = false;
        }
    }

    public function moveSectionUp(int $index): void
    {
        if ($index > 0) {
            $temp = $this->sections[$index - 1];
            $this->sections[$index - 1] = $this->sections[$index];
            $this->sections[$index] = $temp;
            $this->saved = false;
        }
    }

    public function moveSectionDown(int $index): void
    {
        if ($index < count($this->sections) - 1) {
            $temp = $this->sections[$index + 1];
            $this->sections[$index + 1] = $this->sections[$index];
            $this->sections[$index] = $temp;
            $this->saved = false;
        }
    }

    public function save(): void
    {
        if (!$this->selectedBranchId) {
            $this->addError('branch', __('يرجى اختيار الفرع'));
            return;
        }

        $academy = app('current_academy');
        if (!$academy) return;

        $template = ReceiptTemplate::where('academy_id', $academy->id)
            ->where('branch_id', $this->selectedBranchId)
            ->where('type', 'pos')
            ->where('is_default', true)
            ->first();

        if (!$template) {
            $template = ReceiptTemplate::create([
                'academy_id' => $academy->id,
                'branch_id' => $this->selectedBranchId,
                'name' => 'POS Receipt',
                'name_ar' => 'إيصال نقطة البيع',
                'type' => 'pos',
                'is_default' => true,
                'is_active' => true,
                'created_by' => auth()->id(),
                'sections' => $this->sections,
                'visible_fields' => $this->visibleFields,
                'settings' => $this->settings,
            ]);
        } else {
            $template->update([
                'sections' => $this->sections,
                'visible_fields' => $this->visibleFields,
                'settings' => $this->settings,
            ]);
        }

        $this->saved = true;
        session()->flash('success', __('تم حفظ إعدادات الإيصال'));
    }

    public function resetToDefaults(): void
    {
        $this->visibleFields = ReceiptTemplate::defaultPosFields();
        $this->sections = ReceiptTemplate::defaultPosSections();
        $this->settings = ReceiptTemplate::defaultSettings();
        $this->saved = false;
    }

    public function render()
    {
        $branches = Branch::where('is_active', true)->orderBy('name_ar')->get();

        $fieldLabels = [
            'header_logo' => 'شعار المنشأة',
            'header_academy_name' => 'اسم الأكاديمية',
            'header_branch_name' => 'اسم الفرع',
            'header_branch_address' => 'عنوان الفرع',
            'header_branch_phone' => 'هاتف الفرع',
            'header_tax_number' => 'الرقم الضريبي',
            'receipt_number' => 'رقم الإيصال',
            'receipt_date' => 'التاريخ',
            'receipt_time' => 'الوقت',
            'cashier_name' => 'اسم الكاشير',
            'participant_name' => 'اسم العميل',
            'participant_code' => 'كود المشترك',
            'items_table' => 'جدول الأصناف',
            'item_description' => 'وصف الصنف',
            'item_quantity' => 'الكمية',
            'item_unit_price' => 'سعر الوحدة',
            'item_discount' => 'خصم الصنف',
            'item_total' => 'إجمالي الصنف',
            'subtotal' => 'المجموع الفرعي',
            'discount_total' => 'إجمالي الخصم',
            'tax_amount' => 'الضريبة',
            'service_fee' => 'مصاريف خدمة',
            'grand_total' => 'الإجمالي النهائي',
            'payment_method' => 'طريقة الدفع',
            'payment_split_details' => 'تفاصيل الدفع المقسم',
            'coupon_code' => 'كود الكوبون',
            'invoice_number' => 'رقم الفاتورة',
            'footer_text' => 'نص التذييل',
            'footer_return_policy' => 'سياسة الإرجاع',
            'footer_thank_you' => 'رسالة الشكر',
            'qr_code' => 'كود QR',
            'barcode' => 'باركود',
        ];

        return view('livewire.settings.receipt-settings', [
            'branches' => $branches,
            'fieldLabels' => $fieldLabels,
        ]);
    }
}
