<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use App\Models\{StockUnit, TransferLog, Product};

class OperationsController extends Controller
{
    /**
     * Handle Incoming Transfers (Receive into Transfer Pool)
     * NOTE: Transit items are NOT financial stock (Price = 0, Status = Transfer Pool).
     */
    public function receiveTransfer(Request $request)
    {
        $request->validate([
            'source' => 'required|string',
            'date' => 'required|date',
            'bikeModel' => 'nullable|string', // Free-text description
            'items' => 'required|array|min:1',
            'items.*.engine' => 'required|string',
            'items.*.chassis' => 'required|string'
        ]);

        DB::transaction(function () use ($request) {
            foreach ($request->items as $item) {
                // Construct Description Note
                $modelDesc = $request->bikeModel ?? 'Unknown Model';
                $notes = "{$modelDesc} | Received from {$request->source}";

                // Check if unit exists in system
                $unit = StockUnit::where('engine_number', $item['engine'])->first();

                if ($unit) {
                    // If unit exists (e.g. returned stock), move to Transfer Pool
                    $unit->update([
                        'status' => 'Transfer Pool',
                        'notes' => $notes
                    ]);
                } else {
                    // Create new unit specifically for Transfer Pool (Zero Value)
                    $defaultProduct = Product::first();

                    StockUnit::create([
                        'id' => (string) Str::uuid(),
                        'product_id' => $defaultProduct ? $defaultProduct->id : 1, // Dummy linkage
                        'engine_number' => $item['engine'],
                        'chassis_number' => $item['chassis'],
                        'purchase_price' => 0, // Zero cost for transit units
                        'status' => 'Transfer Pool',
                        'condition' => 'Transfer/Transit',
                        'stock_type' => 'Transfer In',
                        'entry_date' => $request->date,
                        'ref_number' => $request->refNumber,
                        'notes' => $notes
                    ]);
                }

                // Log History
                TransferLog::create([
                    'type' => 'IN',
                    'party' => $request->source,
                    'ref_number' => $request->refNumber,
                    'date' => $request->date,
                    'engine_number' => $item['engine'],
                    'chassis_number' => $item['chassis'],
                    'details' => $modelDesc,
                    'notes' => $request->notes
                ]);
            }
        });

        return back()->with('message', 'Stock Received into Transfer Pool');
    }

    /**
     * Handle Outgoing Transfers (Issue/Dispatch)
     */
    public function issueTransfer(Request $request)
    {
        $request->validate([
            'dealer' => 'required|string',
            'ids' => 'required|array|min:1', // Array of StockUnit UUIDs
            'date' => 'required|date'
        ]);

        DB::transaction(function () use ($request) {
            $units = StockUnit::whereIn('id', $request->ids)->get();

            foreach ($units as $unit) {
                // Update Unit Status to remove from active pool
                $unit->update([
                    'status' => 'Transferred Out'
                ]);

                // Log History
                TransferLog::create([
                    'type' => 'OUT',
                    'party' => $request->dealer,
                    'ref_number' => $request->refNumber,
                    'date' => $request->date,
                    'engine_number' => $unit->engine_number,
                    'chassis_number' => $unit->chassis_number,
                    'details' => "Dispatched: " . $unit->engine_number,
                    'notes' => $request->notes
                ]);
            }
        });

        return back()->with('message', count($request->ids) . ' Units Dispatched');
    }
}
