<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Storage;

class ProductController extends Controller
{
    /**
     * Display the inventory catalog.
     */
    public function index()
    {
        // Global scope automatically filters this to the logged-in user's company
        $products = Product::latest()->paginate(20);

        return view('inventory.products', compact('products'));
    }

    /**
     * Store a newly created product in storage.
     */
    public function store(Request $request)
    {
        $companyId = auth()->user()->company_id;

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'industrial_name' => ['nullable', 'string', 'max:255'],
            'brand' => ['nullable', 'string', 'max:255'],

            // Image Validation: Must be an image, max 2048 KB (2MB)
            'image' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp', 'max:2048'],
            
            // SKU must be unique, but ONLY within the same company
            'sku' => [
                'required', 
                'string', 
                'max:255',
                Rule::unique('products')->where(function ($query) use ($companyId) {
                    return $query->where('company_id', $companyId);
                })
            ],
            
            // Barcode must be unique within the company if provided
            'barcode' => [
                'nullable', 
                'string', 
                'max:255',
                Rule::unique('products')->where(function ($query) use ($companyId) {
                    return $query->where('company_id', $companyId);
                })
            ],
            
            'selling_price' => ['required', 'numeric', 'min:0'],
            'purchase_price' => ['nullable', 'numeric', 'min:0'],
            'low_stock_threshold' => ['required', 'integer', 'min:0'],
            
            // THE MISSING LINK: Capture the Initial Stock from the frontend
            'stock_quantity' => ['required', 'integer', 'min:0'], 
        ]);

        // Handle Image Upload
        if ($request->hasFile('image')) {
            // Stores in storage/app/public/products
            $validated['image_path'] = $request->file('image')->store('products', 'public');
        }

        // 1. Create the Product
        // Model events will automatically attach company_id, created_by, and generate a barcode if missing
        $product = Product::create($validated);

        // 2. Write the Initial Stock to the Audit Ledger
        if ($validated['stock_quantity'] > 0) {
            \App\Models\StockMovement::create([
                'company_id' => $companyId,
                'product_id' => $product->id,
                'user_id' => auth()->id(),
                'type' => 'addition',
                'quantity' => $validated['stock_quantity'],
                'balance_after' => $validated['stock_quantity'],
                'reference' => 'Initial Stock Registration',
            ]);
        }

        return redirect()->route('products.index')
            ->with('success', 'Product registered successfully.');
    }

   /**
     * Update the specified product in storage.
     */
    public function update(Request $request, Product $product)
    {
        $companyId = auth()->user()->company_id;

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'industrial_name' => ['nullable', 'string', 'max:255'],
            'brand' => ['nullable', 'string', 'max:255'],
            
            // Image Validation
            'image' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp', 'max:2048'],
            
            // Unique rules MUST ignore the current product's ID
            'sku' => [
                'required', 'string', 'max:255',
                Rule::unique('products')->where(fn ($query) => $query->where('company_id', $companyId))->ignore($product->id)
            ],
            'barcode' => [
                'nullable', 'string', 'max:255',
                Rule::unique('products')->where(fn ($query) => $query->where('company_id', $companyId))->ignore($product->id)
            ],
            
            'selling_price' => ['required', 'numeric', 'min:0'],
            'low_stock_threshold' => ['required', 'integer', 'min:0'],
        ]);

        // Handle Image Replacement
        if ($request->hasFile('image')) {
            // Delete the old image from the server to save space
            if ($product->image_path) {
                Storage::disk('public')->delete($product->image_path);
            }
            // Store the new one
            $validated['image_path'] = $request->file('image')->store('products', 'public');
        }

        $product->update($validated);

        return redirect()->route('products.index')
            ->with('success', 'Product details updated successfully.');
    }

    /**
     * Display analytics and movement history for a single product.
     */
    public function analytics(Product $product)
    {
        // 1. Security Check: Ensure the product belongs to this company
        if ($product->company_id !== auth()->user()->company_id) {
            abort(403, 'Unauthorized access.');
        }

        // 2. Fetch all movements with the user who made them
        $movements = $product->stockMovements()->with('user')->latest()->get();

        // 3. Crunch the numbers using Laravel Collections
        $metrics = [
            'total_sold' => $movements->where('type', 'deduction')->sum('quantity'),
            'total_revenue' => $movements->where('type', 'deduction')->sum('total_price'),
            'total_restocked' => $movements->where('type', 'addition')->sum('quantity'),
        ];

        return view('inventory.product-analytics', compact('product', 'movements', 'metrics'));
    }
}