<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Storage;

class ReceiptPDFController extends Controller
{
    /**
     * Generate PDF from receipt HTML
     */
    public function generatePDF(Request $request)
    {
        try {
            $request->validate([
                'html' => 'required|string',
                'receipt' => 'required|array',
                'download' => 'boolean'
            ]);
            
            $html = $request->input('html');
            $receipt = $request->input('receipt');
            $download = $request->input('download', false);
            
            // Configure PDF
            $pdf = PDF::loadHTML($html);
            $pdf->setPaper('A4', 'portrait');
            $pdf->setOptions([
                'defaultFont' => 'Courier',
                'isHtml5ParserEnabled' => true,
                'isRemoteEnabled' => true,
                'dpi' => 150
            ]);
            
            $filename = 'receipt-' . ($receipt['invoice_no'] ?? time()) . '.pdf';
            
            if ($download) {
                return $pdf->download($filename);
            }
            
            return $pdf->stream($filename);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'PDF generation failed: ' . $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * Generate PDF from receipt data
     */
    public function generateFromData(Request $request)
    {
        try {
            $request->validate([
                'receipt' => 'required|array'
            ]);
            
            $receipt = $request->input('receipt');
            
            // Generate HTML from blade template
            $html = view('pos.receipts.pdf', [
                'receiptData' => $receipt
            ])->render();
            
            $pdf = PDF::loadHTML($html);
            $pdf->setPaper('A4', 'portrait');
            
            $filename = 'receipt-' . ($receipt['invoice_no'] ?? time()) . '.pdf';
            
            return $pdf->download($filename);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'PDF generation failed: ' . $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * Get PDF download link
     */
    public function getDownloadLink(Request $request)
    {
        try {
            $request->validate([
                'sale_id' => 'required|exists:sales,id'
            ]);
            
            $sale = \App\Models\Sale::with(['items.product', 'customer', 'payments'])
                ->findOrFail($request->input('sale_id'));
            
            // Generate receipt data
            $receiptData = $this->prepareReceiptData($sale);
            
            // Generate HTML
            $html = view('pos.receipts.pdf', [
                'receiptData' => $receiptData
            ])->render();
            
            // Generate PDF
            $pdf = PDF::loadHTML($html);
            $pdf->setPaper('A4', 'portrait');
            
            // Save to storage
            $filename = 'receipt-' . $sale->invoice_no . '.pdf';
            $path = 'receipts/' . date('Y/m/d') . '/' . $filename;
            
            Storage::disk('public')->put($path, $pdf->output());
            
            $url = Storage::disk('public')->url($path);
            
            return response()->json([
                'success' => true,
                'download_url' => $url,
                'filename' => $filename
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to generate download link: ' . $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * Prepare receipt data from sale
     */
    private function prepareReceiptData($sale)
    {
        return [
            'invoice_no' => $sale->invoice_no,
            'date' => $sale->sale_date->format('Y-m-d'),
            'time' => $sale->sale_date->format('H:i:s'),
            'cashier' => $sale->user->name,
            'customer' => $sale->customer ? [
                'name' => $sale->customer->name,
                'phone' => $sale->customer->phone,
                'pin' => $sale->customer->pin,
                'vat_status' => $sale->customer->vat_status
            ] : null,
            'items' => $sale->items->map(function ($item) {
                return [
                    'name' => $item->product->name,
                    'quantity' => $item->quantity,
                    'unit_price' => $item->unit_price,
                    'total' => $item->total,
                    'vat_included' => $item->product->has_vat
                ];
            }),
            'totals' => [
                'subtotal' => $sale->subtotal,
                'vat_amount' => $sale->vat_amount,
                'discount' => $sale->discount,
                'grand_total' => $sale->total
            ],
            'payment' => $sale->payments->first() ? [
                'method' => $sale->payments->first()->method,
                'amount_paid' => $sale->payments->first()->amount
            ] : null,
            'store' => [
                'name' => config('app.name'),
                'address' => config('app.address'),
                'phone' => config('app.phone'),
                'vat_number' => config('app.vat_number')
            ]
        ];
    }
}