<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Tenant\Sale;
use App\Models\Tenant\SaleReturn;
use App\Models\Tenant\ProductVariant;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class SaleReturnController extends Controller
{
    public function index()
    {
        $returns = SaleReturn::with(['customer', 'sale'])->latest()->paginate(10);
        return view('tenant.sales.returns.index', compact('returns'));
    }

    public function create(Request $request)
    {
        $sale = null;
        if ($request->has('sale_id')) {
            $sale = Sale::with(['items.variant.product', 'items.productUnit', 'customer'])->find($request->sale_id);
        }
        return view('tenant.sales.returns.create', compact('sale'));
    }

    public function search(Request $request)
    {
        $request->validate(['invoice_no' => 'required|string']);
        
        $sale = Sale::where('invoice_no', $request->invoice_no)->first();
        
        if (!$sale) {
            return back()->with('error', 'Invoice not found.');
        }

        return redirect()->route('tenant.returns.create', ['sale_id' => $sale->id]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'sale_id' => 'required|exists:tenant.sales,id',
            'items' => 'required|array',
            'items.*.variant_id' => 'required|exists:tenant.product_variants,id',
            'items.*.quantity' => 'required|numeric|min:0.01',
            'items.*.unit_price' => 'required|numeric|min:0',
            'note' => 'nullable|string',
        ]);

        try {
            DB::transaction(function () use ($validated) {
                $sale = Sale::findOrFail($validated['sale_id']);
                
                // Calculate Total Refund
                $totalRefund = 0;
                foreach ($validated['items'] as $item) {
                    $totalRefund += $item['quantity'] * $item['unit_price'];
                }

                // Create Return Record
                $return = SaleReturn::create([
                    'sale_id' => $sale->id,
                    'return_no' => 'RET-' . date('Ymd') . '-' . strtoupper(Str::random(4)),
                    'customer_id' => $sale->customer_id,
                    'total_amount' => $totalRefund,
                    'note' => $validated['note'],
                ]);

                // Process Items
                foreach ($validated['items'] as $itemData) {
                    // Find original sale item to get unit info (simplification)
                    // Ideally we should pass unit_id from form, but for now let's assume base or infer
                    $originalItem = $sale->items()->where('variant_id', $itemData['variant_id'])->first();
                    
                    $return->items()->create([
                        'product_variant_id' => $itemData['variant_id'],
                        'product_unit_id' => $originalItem->product_unit_id ?? null,
                        'conversion_factor' => $originalItem->conversion_factor ?? 1,
                        'quantity' => $itemData['quantity'],
                        'unit_price' => $itemData['unit_price'],
                        'total' => $itemData['quantity'] * $itemData['unit_price'],
                    ]);

                    // Update Stock (Increment)
                    $variant = ProductVariant::find($itemData['variant_id']);
                    $qtyToAdd = $itemData['quantity'] * ($originalItem->conversion_factor ?? 1);
                    $variant->increment('stock', $qtyToAdd);
                }

                // Update Sale Status if fully returned? (Optional logic)
                // For now just keep record
            });

            return redirect()->route('tenant.returns.index')->with('success', 'Return processed successfully.');
        } catch (\Exception $e) {
            return back()->with('error', 'Return failed: ' . $e->getMessage());
        }
    }
}
