<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Models\StockLedger;
use App\Models\Tank;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class StockController extends Controller
{
    public function manage(Request $request)
    {
        return view('stock.manage', [
            'tanks' => Tank::with('fuelType')->where('is_active', true)->get(),
            'customers' => Customer::where('is_active', true)->get(),
            'selectedTankId' => $request->integer('tank_id'),
            'recentLedgers' => StockLedger::with(['tank.fuelType','customer'])
                ->latest()
                ->limit(25)
                ->get(),
        ]);
    }

    public function add(Request $request)
    {
        $request->validate([
            'stock_date' => ['required','date'],
            'tank_id' => ['required','exists:tanks,id'],
            'owner_type' => ['required','in:own,customer'],
            'customer_id' => ['nullable','required_if:owner_type,customer','exists:customers,id'],
            'quantity' => ['required','numeric','min:0.001'],
            'notes' => ['nullable','string'],
        ]);

        try {
            DB::transaction(function () use ($request) {
                $tank = Tank::lockForUpdate()->findOrFail($request->tank_id);
                $newTotal = $tank->current_qty + $request->quantity;

                if ($tank->capacity > 0 && $newTotal > $tank->capacity) {
                    throw new \Exception('Tank capacity is not enough. Please check tank size first.');
                }

                $tank->current_qty = $newTotal;
                if ($request->owner_type === 'own') {
                    $tank->own_qty += $request->quantity;
                } else {
                    $tank->customer_qty += $request->quantity;
                }
                $tank->save();

                StockLedger::create([
                    'ledger_date' => $request->stock_date,
                    'fuel_type_id' => $tank->fuel_type_id,
                    'tank_id' => $tank->id,
                    'owner_type' => $request->owner_type,
                    'customer_id' => $request->owner_type === 'customer' ? $request->customer_id : null,
                    'qty_in' => $request->quantity,
                    'qty_out' => 0,
                    'balance' => $tank->current_qty,
                    'reference_type' => 'stock_add',
                    'reference_id' => $tank->id,
                    'notes' => $request->notes ?: 'Manual stock add',
                    'user_id' => Auth::id(),
                ]);
            });
        } catch (\Throwable $e) {
            return back()->withInput()->with('error', $e->getMessage());
        }

        return redirect()->route('stock.manage', ['tank_id' => $request->tank_id])
            ->with('success', 'Stock added successfully.');
    }

    public function correct(Request $request)
    {
        $request->validate([
            'stock_date' => ['required','date'],
            'tank_id' => ['required','exists:tanks,id'],
            'own_qty' => ['required','numeric','min:0'],
            'customer_qty' => ['required','numeric','min:0'],
            'notes' => ['nullable','string'],
        ]);

        try {
            DB::transaction(function () use ($request) {
                $tank = Tank::lockForUpdate()->findOrFail($request->tank_id);
                $oldTotal = (float) $tank->current_qty;
                $newOwn = (float) $request->own_qty;
                $newCustomer = (float) $request->customer_qty;
                $newTotal = $newOwn + $newCustomer;

                if ($tank->capacity > 0 && $newTotal > $tank->capacity) {
                    throw new \Exception('Corrected stock is more than tank capacity.');
                }

                $difference = $newTotal - $oldTotal;

                $tank->own_qty = $newOwn;
                $tank->customer_qty = $newCustomer;
                $tank->current_qty = $newTotal;
                $tank->save();

                StockLedger::create([
                    'ledger_date' => $request->stock_date,
                    'fuel_type_id' => $tank->fuel_type_id,
                    'tank_id' => $tank->id,
                    'owner_type' => 'own',
                    'customer_id' => null,
                    'qty_in' => $difference > 0 ? $difference : 0,
                    'qty_out' => $difference < 0 ? abs($difference) : 0,
                    'balance' => $tank->current_qty,
                    'reference_type' => 'stock_correction',
                    'reference_id' => $tank->id,
                    'notes' => $request->notes ?: 'Stock balance corrected. Old: '.$oldTotal.', New: '.$newTotal,
                    'user_id' => Auth::id(),
                ]);
            });
        } catch (\Throwable $e) {
            return back()->withInput()->with('error', $e->getMessage());
        }

        return redirect()->route('stock.manage', ['tank_id' => $request->tank_id])
            ->with('success', 'Stock corrected successfully.');
    }
}
