<?php

namespace App\Http\Controllers;

use App\Models\ReceiptSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log; // Add this

class ReceiptSettingsController extends Controller
{
    const CACHE_KEY = 'receipt_settings';
    const CACHE_TTL = 3600;

    /**
     * Display receipt settings
     */
    public function index()
    {
        $settings = ReceiptSetting::getActive();
        $defaultSetting = ReceiptSetting::getDefault();
        
        return view('settings.receipt', compact('settings', 'defaultSetting'));
    }

    /**
     * Store new receipt setting
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:100',
            'paper_size' => 'required|string|in:80mm,58mm,A4,A5',
            'chars_per_line' => 'required|integer|min:32|max:80',
            'encoding' => 'required|string|in:CP850,CP437,UTF-8',
            'auto_cut' => 'boolean',
            'auto_open_drawer' => 'boolean',
            'print_store_logo' => 'boolean',
            'logo_path' => 'nullable|url|max:500',
            'print_store_name' => 'boolean',
            'print_store_address' => 'boolean',
            'print_store_phone' => 'boolean',
            'print_vat_number' => 'boolean',
            'print_branch_code' => 'boolean',
            'print_cashier_name' => 'boolean',
            'print_date_time' => 'boolean',
            'print_transaction_number' => 'boolean',
            'print_customer_info' => 'boolean',
            'print_item_barcode' => 'boolean',
            'print_qr_code' => 'boolean',
            'qr_code_type' => 'required_if:print_qr_code,true|string|in:store_info,transaction_id,payment_link',
            'print_tax_breakdown' => 'boolean',
            'print_discounts' => 'boolean',
            'print_payment_method' => 'boolean',
            'print_change_amount' => 'boolean',
            'footer_text' => 'nullable|string|max:500',
            'print_footer' => 'boolean',
            'copies' => 'required|integer|min:1|max:3',
            'is_default' => 'boolean',
            'is_active' => 'boolean',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput()
                ->with('error', 'Please correct the errors below.');
        }

        try {
            $data = $validator->validated();
            
            // If this is set as default, remove default from other settings
            if ($request->boolean('is_default')) {
                ReceiptSetting::where('is_default', true)->update(['is_default' => false]);
            }

            // Handle custom settings
            $customSettings = [];
            if ($request->filled('custom_settings')) {
                $customSettings = json_decode($request->custom_settings, true);
            }
            $data['custom_settings'] = $customSettings;

            $receiptSetting = ReceiptSetting::create($data);

            // Clear cache
            $this->clearCache();

            // Log activity
            activity()
                ->causedBy(auth()->user())
                ->log('created receipt setting: ' . $receiptSetting->name);

            return redirect()->route('settings.receipt.index')
                ->with('success', 'Receipt setting created successfully!');

        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Failed to create receipt setting: ' . $e->getMessage());
        }
    }

    /**
     * Update receipt setting
     */
    public function update(Request $request, ReceiptSetting $receiptSetting)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'sometimes|required|string|max:100',
            'paper_size' => 'sometimes|required|string|in:80mm,58mm,A4,A5',
            'chars_per_line' => 'sometimes|required|integer|min:32|max:80',
            'encoding' => 'sometimes|required|string|in:CP850,CP437,UTF-8',
            'auto_cut' => 'sometimes|boolean',
            'auto_open_drawer' => 'sometimes|boolean',
            'print_store_logo' => 'sometimes|boolean',
            'logo_path' => 'nullable|url|max:500',
            'print_store_name' => 'sometimes|boolean',
            'print_store_address' => 'sometimes|boolean',
            'print_store_phone' => 'sometimes|boolean',
            'print_vat_number' => 'sometimes|boolean',
            'print_branch_code' => 'sometimes|boolean',
            'print_cashier_name' => 'sometimes|boolean',
            'print_date_time' => 'sometimes|boolean',
            'print_transaction_number' => 'sometimes|boolean',
            'print_customer_info' => 'sometimes|boolean',
            'print_item_barcode' => 'sometimes|boolean',
            'print_qr_code' => 'sometimes|boolean',
            'qr_code_type' => 'sometimes|required_if:print_qr_code,true|string|in:store_info,transaction_id,payment_link',
            'print_tax_breakdown' => 'sometimes|boolean',
            'print_discounts' => 'sometimes|boolean',
            'print_payment_method' => 'sometimes|boolean',
            'print_change_amount' => 'sometimes|boolean',
            'footer_text' => 'nullable|string|max:500',
            'print_footer' => 'sometimes|boolean',
            'copies' => 'sometimes|required|integer|min:1|max:3',
            'is_default' => 'sometimes|boolean',
            'is_active' => 'sometimes|boolean',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput()
                ->with('error', 'Please correct the errors below.');
        }

        try {
            $data = $validator->validated();
            
            // If this is set as default, remove default from other settings
            if ($request->has('is_default') && $request->boolean('is_default')) {
                ReceiptSetting::where('id', '!=', $receiptSetting->id)
                    ->where('is_default', true)
                    ->update(['is_default' => false]);
            }

            // Handle custom settings
            if ($request->filled('custom_settings')) {
                $data['custom_settings'] = json_decode($request->custom_settings, true);
            }

            $receiptSetting->update($data);

            // Clear cache
            $this->clearCache();

            // Log activity
            activity()
                ->causedBy(auth()->user())
                ->log('updated receipt setting: ' . $receiptSetting->name);

            return redirect()->route('settings.receipt.index')
                ->with('success', 'Receipt setting updated successfully!');

        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Failed to update receipt setting: ' . $e->getMessage());
        }
    }

    /**
     * Delete receipt setting
     */
    public function destroy(ReceiptSetting $receiptSetting)
    {
        try {
            // Don't allow deleting the only default setting
            if ($receiptSetting->is_default && ReceiptSetting::where('is_default', true)->count() === 1) {
                return redirect()->back()
                    ->with('error', 'Cannot delete the only default receipt setting.');
            }

            $receiptSetting->delete();

            // Clear cache
            $this->clearCache();

            // Log activity
            activity()
                ->causedBy(auth()->user())
                ->log('deleted receipt setting: ' . $receiptSetting->name);

            return redirect()->route('settings.receipt.index')
                ->with('success', 'Receipt setting deleted successfully!');

        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Failed to delete receipt setting: ' . $e->getMessage());
        }
    }

    /**
     * Set as default receipt setting
     */
    public function setDefault(ReceiptSetting $receiptSetting)
    {
        try {
            // Remove default from other settings
            ReceiptSetting::where('is_default', true)->update(['is_default' => false]);
            
            // Set this as default
            $receiptSetting->update(['is_default' => true]);

            // Clear cache
            $this->clearCache();

            return redirect()->route('settings.receipt.index')
                ->with('success', 'Receipt setting set as default!');

        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Failed to set default receipt setting.');
        }
    }

    /**
     * Get receipt settings for API
     */
    public function apiGetSettings()
    {
        $settings = Cache::remember(self::CACHE_KEY, self::CACHE_TTL, function () {
            $default = ReceiptSetting::getDefault();
            
            if (!$default) {
                // Return default configuration
                return $this->getDefaultConfig();
            }
            
            return $default->getFormattedSettings();
        });

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

    /**
     * Get receipt setting by ID for API
     */
    public function apiGetSetting($id)
    {
        $setting = ReceiptSetting::find($id);
        
        if (!$setting) {
            return response()->json([
                'success' => false,
                'message' => 'Receipt setting not found'
            ], 404);
        }

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

    /**
     * Test receipt generation
     */
/**
 * Test receipt generation
 */
/**
 * Test receipt generation
 */
public function testReceipt(Request $request)
{
    try {
        $settingId = $request->get('setting_id');
        
        if ($settingId) {
            $setting = ReceiptSetting::find($settingId);
        } else {
            $setting = ReceiptSetting::getDefault();
        }

        if (!$setting) {
            $setting = new ReceiptSetting();
            $setting->fill($this->getDefaultConfig());
        }

        // Get actual store information
        $storeInfo = \App\Models\StoreInformation::first();
        
        if (!$storeInfo) {
            return redirect()->back()
                ->with('error', 'No store information found. Please save store information first.');
        }
        
        // Get actual store logo path
        $logoPath = null;
        if ($storeInfo->logo) {
            if (filter_var($storeInfo->logo, FILTER_VALIDATE_URL)) {
                $logoPath = $storeInfo->logo;
            } else {
                // Try to get logo from storage
                $logoPath = asset('storage/' . $storeInfo->logo);
            }
        }

        // Generate test data
        $testData = $this->generateTestData($storeInfo);
        
        // Generate QR code using Google Charts API
        if ($setting->print_qr_code) {
            $qrImage = $this->generateQRCodeWithGoogle($storeInfo, $testData);
            $testData['qr_code']['image'] = $qrImage;
        }

        return view('receipt.test', [
            'setting' => $setting,
            'data' => $testData,
            'storeInfo' => $storeInfo,
        ]);
        
    } catch (\Exception $e) {
        Log::error('Error generating test receipt: ' . $e->getMessage());
        
        return redirect()->back()
            ->with('error', 'Failed to generate test receipt: ' . $e->getMessage());
    }
}

/**
 * Generate test data
 */
private function generateTestData($storeInfo)
{
    $invoiceNo = 'INV-' . date('Ym') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
    $grandTotal = 7728.00;
    
    return [
        'store' => [
            'name' => $storeInfo->store_name,
            'logo' => $storeInfo->logo ? (filter_var($storeInfo->logo, FILTER_VALIDATE_URL) ? $storeInfo->logo : asset('storage/' . $storeInfo->logo)) : null,
            'address' => $storeInfo->address,
            'phone' => $storeInfo->telephone,
            'whatsapp' => $storeInfo->whatsapp_number,
            'email' => $storeInfo->email,
            'vat_number' => $storeInfo->vat_number,
            'branch_code' => $storeInfo->branch_code,
            'company_pin' => $storeInfo->company_pin,
            'city' => $storeInfo->city,
            'country' => $storeInfo->country,
            'kra_pin' => $storeInfo->kra_pin,
            'currency' => $storeInfo->currency,
            'timezone' => $storeInfo->timezone,
        ],
        'transaction' => [
            'id' => 'TEST-' . date('Ymd-His'),
            'invoice_no' => $invoiceNo,
            'date' => now()->format('d/m/Y'),
            'time' => now()->format('H:i:s'),
            'cashier' => auth()->user()->name ?? 'System Admin',
        ],
        'customer' => [
            'name' => 'Test Customer',
            'phone' => '0712 345 678',
            'email' => 'customer@example.com',
        ],
        'items' => [
            [
                'name' => 'Engine Oil 5W-30',
                'quantity' => 2,
                'price' => 1250.00,
                'total' => 2500.00,
                'barcode' => '8901234567890',
                'tax_rate' => 16,
            ],
            [
                'name' => 'Brake Pads Set',
                'quantity' => 1,
                'price' => 1800.00,
                'total' => 1800.00,
                'barcode' => '8909876543210',
                'tax_rate' => 16,
            ],
            [
                'name' => 'Air Filter',
                'quantity' => 3,
                'price' => 450.00,
                'total' => 1350.00,
                'barcode' => '8904567890123',
                'tax_rate' => 16,
            ],
            [
                'name' => 'Wiper Blades Pair',
                'quantity' => 1,
                'price' => 850.00,
                'total' => 850.00,
                'barcode' => '8907890123456',
                'tax_rate' => 16,
            ],
            [
                'name' => 'Car Wash Service',
                'quantity' => 1,
                'price' => 500.00,
                'total' => 500.00,
                'barcode' => 'SVC-CWASH-001',
                'tax_rate' => 0,
            ],
        ],
        'totals' => [
            'subtotal' => 7000.00,
            'tax' => 928.00,
            'discount' => 200.00,
            'grand_total' => $grandTotal,
            'total_items' => 8,
        ],
        'payment' => [
            'method' => 'M-Pesa',
            'amount_paid' => 8000.00,
            'change' => 272.00,
            'transaction_id' => 'MPESA-' . time(),
        ],
        'qr_code' => [
            'type' => 'eTIMS/KRA',
            'text' => 'eTIMS/KRA QR Code',
        ],
        'is_test' => true,
    ];
}

/**
 * Generate QR code using Google Charts API
 */
private function generateQRCodeWithGoogle($storeInfo, $testData)
{
    try {
        // Create QR code data string
        $qrData = [
            'ver' => '1.0',
            'idt' => now()->format('Y-m-d\TH:i:s'),
            'tin' => $storeInfo->company_pin ?? 'P000000000A',
            'bhfId' => $storeInfo->branch_code ?? '001',
            'invNo' => $testData['transaction']['invoice_no'] ?? 'INV-TEST',
            'sdcId' => 'SDC' . rand(1000, 9999),
            'buyerTin' => 'P051233870C',
            'buyerNm' => $testData['customer']['name'] ?? 'Test Customer',
            'totTaxblAmt' => $testData['totals']['subtotal'] ?? 0,
            'totTaxAmt' => $testData['totals']['tax'] ?? 0,
            'totAmt' => $testData['totals']['grand_total'] ?? 0,
        ];
        
        // Convert to string for QR code
        $qrString = json_encode($qrData);
        
        // Generate QR code URL using Google Charts API
        $encodedData = urlencode($qrString);
        
        // Alternative: Use a simpler text format if Google API is blocked
        $simpleText = "Store: {$storeInfo->store_name}\n";
        $simpleText .= "TIN: {$storeInfo->company_pin}\n";
        $simpleText .= "Invoice: {$testData['transaction']['invoice_no']}\n";
        $simpleText .= "Amount: KSh " . number_format($testData['totals']['grand_total'], 2) . "\n";
        $simpleText .= "Date: " . now()->format('Y-m-d H:i:s');
        
        $encodedText = urlencode($simpleText);
        
        // Return Google Charts QR code URL
        return "https://chart.googleapis.com/chart?chs=150x150&cht=qr&chl=" . $encodedText . "&choe=UTF-8";
        
    } catch (\Exception $e) {
        Log::error('Google QR Code generation error: ' . $e->getMessage());
        return $this->generateSimpleQRCodePlaceholder();
    }
}

/**
 * Generate simple QR code placeholder as fallback
 */
private function generateSimpleQRCodePlaceholder()
{
    // Return a simple SVG placeholder
    return 'data:image/svg+xml;base64,' . base64_encode($this->getQRCodeSVG());
}

/**
 * Get SVG for QR code placeholder
 */
private function getQRCodeSVG()
{
    return <<<SVG
<svg width="150" height="150" xmlns="http://www.w3.org/2000/svg">
    <rect width="150" height="150" fill="#ffffff"/>
    <rect x="15" y="15" width="120" height="120" fill="#ffffff" stroke="#000" stroke-width="2"/>
    
    <!-- QR code pattern -->
    <!-- Top-left position marker -->
    <rect x="25" y="25" width="25" height="25" fill="#000"/>
    <rect x="30" y="30" width="15" height="15" fill="#ffffff"/>
    
    <!-- Top-right position marker -->
    <rect x="100" y="25" width="25" height="25" fill="#000"/>
    <rect x="105" y="30" width="15" height="15" fill="#ffffff"/>
    
    <!-- Bottom-left position marker -->
    <rect x="25" y="100" width="25" height="25" fill="#000"/>
    <rect x="30" y="105" width="15" height="15" fill="#ffffff"/>
    
    <!-- Data modules -->
    <rect x="60" y="40" width="8" height="8" fill="#000"/>
    <rect x="80" y="40" width="8" height="8" fill="#000"/>
    <rect x="60" y="60" width="8" height="8" fill="#000"/>
    <rect x="70" y="60" width="8" height="8" fill="#000"/>
    <rect x="90" y="60" width="8" height="8" fill="#000"/>
    <rect x="60" y="80" width="8" height="8" fill="#000"/>
    <rect x="80" y="80" width="8" height="8" fill="#000"/>
    <rect x="100" y="80" width="8" height="8" fill="#000"/>
    <rect x="70" y="100" width="8" height="8" fill="#000"/>
    <rect x="90" y="100" width="8" height="8" fill="#000"/>
    
    <!-- Center alignment -->
    <rect x="75" y="75" width="10" height="10" fill="#000"/>
    
    <!-- Text -->
    <text x="75" y="140" text-anchor="middle" font-family="Arial" font-size="8" fill="#333">eTIMS QR Code</text>
</svg>
SVG;
}

    /**
     * Clear receipt settings cache
     */
    private function clearCache()
    {
        Cache::forget(self::CACHE_KEY);
    }

    /**
     * Get default configuration
     */
    private function getDefaultConfig()
    {
        return [
            'paper' => [
                'size' => '80mm',
                'chars_per_line' => 42,
                'encoding' => 'CP850',
            ],
            'printer' => [
                'auto_cut' => true,
                'auto_open_drawer' => false,
                'copies' => 1,
            ],
            'header' => [
                'print_logo' => false,
                'logo_path' => null,
                'print_name' => true,
                'print_address' => true,
                'print_phone' => true,
                'print_vat' => true,
                'print_branch' => true,
            ],
            'body' => [
                'print_cashier' => true,
                'print_datetime' => true,
                'print_transaction_no' => true,
                'print_customer' => false,
                'print_item_barcode' => false,
                'print_qr_code' => true,
                'qr_code_type' => 'store_info',
                'print_tax' => true,
                'print_discounts' => true,
            ],
            'footer' => [
                'print_payment_method' => true,
                'print_change' => true,
                'print_footer' => true,
                'footer_text' => 'Thank you for shopping with us!',
            ],
            'custom' => [],
        ];
    }
}