<?php

namespace App\Modules\Billing\Logo;

use App\Modules\Billing\BaseBillingModule;

class LogoModule extends BaseBillingModule
{
    public function getName(): string
    {
        return 'logo';
    }

    public function getDisplayName(): string
    {
        return 'Logo E-Fatura';
    }

    public function getType(): string
    {
        return 'e-invoice';
    }

    public function getDefaultSettings(): array
    {
        return [
            'api_url' => 'https://api.logo.com.tr',
            'api_key' => '',
            'firm_no' => '',
            'period_no' => '',
            'username' => '',
            'password' => '',
            'client_id' => '',
            'client_secret' => '',
            'access_token' => '',
            'refresh_token' => '',
            'token_expires_at' => null,
        ];
    }

    /**
     * Logo e-fatura OAuth access_token kullanır (statik api_key değil).
     * getDefaultSettings OAuth2 alanlarını (client_id/secret/access_token/
     * refresh_token) taşır; base'in api_key Bearer'ı buraya uymuyordu.
     */
    protected function authHeaders(): array
    {
        return ['Authorization' => 'Bearer '.($this->settings['access_token'] ?? '')];
    }

    public function test(): array
    {
        try {
            // Logo API testi
            $response = $this->get('test');

            return [
                'success' => true,
                'message' => __('admin/modules.logo_connection_success'),
                'data' => $response,
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => __('admin/modules.logo_connection_error', ['error' => $e->getMessage()]),
            ];
        }
    }

    public function createEInvoice(array $invoiceData): array
    {
        try {
            // Logo formatında veri hazırla
            $logoData = $this->prepareLogoInvoiceData($invoiceData);

            // E-Fatura oluştur
            $response = $this->post('invoices', $logoData);

            $externalId = $response['id'] ?? $response['data']['id'] ?? null;
            if ($externalId === null) {
                return [
                    'success' => false,
                    'message' => __('admin/modules.logo_invoice_create_error', ['error' => 'missing id']),
                    'data' => $response,
                ];
            }

            return [
                'success' => true,
                'external_id' => $externalId,
                'data' => $response,
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => __('admin/modules.logo_invoice_create_error', ['error' => $e->getMessage()]),
            ];
        }
    }

    public function createEArchive(array $invoiceData): array
    {
        try {
            // Logo E-Arşiv formatında veri hazırla
            $logoData = $this->prepareLogoArchiveData($invoiceData);

            // E-Arşiv Fatura oluştur
            $response = $this->post('archive_invoices', $logoData);

            $externalId = $response['id'] ?? $response['data']['id'] ?? null;
            if ($externalId === null) {
                return [
                    'success' => false,
                    'message' => __('admin/modules.logo_archive_create_error', ['error' => 'missing id']),
                    'data' => $response,
                ];
            }

            return [
                'success' => true,
                'external_id' => $externalId,
                'data' => $response,
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => __('admin/modules.logo_archive_create_error', ['error' => $e->getMessage()]),
            ];
        }
    }

    public function cancelInvoice(string $externalId): array
    {
        try {
            // Logo'da fatura iptal et
            $response = $this->post("invoices/{$externalId}/cancel");

            return [
                'success' => true,
                'message' => __('admin/modules.logo_invoice_cancelled_success'),
                'data' => $response,
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => __('admin/modules.logo_invoice_cancel_error', ['error' => $e->getMessage()]),
            ];
        }
    }

    public function refundInvoice(string $externalId, array $refundData): array
    {
        try {
            // Logo'da iade faturası oluştur
            $refundInvoiceData = $this->prepareRefundData($externalId, $refundData);

            $response = $this->post('refund_invoices', $refundInvoiceData);

            $externalId = $response['id'] ?? $response['data']['id'] ?? null;
            if ($externalId === null) {
                return [
                    'success' => false,
                    'message' => __('admin/modules.logo_refund_create_error', ['error' => 'missing id']),
                    'data' => $response,
                ];
            }

            return [
                'success' => true,
                'external_id' => $externalId,
                'message' => __('admin/modules.logo_refund_created_success'),
                'data' => $response,
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => __('admin/modules.logo_refund_create_error', ['error' => $e->getMessage()]),
            ];
        }
    }

    public function getInvoice(string $externalId): array
    {
        try {
            $response = $this->get("invoices/{$externalId}");

            return [
                'success' => true,
                'data' => $response,
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Fatura getirilemedi: '.$e->getMessage(),
            ];
        }
    }

    /**
     * Logo formatında fatura verisi hazırla
     */
    protected function prepareLogoInvoiceData(array $invoiceData): array
    {
        $mappedData = $this->applyFieldMapping($invoiceData);

        return [
            'firm_no' => $this->settings['firm_no'],
            'period_no' => $this->settings['period_no'],
            'invoice_no' => $mappedData['invoice_number'] ?? '',
            'invoice_date' => $mappedData['invoice_date'] ?? now()->format('Y-m-d'),
            'due_date' => $mappedData['due_date'] ?? now()->addDays(30)->format('Y-m-d'),
            'currency' => $mappedData['currency'] ?? 'TRY',
            'exchange_rate' => $mappedData['exchange_rate'] ?? 1,
            'client_code' => $mappedData['client_code'] ?? '',
            'client_name' => $mappedData['client_name'] ?? '',
            'client_tax_number' => $mappedData['client_tax_number'] ?? '',
            'client_address' => $mappedData['client_address'] ?? '',
            'client_city' => $mappedData['client_city'] ?? '',
            'client_country' => $mappedData['client_country'] ?? 'TR',
            'description' => $mappedData['description'] ?? 'E-Fatura',
            'items' => $this->prepareLogoInvoiceItems($mappedData),
            'total_amount' => $mappedData['total_amount'] ?? 0,
            'vat_amount' => $mappedData['vat_amount'] ?? 0,
            'discount_amount' => $mappedData['discount_amount'] ?? 0,
            'net_amount' => $mappedData['net_amount'] ?? 0,
        ];
    }

    /**
     * Logo formatında E-Arşiv verisi hazırla
     */
    protected function prepareLogoArchiveData(array $invoiceData): array
    {
        $data = $this->prepareLogoInvoiceData($invoiceData);
        $data['invoice_type'] = 'archive';

        return $data;
    }

    /**
     * İade verisi hazırla
     */
    protected function prepareRefundData(string $originalInvoiceId, array $refundData): array
    {
        $data = $this->prepareLogoInvoiceData($refundData);
        $data['invoice_type'] = 'refund';
        $data['original_invoice_id'] = $originalInvoiceId;

        return $data;
    }

    /**
     * Logo fatura kalemlerini hazırla
     */
    protected function prepareLogoInvoiceItems(array $mappedData): array
    {
        $items = [];

        if (isset($mappedData['items']) && is_array($mappedData['items'])) {
            foreach ($mappedData['items'] as $item) {
                $items[] = [
                    'item_code' => $item['item_code'] ?? '',
                    'item_name' => $item['name'] ?? '',
                    'description' => $item['description'] ?? '',
                    'quantity' => $item['quantity'] ?? 1,
                    'unit' => $item['unit'] ?? 'piece',
                    'unit_price' => $item['unit_price'] ?? 0,
                    'vat_rate' => $item['vat_rate'] ?? 0,
                    'discount_rate' => $item['discount_rate'] ?? 0,
                    'discount_amount' => $item['discount_amount'] ?? 0,
                    'net_amount' => $item['net_amount'] ?? 0,
                    'vat_amount' => $item['vat_amount'] ?? 0,
                    'total_amount' => $item['total_amount'] ?? 0,
                ];
            }
        }

        return $items;
    }

    /**
     * Logo'ya özel alan eşleştirmeleri
     */
    protected function getDefaultFieldMappings(): array
    {
        return array_merge(parent::getDefaultFieldMappings(), [
            'client_code' => 'client.code',
            'client_city' => 'client.city',
            'client_country' => 'client.country',
            'description' => 'description',
            'due_date' => 'due_date',
            'currency' => 'currency',
            'exchange_rate' => 'exchange_rate',
            'vat_amount' => 'vat_amount',
            'discount_amount' => 'discount_amount',
            'net_amount' => 'net_amount',
            'items' => 'items',
        ]);
    }
}
