<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CompanySetting;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class InvoiceTemplateController extends Controller
{
    /**
     * Available invoice templates
     */
    private function getInvoiceTemplates(): array
    {
        return [
            'modern' => [
                'name' => 'Modern Corporate',
                'description' => 'Clean corporate layout with professional design and blue accents',
                'preview' => 'invoice-template-1',
                'file' => 'invoice-template-1',
            ],
            'classic' => [
                'name' => 'Minimal Clean',
                'description' => 'Centered design with minimal borders and elegant typography',
                'preview' => 'invoice-template-2',
                'file' => 'invoice-template-2',
            ],
            'minimal' => [
                'name' => 'Business Professional',
                'description' => 'Boxed layout with colored header and professional corporate feel',
                'preview' => 'invoice-template-3',
                'file' => 'invoice-template-3',
            ],
            'bold' => [
                'name' => 'Premium Branding',
                'description' => 'Full-width header with brand color, suitable for enterprise businesses',
                'preview' => 'invoice-template-4',
                'file' => 'invoice-template-4',
            ],
        ];
    }

    /**
     * Available quotation templates
     */
    private function getQuotationTemplates(): array
    {
        return [
            'modern' => [
                'name' => 'Corporate Quote',
                'description' => 'Professional corporate quotation with valid until date and terms',
                'preview' => 'quotation-template-1',
                'file' => 'quotation-template-1',
            ],
            'classic' => [
                'name' => 'Sales Proposal',
                'description' => 'Sales-style quotation with proposal header and acceptance signature',
                'preview' => 'quotation-template-2',
                'file' => 'quotation-template-2',
            ],
            'minimal' => [
                'name' => 'Clean Estimate',
                'description' => 'Minimal style with quote summary and simple cost breakdown',
                'preview' => 'quotation-template-3',
                'file' => 'quotation-template-3',
            ],
            'bold' => [
                'name' => 'Premium Proposal',
                'description' => 'Elegant header with branding emphasis, suitable for large contracts',
                'preview' => 'quotation-template-4',
                'file' => 'quotation-template-4',
            ],
        ];
    }

    /**
     * Available receipt templates
     */
    private function getReceiptTemplates(): array
    {
        return [
            'modern' => [
                'name' => 'Standard Payment Receipt',
                'description' => 'Professional receipt with payment summary and thank you message',
                'preview' => 'receipt-template-1',
                'file' => 'receipt-template-1',
            ],
            'classic' => [
                'name' => 'POS Style Receipt',
                'description' => 'Narrow receipt style with monospace font, retail-style layout',
                'preview' => 'receipt-template-2',
                'file' => 'receipt-template-2',
            ],
            'minimal' => [
                'name' => 'Business Receipt',
                'description' => 'Professional boxed layout with payment breakdown and balance info',
                'preview' => 'receipt-template-3',
                'file' => 'receipt-template-3',
            ],
            'bold' => [
                'name' => 'Modern Branded Receipt',
                'description' => 'Color accent header with payment summary highlight and modern typography',
                'preview' => 'receipt-template-4',
                'file' => 'receipt-template-4',
            ],
        ];
    }

    /**
     * Get default template from database or config
     */
    private function getDefaultTemplate(string $type): string
    {
        return CompanySetting::getDocumentDefaultTemplateKey($type);
    }

    /**
     * Get template view path for rendering
     */
    public static function getTemplateView(string $type, string $templateKey): string
    {
        if ($type === 'invoice') {
            return \App\Support\InvoiceTemplateResolver::webView($templateKey);
        }

        if ($type === 'receipt') {
            return \App\Support\ReceiptTemplateResolver::webView($templateKey);
        }

        $templates = match ($type) {
            'quotation' => [
                'modern' => 'quotation-template-1',
                'classic' => 'quotation-template-2',
                'minimal' => 'quotation-template-3',
                'bold' => 'quotation-template-4',
            ],
            default => [],
        };

        $templateFile = $templates[$templateKey] ?? $templates['modern'] ?? 'quotation-template-1';

        return 'admin.invoice-templates.designs.'.$templateFile;
    }

    /**
     * Display a listing of document templates
     */
    public function index(): View
    {
        $invoiceTemplates = $this->getInvoiceTemplates();
        $quotationTemplates = $this->getQuotationTemplates();
        $receiptTemplates = $this->getReceiptTemplates();

        $defaultInvoiceTemplate = $this->getDefaultTemplate('invoice');
        $defaultQuotationTemplate = $this->getDefaultTemplate('quotation');
        $defaultReceiptTemplate = $this->getDefaultTemplate('receipt');

        return view('admin.invoice-templates.index', [
            'invoiceTemplates' => $invoiceTemplates,
            'quotationTemplates' => $quotationTemplates,
            'receiptTemplates' => $receiptTemplates,
            'defaultInvoiceTemplate' => $defaultInvoiceTemplate,
            'defaultQuotationTemplate' => $defaultQuotationTemplate,
            'defaultReceiptTemplate' => $defaultReceiptTemplate,
        ]);
    }

    /**
     * Set the default template for a document type
     */
    public function setDefault(Request $request): RedirectResponse|JsonResponse
    {
        $request->validate([
            'type' => 'required|string|in:invoice,quotation,receipt',
            'template' => 'required|string',
        ]);

        $type = $request->type;
        $template = $request->template;

        // Validate template exists
        $templates = match ($type) {
            'invoice' => $this->getInvoiceTemplates(),
            'quotation' => $this->getQuotationTemplates(),
            'receipt' => $this->getReceiptTemplates(),
            default => [],
        };

        if (! isset($templates[$template])) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid template selected.',
                ], 400);
            }

            return redirect()
                ->route('admin.invoice-templates.index')
                ->with('error', 'Invalid template selected.');
        }

        // Try to save to database first
        try {
            // Check if column exists, if not add it
            $columnName = $type.'_default_template';
            $tableName = 'company_settings';

            // Check if column exists
            $columns = DB::select("SHOW COLUMNS FROM {$tableName} LIKE '{$columnName}'");
            if (empty($columns)) {
                // Add column if it doesn't exist
                DB::statement("ALTER TABLE {$tableName} ADD COLUMN {$columnName} VARCHAR(255) NULL AFTER company_notes");
            }

            // Update the default template on the primary settings row (same row read by PDF / invoice view)
            $target = DB::table($tableName)->orderBy('id')->first();
            if ($target) {
                DB::table($tableName)
                    ->where('id', $target->id)
                    ->update([$columnName => $template]);
            }

        } catch (\Exception $e) {
            // If database update fails, fall back to config file
            $configPath = config_path('invoice.php');
            if (file_exists($configPath)) {
                $config = include $configPath;
                $configKey = $type.'_default_template';
                $config[$configKey] = $template;

                $content = "<?php\n\nreturn [\n";
                $content .= "    'number_prefix' => env('INVOICE_NUMBER_PREFIX', 'INV'),\n";
                $content .= "    'estimate_prefix' => env('ESTIMATE_NUMBER_PREFIX', 'EST'),\n";
                $content .= "    'payment_prefix' => env('PAYMENT_NUMBER_PREFIX', 'PAY'),\n";
                $content .= "    'default_currency' => env('INVOICE_DEFAULT_CURRENCY', 'USD'),\n";
                $content .= "    'default_payment_terms' => env('INVOICE_DEFAULT_PAYMENT_TERMS', 30),\n";
                $content .= "    'invoice_default_template' => '".addslashes($config['invoice_default_template'] ?? 'modern')."',\n";
                $content .= "    'quotation_default_template' => '".addslashes($config['quotation_default_template'] ?? 'modern')."',\n";
                $content .= "    'receipt_default_template' => '".addslashes($config['receipt_default_template'] ?? 'modern')."',\n";
                $content .= "];\n";

                file_put_contents($configPath, $content);
                Config::set("invoice.{$configKey}", $template);

                // Clear config cache
                \Illuminate\Support\Facades\Artisan::call('config:clear');
            }
        }

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => ucfirst($type).' default template updated successfully.',
            ]);
        }

        return redirect()
            ->route('admin.invoice-templates.index')
            ->with('success', ucfirst($type).' default template updated successfully.');
    }
}
