<?php

namespace App\Livewire\Settings;

use App\Domain\POS\Models\ReceiptTemplate;
use App\Domain\Shared\Traits\UsesBranchScope;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('إعدادات الإيصالات والفواتير')]
class ReceiptSettings extends Component
{
    use UsesBranchScope;

    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 = $this->defaultBranchId();
        $this->loadAll();
    }

    public function updatedSelectedBranchId(): void
    {
        // A plain public property is settable from the browser, and this one
        // decides whose receipts get rewritten — so the value is checked
        // against the branches this user may actually work in before anything
        // is loaded from it, not merely used as a filter.
        $this->selectedBranchId = $this->allowedBranchId($this->selectedBranchId);
        $this->loadAll();
    }

    /**
     * The branch this screen edits when the user has not chosen one.
     *
     * The topbar switcher owns the branch; in all-branches mode there is no
     * single branch to configure, so the first one the user may pick stands in
     * until they choose.
     */
    private function defaultBranchId(): ?int
    {
        $active = $this->getActiveBranchId();

        if ($active !== null) {
            return $active;
        }

        $first = $this->selectableBranches()->first();

        return $first ? (int) $first->id : null;
    }

    /**
     * Reduce a browser-supplied branch id to one this user may actually edit.
     */
    private function allowedBranchId(?int $branchId): ?int
    {
        if ($branchId === null) {
            return null;
        }

        return $this->selectableBranches()->contains('id', $branchId)
            ? $branchId
            : $this->defaultBranchId();
    }

    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
    {
        // Re-checked here and not only in the updated hook: this is the write,
        // and a request that never touches the picker still reaches it.
        $branchId = $this->allowedBranchId($this->selectedBranchId);

        if (!$branchId) {
            $this->addError('branch', __('يرجى اختيار الفرع'));
            return;
        }

        $this->selectedBranchId = $branchId;

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

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

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

    private function saveTemplate(int $branchId, 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', $branchId)
            ->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'  => $branchId,
                '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()
    {
        // One entry unless the user is genuinely in all-branches mode. The
        // topbar switcher is the branch selector; a second picker here listing
        // every branch is what let one branch's receipts be edited from
        // another branch's screen.
        $branches = $this->selectableBranches();

        $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,
        ]);
    }
}
