<?php

namespace App\Domain\POS\Models;

use App\Domain\Identity\Models\Branch;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ReceiptTemplate extends Model
{
    use BelongsToAcademy;

    protected $fillable = [
        'academy_id',
        'branch_id',
        'name',
        'name_ar',
        'type',
        'sections',
        'visible_fields',
        'settings',
        'is_default',
        'is_active',
        'created_by',
    ];

    protected function casts(): array
    {
        return [
            'sections' => 'array',
            'visible_fields' => 'array',
            'settings' => 'array',
            'is_default' => 'boolean',
            'is_active' => 'boolean',
        ];
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class);
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function scopeForBranch($query, int $branchId)
    {
        return $query->where(function ($q) use ($branchId) {
            $q->where('branch_id', $branchId)
              ->orWhereNull('branch_id');
        });
    }

    public function scopeOfType($query, string $type)
    {
        return $query->where('type', $type);
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Get the effective template for a branch + type.
     * Branch-specific first, then academy-wide default.
     */
    public static function resolveFor(int $branchId, string $type = 'pos'): ?self
    {
        // Branch-specific default
        $template = static::where('branch_id', $branchId)
            ->where('type', $type)
            ->where('is_active', true)
            ->where('is_default', true)
            ->first();

        if ($template) return $template;

        // Academy-wide default (branch_id = null)
        return static::whereNull('branch_id')
            ->where('type', $type)
            ->where('is_active', true)
            ->where('is_default', true)
            ->first();
    }

    /**
     * Default field configuration for a new POS receipt template.
     */
    public static function defaultPosFields(): array
    {
        return [
            'header_logo' => true,
            'header_academy_name' => true,
            'header_branch_name' => true,
            'header_branch_address' => true,
            'header_branch_phone' => true,
            'header_tax_number' => false,
            'receipt_number' => true,
            'receipt_date' => true,
            'receipt_time' => true,
            'cashier_name' => true,
            'participant_name' => true,
            'participant_code' => false,
            'items_table' => true,
            'item_description' => true,
            'item_quantity' => true,
            'item_unit_price' => true,
            'item_discount' => true,
            'item_total' => true,
            'subtotal' => true,
            'discount_total' => true,
            'tax_amount' => true,
            'service_fee' => true,
            'grand_total' => true,
            'payment_method' => true,
            'payment_split_details' => true,
            'coupon_code' => false,
            'invoice_number' => false,
            'footer_text' => true,
            'footer_return_policy' => true,
            'footer_thank_you' => true,
            'qr_code' => false,
            'barcode' => false,
        ];
    }

    /**
     * Default section order for POS receipt.
     */
    public static function defaultPosSections(): array
    {
        return [
            ['key' => 'header', 'label' => 'الترويسة', 'enabled' => true],
            ['key' => 'receipt_info', 'label' => 'معلومات الإيصال', 'enabled' => true],
            ['key' => 'customer_info', 'label' => 'معلومات العميل', 'enabled' => true],
            ['key' => 'items', 'label' => 'المنتجات/الخدمات', 'enabled' => true],
            ['key' => 'totals', 'label' => 'الإجماليات', 'enabled' => true],
            ['key' => 'payment', 'label' => 'طريقة الدفع', 'enabled' => true],
            ['key' => 'footer', 'label' => 'التذييل', 'enabled' => true],
        ];
    }

    /**
     * Default settings for receipt appearance.
     */
    public static function defaultSettings(): array
    {
        return [
            'paper_width' => '80mm',
            'font_size' => 'normal',
            'show_borders' => true,
            'logo_height' => '40px',
            'footer_text' => 'شكراً لزيارتكم',
            'return_policy' => 'لا يمكن استرجاع المبلغ بعد 7 أيام',
            'currency_symbol' => 'ج.م',
            'date_format' => 'Y/m/d',
            'time_format' => 'H:i',
        ];
    }

    public static function defaultInvoiceFields(): array
    {
        return [
            'header_logo' => true,
            'header_academy_name' => true,
            'header_branch' => true,
            'header_tax_number' => false,
            'client_details' => true,
            'items_table' => true,
            'subtotal' => true,
            'discount' => true,
            'tax_amount' => true,
            'service_fee' => true,
            'paid_amount' => true,
            'payments_history' => true,
            'signature' => false,
            'terms_conditions' => false,
            'footer_text' => true,
        ];
    }

    public static function defaultInvoiceSettings(): array
    {
        return [
            'footer_text' => '',
            'currency_symbol' => 'ج.م',
        ];
    }

    public static function defaultPaymentFields(): array
    {
        return [
            'header_logo' => true,
            'header_academy_name' => true,
            'reference_number' => true,
            'date' => true,
            'payment_method' => true,
            'invoice_number' => true,
            'payer_name' => true,
            'received_by' => true,
            'status_badge' => true,
            'notes' => true,
            'footer_text' => true,
        ];
    }

    public static function defaultPaymentSettings(): array
    {
        return [
            'footer_text' => 'تم إنشاء هذا المستند إلكترونياً ولا يحتاج إلى توقيع',
            'currency_symbol' => 'ج.م',
        ];
    }
}
