<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiBaseController;
use PDF;

class PdfController extends ApiBaseController
{
    /**
     * Available PDF templates with their sample data generators
     *
     * @var array
     */
    protected $templates = [
        'default' => [
            'name' => 'Default Sample',
            'view' => 'pdf.sample',
            'filename' => 'sample-pdf-settings.pdf',
        ],
        'invoice' => [
            'name' => 'Invoice - Classic',
            'view' => 'pdf.samples.invoice',
            'filename' => 'sample-invoice.pdf',
        ],
        'invoice-modern' => [
            'name' => 'Invoice - Modern',
            'view' => 'pdf.samples.invoice-modern',
            'filename' => 'sample-invoice-modern.pdf',
        ],
        'invoice-minimal' => [
            'name' => 'Invoice - Minimal',
            'view' => 'pdf.samples.invoice-minimal',
            'filename' => 'sample-invoice-minimal.pdf',
        ],
        'quotation' => [
            'name' => 'Quotation',
            'view' => 'pdf.samples.quotation',
            'filename' => 'sample-quotation.pdf',
        ],
        'receipt' => [
            'name' => 'Receipt',
            'view' => 'pdf.samples.receipt',
            'filename' => 'sample-receipt.pdf',
        ],
        'delivery-note' => [
            'name' => 'Delivery Note',
            'view' => 'pdf.samples.delivery-note',
            'filename' => 'sample-delivery-note.pdf',
        ],
        'purchase-order' => [
            'name' => 'Purchase Order',
            'view' => 'pdf.samples.purchase-order',
            'filename' => 'sample-purchase-order.pdf',
        ],
        'report' => [
            'name' => 'Business Report',
            'view' => 'pdf.samples.report',
            'filename' => 'sample-report.pdf',
        ],
    ];

    /**
     * Set PDF configuration based on company settings
     *
     * @param bool $withHeaderFooter
     * @return void
     */
    public function setPdfConfig($withHeaderFooter = true)
    {
        $company = company();
        $marginLeft = $withHeaderFooter ? 0 : ($company->pdf_left_space ?? 15);
        $marginRight = $withHeaderFooter ? 0 : ($company->pdf_right_space ?? 15);
        $marginTop = $withHeaderFooter ? ($company->pdf_top_space ?? 40) : ($company->pdf_top_space ?? 40);
        $marginBottom = $withHeaderFooter ? ($company->pdf_bottom_space ?? 20) : ($company->pdf_bottom_space ?? 20);
        $allFonts = [];

        if ($company->use_custom_font && $company->pdfFont && $company->pdfFont->id) {
            // Database stores 0 or 1, convert to mPDF expected values:
            // useOTL: 0 = disabled, 0x80 (128) = Indic scripts like Devanagari
            // useKashida: 0 = disabled, 75 = enabled (percentage for Arabic text justification)
            $useOtlValue = $company->pdfFont->use_otl ? 0x80 : 0;
            $useKashidaValue = $company->pdfFont->user_kashida ? 75 : 0;

            $allFonts[$company->pdfFont->short_name] = [
                'R'  => $company->pdfFont->file,
                'B'  => $company->pdfFont->file,
                'I'  => $company->pdfFont->file,
                'BI' => $company->pdfFont->file,
                'useOTL' => $useOtlValue,
                'useKashida' => $useKashidaValue,
            ];
        }

        config([
            'pdf.margin_left' => (int)$marginLeft,
            'pdf.margin_right' => (int)$marginRight,
            'pdf.margin_top' => (int)$marginTop,
            'pdf.margin_bottom' => (int)$marginBottom,
            'pdf.margin_header'  => (int)0,
            'pdf.margin_footer'  => (int)0,
            'pdf.auto_language_detection'  => $company->use_custom_font && $company->pdfFont && $company->pdfFont->id ? false : true,
            'pdf.custom_font_data' => $allFonts
        ]);
    }

    /**
     * Get PDF margins from company settings
     *
     * @return array
     */
    public function getMargins()
    {
        $company = company();

        return [
            'left' => ($company->pdf_left_space ?? 15) . 'mm',
            'right' => ($company->pdf_right_space ?? 15) . 'mm',
            'top' => ($company->pdf_top_space ?? 40) . 'mm',
            'bottom' => ($company->pdf_bottom_space ?? 20) . 'mm',
        ];
    }

    /**
     * Get list of available PDF templates
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getTemplates()
    {
        $templates = [];
        foreach ($this->templates as $key => $template) {
            $templates[] = [
                'key' => $key,
                'name' => $template['name'],
            ];
        }

        return response()->json([
            'success' => true,
            'data' => $templates,
        ]);
    }

    /**
     * Generate a sample PDF for preview
     *
     * @return \Illuminate\Http\Response
     */
    public function generateSamplePdf()
    {
        $request = request();
        $company = company();
        $templateKey = $request->template ?? 'invoice';
        $title = $request->title ?? 'PDF Font Settings Sample Document';
        $showHeaderFooter = $request->has('show_header_footer') && $request->show_header_footer == 'yes' ? true : false;

        // Validate template exists
        if (!isset($this->templates[$templateKey])) {
            $templateKey = 'default';
        }

        $template = $this->templates[$templateKey];
        $margins = $this->getMargins();

        $pdfData = [
            'title' => $title,
            'company' => $company,
            'showHeaderFooter' => $showHeaderFooter,
            'margins' => $margins,
            'sampleData' => $this->getSampleData($templateKey),
            'logoUrl' => $company->dark_logo_url,
        ];

        $this->setPdfConfig($showHeaderFooter);

        try {
            $pdf = PDF::loadView($template['view'], $pdfData);
            return $pdf->stream($template['filename']);
        } catch (\Mpdf\Exception\FontException | \ErrorException | \Exception $e) {
            // Problem in loading font... so use mpdf default font
            config([
                'pdf.auto_language_detection' => true,
                'pdf.custom_font_data' => [],
            ]);

            // Update company object to not use custom font for this render
            $pdfData['company']->use_custom_font = false;

            $pdf = PDF::loadView($template['view'], $pdfData);
            return $pdf->stream($template['filename']);
        }
    }

    /**
     * Generate sample data for each template type
     *
     * @param string $templateKey
     * @return array
     */
    protected function getSampleData($templateKey)
    {
        switch ($templateKey) {
            case 'invoice':
            case 'invoice-modern':
            case 'invoice-minimal':
                return $this->getInvoiceSampleData();
            case 'quotation':
                return $this->getQuotationSampleData();
            case 'receipt':
                return $this->getReceiptSampleData();
            case 'delivery-note':
                return $this->getDeliveryNoteSampleData();
            case 'purchase-order':
                return $this->getPurchaseOrderSampleData();
            case 'report':
                return $this->getReportSampleData();
            default:
                return [];
        }
    }

    /**
     * Sample data for Invoice template
     *
     * @return array
     */
    protected function getInvoiceSampleData()
    {
        $items = [
            ['name' => 'Web Development Services', 'quantity' => 1, 'price' => 2500.00],
            ['name' => 'UI/UX Design Package', 'quantity' => 1, 'price' => 1200.00],
        ];

        $subtotal = array_reduce($items, function ($carry, $item) {
            return $carry + ($item['quantity'] * $item['price']);
        }, 0);

        $tax = $subtotal * 0.10;
        $discount = 150.00;

        return [
            'invoice_number' => 'INV-' . now()->format('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT),
            'invoice_date' => now()->format('M d, Y'),
            'due_date' => now()->addDays(30)->format('M d, Y'),
            'customer' => [
                'name' => 'John Smith',
                'email' => 'john.smith@example.com',
                'phone' => '+1 (555) 123-4567',
                'address' => '123 Business Ave, New York, NY 10001',
            ],
            'items' => $items,
            'subtotal' => $subtotal,
            'tax' => $tax,
            'discount' => $discount,
            'total' => $subtotal + $tax - $discount,
        ];
    }

    /**
     * Sample data for Quotation template
     *
     * @return array
     */
    protected function getQuotationSampleData()
    {
        $services = [
            ['name' => 'Mobile App Development', 'description' => 'Native iOS and Android app', 'quantity' => 1, 'rate' => 12000.00],
            ['name' => 'Backend API Development', 'description' => 'RESTful API with auth', 'quantity' => 1, 'rate' => 5000.00],
        ];

        $subtotal = array_reduce($services, function ($carry, $service) {
            return $carry + ($service['quantity'] * $service['rate']);
        }, 0);

        $discountPercent = 10;
        $discount = $subtotal * ($discountPercent / 100);
        $taxPercent = 8;
        $tax = ($subtotal - $discount) * ($taxPercent / 100);

        return [
            'quotation_number' => now()->format('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT),
            'date' => now()->format('M d, Y'),
            'valid_until' => now()->addDays(30)->format('M d, Y'),
            'project_name' => 'E-Commerce Mobile App',
            'prepared_by' => 'Sales Team',
            'customer' => [
                'name' => 'Sarah Johnson',
                'company' => 'Tech Innovations Inc.',
                'email' => 'sarah@techinnovations.com',
                'phone' => '+1 (555) 987-6543',
                'address' => '456 Innovation Drive, San Francisco, CA',
            ],
            'services' => $services,
            'subtotal' => $subtotal,
            'discount_percent' => $discountPercent,
            'discount' => $discount,
            'tax_percent' => $taxPercent,
            'tax' => $tax,
            'total' => $subtotal - $discount + $tax,
        ];
    }

    /**
     * Sample data for Receipt template
     *
     * @return array
     */
    protected function getReceiptSampleData()
    {
        $items = [
            ['name' => 'Premium Subscription - Annual', 'quantity' => 1, 'price' => 299.00],
            ['name' => 'Priority Support Package', 'quantity' => 1, 'price' => 149.00],
        ];

        $subtotal = array_reduce($items, function ($carry, $item) {
            return $carry + ($item['quantity'] * $item['price']);
        }, 0);

        $taxPercent = 8.5;
        $tax = $subtotal * ($taxPercent / 100);
        $discount = 25.00;

        return [
            'receipt_number' => 'RCP-' . now()->format('YmdHis'),
            'date' => now()->format('M d, Y'),
            'time' => now()->format('h:i A'),
            'cashier' => 'Admin User',
            'customer' => [
                'name' => 'Michael Brown',
                'email' => 'michael.brown@email.com',
                'phone' => '+1 (555) 456-7890',
            ],
            'items' => $items,
            'subtotal' => $subtotal,
            'tax_percent' => $taxPercent,
            'tax' => $tax,
            'discount' => $discount,
            'total' => $subtotal + $tax - $discount,
            'payment_method' => 'Credit Card (Visa **** 4242)',
            'transaction_id' => 'TXN-' . strtoupper(substr(md5(now()->timestamp), 0, 12)),
        ];
    }

    /**
     * Sample data for Business Report template
     *
     * @return array
     */
    protected function getReportSampleData()
    {
        return [
            'report_id' => 'RPT-' . now()->format('Ym') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT),
            'report_title' => 'Monthly Business Performance Report',
            'period_start' => now()->startOfMonth()->format('F d, Y'),
            'period_end' => now()->endOfMonth()->format('F d, Y'),
            'generated_by' => 'System Administrator',
            'total_revenue' => 158750.00,
            'total_orders' => 847,
            'new_customers' => 126,
            'avg_order_value' => '$187.50',
            'insights' => [
                'Revenue increased by 15% compared to last month',
                'Customer acquisition cost decreased by 8%',
                'Top performing category: Electronics (32% of total sales)',
                'Mobile orders now represent 65% of all transactions',
            ],
            'top_products' => [
                ['name' => 'Wireless Bluetooth Headphones', 'units' => 234, 'revenue' => 23400.00, 'trend' => 12],
                ['name' => 'Smart Watch Pro', 'units' => 189, 'revenue' => 37800.00, 'trend' => 8],
                ['name' => 'Laptop Stand Adjustable', 'units' => 156, 'revenue' => 7800.00, 'trend' => -3],
                ['name' => 'USB-C Hub 7-in-1', 'units' => 142, 'revenue' => 8520.00, 'trend' => 22],
                ['name' => 'Mechanical Keyboard RGB', 'units' => 128, 'revenue' => 15360.00, 'trend' => 5],
            ],
            'recent_orders' => [
                ['id' => 'ORD-10847', 'customer' => 'Alice Cooper', 'date' => now()->subDays(1)->format('M d, Y'), 'amount' => 245.00, 'status' => 'Completed'],
                ['id' => 'ORD-10846', 'customer' => 'Bob Wilson', 'date' => now()->subDays(1)->format('M d, Y'), 'amount' => 189.50, 'status' => 'Completed'],
                ['id' => 'ORD-10845', 'customer' => 'Carol Davis', 'date' => now()->subDays(2)->format('M d, Y'), 'amount' => 532.00, 'status' => 'Pending'],
                ['id' => 'ORD-10844', 'customer' => 'David Lee', 'date' => now()->subDays(2)->format('M d, Y'), 'amount' => 78.00, 'status' => 'Completed'],
                ['id' => 'ORD-10843', 'customer' => 'Eva Martinez', 'date' => now()->subDays(3)->format('M d, Y'), 'amount' => 1250.00, 'status' => 'Cancelled'],
            ],
            'revenue_by_category' => [
                ['name' => 'Electronics', 'revenue' => 50800.00, 'percentage' => 32],
                ['name' => 'Accessories', 'revenue' => 38100.00, 'percentage' => 24],
                ['name' => 'Software', 'revenue' => 31750.00, 'percentage' => 20],
                ['name' => 'Services', 'revenue' => 23812.50, 'percentage' => 15],
                ['name' => 'Others', 'revenue' => 14287.50, 'percentage' => 9],
            ],
            'sales_by_region' => [
                ['name' => 'North America', 'sales' => 63500.00, 'percentage' => 40],
                ['name' => 'Europe', 'sales' => 39687.50, 'percentage' => 25],
                ['name' => 'Asia Pacific', 'sales' => 31750.00, 'percentage' => 20],
                ['name' => 'Latin America', 'sales' => 15875.00, 'percentage' => 10],
                ['name' => 'Others', 'sales' => 7937.50, 'percentage' => 5],
            ],
        ];
    }

    /**
     * Sample data for Delivery Note template
     *
     * @return array
     */
    protected function getDeliveryNoteSampleData()
    {
        return [
            'delivery_number' => now()->format('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT),
            'order_number' => 'ORD-' . str_pad(rand(10000, 99999), 5, '0', STR_PAD_LEFT),
            'order_date' => now()->subDays(3)->format('M d, Y'),
            'po_number' => 'PO-' . str_pad(rand(1000, 9999), 4, '0', STR_PAD_LEFT),
            'delivery_date' => now()->format('M d, Y'),
            'carrier' => 'FedEx Express',
            'tracking_number' => 'FX' . rand(100000000000, 999999999999),
            'packages' => '2 boxes',
            'customer' => [
                'name' => 'ABC Corporation',
                'address' => '789 Corporate Blvd, Chicago, IL 60601',
                'phone' => '+1 (555) 789-0123',
            ],
            'items' => [
                ['name' => 'Wireless Bluetooth Headphones', 'ordered' => 10, 'shipped' => 10],
                ['name' => 'USB-C Charging Cable (2m)', 'ordered' => 25, 'shipped' => 25],
            ],
            'notes' => 'Handle with care. Please inspect items upon receipt and report any damages within 24 hours.',
        ];
    }

    /**
     * Sample data for Purchase Order template
     *
     * @return array
     */
    protected function getPurchaseOrderSampleData()
    {
        $items = [
            ['name' => 'Office Desk - Standing Adjustable', 'quantity' => 5, 'price' => 450.00],
            ['name' => 'Ergonomic Office Chair', 'quantity' => 5, 'price' => 320.00],
        ];

        $subtotal = array_reduce($items, function ($carry, $item) {
            return $carry + ($item['quantity'] * $item['price']);
        }, 0);

        $shipping = 150.00;
        $taxPercent = 8;
        $tax = $subtotal * ($taxPercent / 100);

        return [
            'po_number' => now()->format('Ymd') . '-' . str_pad(rand(100, 999), 3, '0', STR_PAD_LEFT),
            'date' => now()->format('M d, Y'),
            'required_date' => now()->addDays(14)->format('M d, Y'),
            'payment_terms' => 'Net 30',
            'shipping_method' => 'Ground Shipping',
            'vendor' => [
                'name' => 'Office Supplies Pro',
                'address' => '456 Vendor Street, Los Angeles, CA 90001',
                'phone' => '+1 (555) 234-5678',
                'email' => 'orders@officesuppliespro.com',
            ],
            'items' => $items,
            'subtotal' => $subtotal,
            'shipping' => $shipping,
            'tax_percent' => $taxPercent,
            'tax' => $tax,
            'total' => $subtotal + $shipping + $tax,
        ];
    }
}
