<?php

namespace App\Domain\POS\Services;

use App\Domain\Financial\Models\Payment;
use App\Domain\POS\Models\POSTransaction;
use App\Domain\POS\Models\ReceiptTemplate;

class ReceiptService
{
    /**
     * Build receipt data for a POS transaction.
     */
    public function buildPosReceiptData(POSTransaction $transaction, ?ReceiptTemplate $template = null): array
    {
        $transaction->load(['items', 'participant.person', 'branch', 'processedBy', 'splitPayments', 'invoice']);

        $template = $template ?? ReceiptTemplate::resolveFor($transaction->branch_id, 'pos');
        $fields = $template?->visible_fields ?? ReceiptTemplate::defaultPosFields();
        $settings = $template?->settings ?? ReceiptTemplate::defaultSettings();

        $data = [
            'template' => $template,
            'fields' => $fields,
            'settings' => $settings,
            'sections' => $template?->sections ?? ReceiptTemplate::defaultPosSections(),
        ];

        // Header
        if ($fields['header_academy_name'] ?? true) {
            $data['academy_name'] = app('current_academy')?->name_ar ?? '';
        }
        if ($fields['header_branch_name'] ?? true) {
            $data['branch_name'] = $transaction->branch?->name_ar ?? '';
        }
        if ($fields['header_branch_address'] ?? true) {
            $data['branch_address'] = $transaction->branch?->address ?? '';
        }
        if ($fields['header_branch_phone'] ?? true) {
            $data['branch_phone'] = $transaction->branch?->phone ?? '';
        }

        // Receipt info
        $data['receipt_number'] = $transaction->receipt_number;
        $data['date'] = $transaction->processed_at?->format($settings['date_format'] ?? 'Y/m/d') ?? '';
        $data['time'] = $transaction->processed_at?->format($settings['time_format'] ?? 'H:i') ?? '';

        if ($fields['cashier_name'] ?? true) {
            $data['cashier_name'] = $transaction->processedBy?->name_ar ?? $transaction->processedBy?->name ?? '';
        }

        // Customer
        if ($fields['participant_name'] ?? true) {
            $person = $transaction->participant?->person;
            $data['participant_name'] = $person ? ($person->name_ar ?? $person->full_name) : __('عميل بدون بيانات');
        }
        if ($fields['participant_code'] ?? false) {
            $data['participant_code'] = $transaction->participant?->code ?? '';
        }

        // Items
        $data['items'] = $transaction->items->map(fn ($item) => [
            'name' => $item->item_name_ar ?? $item->item_name,
            'quantity' => $item->quantity,
            'unit_price' => $item->unit_price,
            'discount' => $item->discount_amount,
            'total' => $item->line_total,
        ])->toArray();

        // Totals
        $data['subtotal'] = $transaction->subtotal;
        $data['discount_amount'] = $transaction->discount_amount;
        $data['tax_amount'] = $transaction->tax_amount;
        $data['service_fee_amount'] = $transaction->service_fee_amount;
        $data['total_amount'] = $transaction->total_amount;

        // Payment
        $data['payment_method'] = $transaction->payment_method?->value ?? '';
        $data['payment_method_label'] = $this->paymentMethodLabel($transaction->payment_method?->value);

        if (($fields['payment_split_details'] ?? true) && $transaction->splitPayments->isNotEmpty()) {
            $data['split_payments'] = $transaction->splitPayments->map(fn ($sp) => [
                'method' => $this->paymentMethodLabel($sp->method),
                'amount' => $sp->amount,
            ])->toArray();
        }

        if ($fields['coupon_code'] ?? false) {
            $data['coupon_code'] = $transaction->coupon_code;
        }

        if ($fields['invoice_number'] ?? false) {
            $data['invoice_number'] = $transaction->invoice?->number ?? '';
        }

        // Footer
        $data['footer_text'] = $settings['footer_text'] ?? '';
        $data['return_policy'] = $settings['return_policy'] ?? '';
        $data['currency'] = $settings['currency_symbol'] ?? 'ج.م';

        return $data;
    }

    /**
     * Build receipt data for a standalone payment.
     */
    public function buildPaymentReceiptData(Payment $payment, ?ReceiptTemplate $template = null): array
    {
        $payment->load(['invoice', 'processedBy']);

        $branchId = $payment->branch_id ?? $payment->invoice?->branch_id;
        $template = $template ?? ReceiptTemplate::resolveFor($branchId ?? 0, 'payment');
        $settings = $template?->settings ?? ReceiptTemplate::defaultSettings();

        return [
            'template' => $template,
            'settings' => $settings,
            'receipt_number' => $payment->reference ?? 'PAY-' . str_pad($payment->id, 6, '0', STR_PAD_LEFT),
            'date' => $payment->paid_at?->format($settings['date_format'] ?? 'Y/m/d') ?? '',
            'time' => $payment->paid_at?->format($settings['time_format'] ?? 'H:i') ?? '',
            'participant_name' => $payment->invoice?->contact_name ?? '',
            'invoice_number' => $payment->invoice?->number ?? '',
            'amount' => $payment->amount,
            'method' => $this->paymentMethodLabel($payment->method?->value ?? $payment->method ?? ''),
            'cashier_name' => $payment->processedBy?->name_ar ?? '',
            'currency' => $settings['currency_symbol'] ?? 'ج.م',
            'footer_text' => $settings['footer_text'] ?? '',
        ];
    }

    /**
     * Create the default receipt template for an academy (called during setup).
     */
    public function createDefaultTemplate(int $academyId, ?int $branchId = null): ReceiptTemplate
    {
        return ReceiptTemplate::create([
            'academy_id' => $academyId,
            'branch_id' => $branchId,
            'name' => 'Default POS Receipt',
            'name_ar' => 'إيصال نقطة البيع الافتراضي',
            'type' => 'pos',
            'sections' => ReceiptTemplate::defaultPosSections(),
            'visible_fields' => ReceiptTemplate::defaultPosFields(),
            'settings' => ReceiptTemplate::defaultSettings(),
            'is_default' => true,
            'is_active' => true,
        ]);
    }

    private function paymentMethodLabel(?string $method): string
    {
        return match ($method) {
            'cash' => 'نقدي',
            'card' => 'بطاقة',
            'bank_transfer' => 'تحويل بنكي',
            'wallet' => 'محفظة',
            'cheque' => 'شيك',
            'other' => 'أخرى',
            default => $method ?? '',
        };
    }
}
