<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Tenant\Product;
use App\Models\Tenant\Customer;
use App\Models\Tenant\Sale;
use App\Models\Tenant\ProductVariant;
use App\Models\Tenant\Category;
use App\Models\Tenant\Unit;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SellController extends Controller
{
    public function index()
    {
        $customers = Customer::on('tenant')
            ->select('id', 'name', 'contact', 'is_sub_dealer')
            ->orderBy('name')
            ->get();
        
        $categories = Category::on('tenant')->select('id', 'name')->orderBy('name')->get();
        $units = Unit::on('tenant')->select('id', 'name', 'short_name', 'conversion_factor', 'base_unit_id')->get();
        
        // Fetch all products with variants for local search (to minimize load time during typing)
        $products = Product::on('tenant')
            ->with([
                'variants' => function($q) {
                    $q->select('id', 'product_id', 'name', 'sku', 'price', 'stock')
                      ->with(['prices.productUnit']);
                },
                'productUnits'
            ])
            ->select('id', 'name', 'category_id', 'has_variants', 'unit_id')
            ->get();

        return view('tenant.sell.index', compact('customers', 'categories', 'units', 'products'));
    }

    public function store(Request $request)
    {
        try {
            DB::connection('tenant')->beginTransaction();

            $sale = Sale::on('tenant')->create([
                'customer_id' => $request->customer_id,
                'subtotal' => $request->subtotal,
                'discount' => $request->discount,
                'total' => $request->total,
                'paid_amount' => $request->paid_amount,
                'payment_method' => $request->payment_method,
                'transaction_id' => $request->transaction_id,
                'status' => $request->status ?? 'completed',
                'payment_status' => $request->paid_amount >= $request->total ? 'paid' : ($request->paid_amount > 0 ? 'partial' : 'due'),
                'invoice_no' => 'INV-' . strtoupper(str_random(8)),
            ]);

            foreach ($request->items as $item) {
                $sale->items()->create([
                    'product_variant_id' => $item['variant_id'],
                    'product_unit_id' => $item['product_unit_id'] ?? null,
                    'conversion_factor' => $item['conversion_factor'] ?? 1,
                    'quantity' => $item['quantity'],
                    'price' => $item['price'],
                    'discount' => $item['discount'] ?? 0,
                    'total' => ($item['price'] * $item['quantity']) - ($item['discount'] ?? 0),
                ]);

                // Update stock in Base Unit
                $variant = ProductVariant::on('tenant')->find($item['variant_id']);
                if ($variant) {
                    $base_qty = $item['quantity'] * ($item['conversion_factor'] ?? 1);
                    $variant->decrement('stock', $base_qty);
                }
            }

            DB::connection('tenant')->commit();

            return response()->json([
                'success' => true,
                'message' => 'Sale completed successfully',
                'sale' => $sale
            ]);
        } catch (\Exception $e) {
            DB::connection('tenant')->rollBack();
            Log::error('Sale Error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to complete sale: ' . $e->getMessage()
            ], 500);
        }
    }

    public function searchProducts(Request $request)
    {
        $query = $request->get('q');
        $products = Product::on('tenant')
            ->where('name', 'like', "%{$query}%")
            ->orWhereHas('variants', function($q) use ($query) {
                $q->where('sku', 'like', "%{$query}%");
            })
            ->with(['variants'])
            ->limit(10)
            ->get();

        return response()->json($products);
    }
}
