<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Sale;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ReceiptController extends Controller
{
    /**
     * Get receipt data
     */
    public function generateReceipt($saleId)
    {
        try {
            $sale = Sale::with(['customer', 'items.product', 'payment'])
                ->findOrFail($saleId);
            
            // Get customer tax information
            $customer = $sale->customer;
            $customerTaxInfo = [
                'name' => $customer->name ?? 'Walk-in Customer',
                'phone' => $customer->phone ?? null,
                'email' => $customer->email ?? null,
                'vat_number' => $customer->vat_number ?? null,
                'pin' => $customer->tax_pin ?? $customer->pin ?? null,
                'company_name' => $customer->company_name ?? null,
                'address' => $customer->address ?? null,
                'is_vat_registered' => $customer->is_vat_registered ?? false,
            ];
            
            // Calculate VAT breakdown
            $vatableAmount = 0;
            $vatAmount = 0;
            $nonVatableAmount = 0;
            
            foreach ($sale->items as $item) {
                if ($item->product->is_vatable ?? false) {
                    $itemTotal = $item->quantity * $item->price;
                    $vatableAmount += $itemTotal;
                    $vatAmount += ($itemTotal * 0.16); // 16% VAT rate
                } else {
                    $nonVatableAmount += $item->quantity * $item->price;
                }
            }
            
            $receiptData = [
                'invoice_no' => $sale->invoice_no,
                'date' => $sale->created_at->format('d/m/Y'),
                'time' => $sale->created_at->format('H:i:s'),
                'cashier' => $sale->cashier->name ?? 'System',
                
                'store' => [
                    'name' => config('app.name', 'Kenyan Supermarket'),
                    'address' => config('app.address', 'Nairobi CBD'),
                    'phone' => config('app.phone', '0700 000 000'),
                    'email' => config('app.email', 'info@example.com'),
                    'pin' => config('app.tax_pin', 'P0000000000'),
                    'vat_number' => config('app.vat_number', 'VAT0000000'),
                ],
                
                'customer' => $customerTaxInfo,
                
                'items' => $sale->items->map(function($item) {
                    return [
                        'name' => $item->product->name,
                        'quantity' => $item->quantity,
                        'unit_price' => $item->price,
                        'total' => $item->quantity * $item->price,
                        'vat_included' => $item->product->is_vatable ?? false,
                    ];
                })->toArray(),
                
                'totals' => [
                    'subtotal' => $sale->subtotal,
                    'vatable_amount' => $vatableAmount,
                    'vat_amount' => $vatAmount,
                    'non_vatable_amount' => $nonVatableAmount,
                    'discount' => $sale->discount_amount ?? 0,
                    'grand_total' => $sale->total_amount,
                ],
                
                'payment' => [
                    'method' => $sale->payment->payment_method ?? 'cash',
                    'amount_paid' => $sale->total_amount,
                    'cash_tendered' => $sale->payment->cash_tendered ?? $sale->total_amount,
                    'change' => ($sale->payment->cash_tendered ?? $sale->total_amount) - $sale->total_amount,
                ],
            ];
            
            // Add M-Pesa details if applicable
            if ($sale->payment->payment_method === 'mpesa') {
                $receiptData['payment']['mpesa_details'] = [
                    'phone' => $sale->payment->mpesa_phone ?? null,
                    'transaction_id' => $sale->payment->mpesa_transaction_id ?? null,
                    'receipt_no' => $sale->payment->mpesa_receipt_no ?? null,
                ];
            }
            
            // Add Card details if applicable
            if ($sale->payment->payment_method === 'card') {
                $receiptData['payment']['card_details'] = [
                    'type' => $sale->payment->card_type ?? 'Credit Card',
                    'last4' => substr($sale->payment->card_number ?? '0000', -4),
                    'transaction_id' => $sale->payment->transaction_id ?? null,
                ];
            }
            
            return view('pos.receipts.receipt', compact('receiptData'));
            
        } catch (\Exception $e) {
            \Log::error('Receipt generation error: ' . $e->getMessage());
            abort(500, 'Failed to generate receipt');
        }
    }
}