<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\DB;
use App\Core\Request;
use App\Core\Response;
use App\Services\PrintSettingsService;
use InvalidArgumentException;
use Throwable;

final class PrintSettingsController
{
    private const GENERAL_PAGE = 'general';

    private const DOCUMENT_PAGES = [
        'quotation' => ['label' => 'عرض السعر', 'route' => '/admin/print-settings/quotation'],
        'sales_invoice' => ['label' => 'فاتورة البيع', 'route' => '/admin/print-settings/sales-invoice'],
        'purchase_invoice' => ['label' => 'فاتورة الشراء', 'route' => '/admin/print-settings/purchase-invoice'],
        'sales_return' => ['label' => 'مرتجع البيع', 'route' => '/admin/print-settings/sales-return'],
        'purchase_return' => ['label' => 'مرتجع الشراء', 'route' => '/admin/print-settings/purchase-return'],
        'customer_receipt' => ['label' => 'سند القبض', 'route' => '/admin/print-settings/customer-receipt'],
        'cash_payment' => ['label' => 'سند الصرف', 'route' => '/admin/print-settings/cash-payment'],
        'supplier_payment' => ['label' => 'سند سداد المورد', 'route' => '/admin/print-settings/supplier-payment'],
        'party_statement' => ['label' => 'كشف الحساب', 'route' => '/admin/print-settings/party-statement'],
    ];

    public function index(): void
    {
        Auth::requireLogin();
        require_permission('admin.print_settings.edit');

        $service = new PrintSettingsService(DB::pdo());
        $settings = $service->settings();

        Response::view('pages/admin/print_settings_index', [
            'page_title' => 'موديول الطباعة',
            'breadcrumbs' => $this->breadcrumbs('موديول الطباعة'),
            'nav_items' => $this->navItems(),
            'documents' => $settings['documents'],
            'general_route' => $this->routeForPage(self::GENERAL_PAGE),
        ]);
    }

    public function general(): void
    {
        Auth::requireLogin();
        require_permission('admin.print_settings.edit');

        $service = new PrintSettingsService(DB::pdo());
        $settings = $service->settings();
        $errors = [];

        if (Request::isPost()) {
            try {
                Csrf::verify();
                $service->saveGeneral(Request::all());
                Response::flash('success', 'تم حفظ الإعدادات العامة للطباعة.');
                Response::redirect($this->routeForPage(self::GENERAL_PAGE));
                return;
            } catch (Throwable $e) {
                $errors[] = $e->getMessage();
                $posted = Request::all();
                $settings['pos_default_print_format'] = (string)($posted['pos_default_print_format'] ?? $settings['pos_default_print_format']);
                $settings['barcode_label_width_mm'] = (string)($posted['barcode_label_width_mm'] ?? $settings['barcode_label_width_mm']);
                $settings['barcode_label_height_mm'] = (string)($posted['barcode_label_height_mm'] ?? $settings['barcode_label_height_mm']);
                $settings['barcode_show_price'] = !empty($posted['barcode_show_price']) ? '1' : '0';
                $settings['barcode_show_item_name'] = !empty($posted['barcode_show_item_name']) ? '1' : '0';
            }
        }

        Response::view('pages/admin/print_settings_general', [
            'page_title' => 'الإعدادات العامة للطباعة',
            'breadcrumbs' => $this->breadcrumbs('الإعدادات العامة للطباعة'),
            'nav_items' => $this->navItems(),
            'active_page' => self::GENERAL_PAGE,
            'settings' => $settings,
            'errors' => $errors,
        ]);
    }

    public function document(string $documentKey): void
    {
        Auth::requireLogin();
        require_permission('admin.print_settings.edit');

        $pageMeta = self::DOCUMENT_PAGES[$documentKey] ?? null;
        if ($pageMeta === null) {
            throw new InvalidArgumentException('صفحة إعدادات الطباعة غير موجودة.');
        }

        $service = new PrintSettingsService(DB::pdo());
        $document = $service->documentSettings($documentKey);
        $errors = [];

        if (Request::isPost()) {
            try {
                Csrf::verify();
                $service->saveDocument($documentKey, Request::all());
                Response::flash('success', 'تم حفظ إعدادات ' . $pageMeta['label'] . '.');
                Response::redirect($pageMeta['route']);
                return;
            } catch (Throwable $e) {
                $errors[] = $e->getMessage();
                $document = $this->mergePostedDocument($document, Request::all());
            }
        }

        Response::view('pages/admin/print_settings_document', [
            'page_title' => 'إعدادات طباعة ' . $pageMeta['label'],
            'breadcrumbs' => $this->breadcrumbs($pageMeta['label']),
            'nav_items' => $this->navItems(),
            'active_page' => $documentKey,
            'document' => $document,
            'errors' => $errors,
            'save_route' => $pageMeta['route'],
        ]);
    }

    public static function navItems(): array
    {
        $items = [
            self::GENERAL_PAGE => ['label' => 'الإعدادات العامة', 'route' => '/admin/print-settings/general', 'icon' => 'fa-sliders'],
        ];

        foreach (self::DOCUMENT_PAGES as $key => $meta) {
            $items[$key] = [
                'label' => $meta['label'],
                'route' => $meta['route'],
                'icon' => match ($key) {
                    'quotation' => 'fa-file-signature',
                    'sales_invoice', 'purchase_invoice' => 'fa-file-invoice-dollar',
                    'sales_return', 'purchase_return' => 'fa-rotate-left',
                    'customer_receipt', 'cash_payment', 'supplier_payment' => 'fa-money-bill-wave',
                    'party_statement' => 'fa-file-lines',
                    default => 'fa-print',
                },
            ];
        }

        return $items;
    }

    private function breadcrumbs(string $lastLabel): array
    {
        return [
            ['label' => 'لوحة التحكم', 'url' => '/admin/dashboard'],
            ['label' => 'إدارة الطباعة', 'url' => '/admin/print-settings'],
            ['label' => $lastLabel],
        ];
    }

    private function routeForPage(string $page): string
    {
        return $page === self::GENERAL_PAGE
            ? '/admin/print-settings/general'
            : (self::DOCUMENT_PAGES[$page]['route'] ?? '/admin/print-settings');
    }

    private function mergePostedDocument(array $document, array $posted): array
    {
        $src = is_array($posted['document'] ?? null) ? $posted['document'] : [];
        $document['default_format'] = (string)($src['default_format'] ?? $document['default_format']);
        $document['show_logo'] = !empty($src['show_logo']);
        $document['show_signatures'] = !empty($src['show_signatures']);
        $document['show_terms'] = !empty($src['show_terms']);
        $document['show_tax_no'] = !empty($src['show_tax_no']);
        $document['footer_note'] = (string)($src['footer_note'] ?? $document['footer_note']);
        $document['active_template'] = (string)($src['active_template'] ?? ($document['active_template'] ?? 'standard'));
        if (is_array($src['templates'] ?? null)) {
            $document['templates'] = $src['templates'];
        }
        return $document;
    }
}
