<?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 string $activeTab = 'pos';
    public ?int $selectedBranchId = null;
    public bool $saved = false;

    // POS Receipt
    public array $posFields = [];
    public array $posSections = [];
    public array $posSettings = [];

    // Invoice
    public array $invoiceFields = [];
    public array $invoiceSettings = [];

    // Payment Receipt
    public array $paymentFields = [];
    public array $paymentSettings = [];

    public function mount(): void
    {
        $this->authorize('settings.manage');
        $this->selectedBranchId = session('active_branch_id', auth()->user()->branch_id);
        $this->loadAll();
    }

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

    public function updatedActiveTab(): void
    {
        $this->saved = false;
    }

    private function loadAll(): void
    {
        $this->loadPos();
        $this->loadInvoice();
        $this->loadPayment();
        $this->saved = false;
    }

    private function loadPos(): void
    {
        $tpl = $this->selectedBranchId
            ? ReceiptTemplate::resolveFor($this->selectedBranchId, 'pos')
            : null;
        $this->posFields   = $tpl?->visible_fields ?? ReceiptTemplate::defaultPosFields();
        $this->posSections = $tpl?->sections       ?? ReceiptTemplate::defaultPosSections();
        $this->posSettings = $tpl?->settings        ?? ReceiptTemplate::defaultSettings();
    }

    private function loadInvoice(): void
    {
        $tpl = $this->selectedBranchId
            ? ReceiptTemplate::resolveFor($this->selectedBranchId, 'invoice')
            : null;
        $this->invoiceFields   = $tpl?->visible_fields ?? ReceiptTemplate::defaultInvoiceFields();
        $this->invoiceSettings = $tpl?->settings        ?? ReceiptTemplate::defaultInvoiceSettings();
    }

    private function loadPayment(): void
    {
        $tpl = $this->selectedBranchId
            ? ReceiptTemplate::resolveFor($this->selectedBranchId, 'payment')
            : null;
        $this->paymentFields   = $tpl?->visible_fields ?? ReceiptTemplate::defaultPaymentFields();
        $this->paymentSettings = $tpl?->settings        ?? ReceiptTemplate::defaultPaymentSettings();
    }

    public function toggleField(string $key): void
    {
        match ($this->activeTab) {
            'pos'     => $this->posFields[$key]     = !($this->posFields[$key] ?? true),
            'invoice' => $this->invoiceFields[$key] = !($this->invoiceFields[$key] ?? true),
            'payment' => $this->paymentFields[$key] = !($this->paymentFields[$key] ?? true),
        };
        $this->saved = false;
    }

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

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

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

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

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

        match ($this->activeTab) {
            'pos'     => $this->saveTemplate('pos',     $this->posFields,     $this->posSettings,     $this->posSections),
            'invoice' => $this->saveTemplate('invoice', $this->invoiceFields, $this->invoiceSettings),
            'payment' => $this->saveTemplate('payment', $this->paymentFields, $this->paymentSettings),
        };

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

    private function saveTemplate(string $type, array $fields, array $settings, array $sections = []): void
    {
        $academy = app('current_academy');
        $data = [
            'visible_fields' => $fields,
            'settings'       => $settings,
        ];
        if ($sections) {
            $data['sections'] = $sections;
        }

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

        if (!$tpl) {
            $names = ['pos' => ['POS Receipt', 'إيصال الكاشير'], 'invoice' => ['Invoice', 'الفاتورة'], 'payment' => ['Payment Receipt', 'إيصال الدفع']];
            ReceiptTemplate::create(array_merge($data, [
                'academy_id' => $academy->id,
                'branch_id'  => $this->selectedBranchId,
                'name'       => $names[$type][0],
                'name_ar'    => $names[$type][1],
                'type'       => $type,
                'is_default' => true,
                'is_active'  => true,
                'created_by' => auth()->id(),
            ]));
        } else {
            $tpl->update($data);
        }
    }

    public function resetToDefaults(): void
    {
        match ($this->activeTab) {
            'pos' => [
                $this->posFields   = ReceiptTemplate::defaultPosFields(),
                $this->posSections = ReceiptTemplate::defaultPosSections(),
                $this->posSettings = ReceiptTemplate::defaultSettings(),
            ],
            'invoice' => [
                $this->invoiceFields   = ReceiptTemplate::defaultInvoiceFields(),
                $this->invoiceSettings = ReceiptTemplate::defaultInvoiceSettings(),
            ],
            'payment' => [
                $this->paymentFields   = ReceiptTemplate::defaultPaymentFields(),
                $this->paymentSettings = ReceiptTemplate::defaultPaymentSettings(),
            ],
        };
        $this->saved = false;
    }

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

        $posFieldLabels = [
            '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'                => 'باركود',
        ];

        $invoiceFieldLabels = [
            'header_logo'        => 'شعار المنشأة',
            'header_academy_name'=> 'اسم الأكاديمية',
            'header_branch'      => 'معلومات الفرع',
            'header_tax_number'  => 'الرقم الضريبي',
            'client_details'     => 'بيانات العميل',
            'items_table'        => 'جدول البنود',
            'subtotal'           => 'المجموع الفرعي',
            'discount'           => 'الخصم',
            'tax_amount'         => 'الضريبة',
            'service_fee'        => 'رسوم الخدمة',
            'paid_amount'        => 'المبلغ المدفوع / المتبقي',
            'payments_history'   => 'جدول المدفوعات',
            'signature'          => 'التوقيع',
            'terms_conditions'   => 'الشروط والأحكام',
            'footer_text'        => 'نص التذييل',
        ];

        $paymentFieldLabels = [
            'header_logo'      => 'شعار المنشأة',
            'header_academy_name' => 'اسم الأكاديمية',
            'reference_number' => 'رقم المرجع',
            'date'             => 'التاريخ',
            'payment_method'   => 'طريقة الدفع',
            'invoice_number'   => 'رقم الفاتورة',
            'payer_name'       => 'اسم الدافع',
            'received_by'      => 'استلم بواسطة',
            'status_badge'     => 'حالة الدفع',
            'notes'            => 'الملاحظات',
            'footer_text'      => 'نص التذييل',
        ];

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