<?php

namespace App\Http\Controllers;

use App\Models\GatePass;
use App\Models\InspectionRequest;
use App\Models\InspectionResult;
use App\Models\InventoryBalance;
use App\Models\InventoryMove;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\JsonResponse;

class InspectionRequestController extends Controller
{
    public function store(Request $request): RedirectResponse
    {
        $v = $request->validate([
            'igp_id' => 'required|exists:gate_passes,id',
            'request_number' => 'nullable|string|max:50',
            'remarks' => 'nullable|string',
            'items' => 'required|array|min:1',
            'items.*.item_id' => 'required|exists:items,id',
            'items.*.purchase_order_item_id' => 'nullable|exists:purchase_order_items,id',
            'items.*.uom_id' => 'nullable|exists:uoms,id',
            'items.*.ordered_qty' => 'nullable|numeric|min:0',
            'items.*.inspected_qty' => 'required|numeric|min:0',
            'items.*.accepted_qty' => 'required|numeric|min:0',
            'items.*.rejected_qty' => 'required|numeric|min:0',
            'items.*.warehouse_id' => 'nullable|exists:warehouses,id',
            'items.*.bin_id' => 'nullable|exists:warehouse_bins,id',
        ]);

        return DB::transaction(function () use ($v) {
            // Create inspection request
            $req = InspectionRequest::create([
                'request_number' => $v['request_number'] ?? now()->format('YmdHis'),
                'igp_id' => $v['igp_id'],
                'created_by' => auth()->id(),
                'status' => 'approved',
                'remarks' => $v['remarks'] ?? null,
            ]);

            // Create results and post accepted qty to inventory
            foreach ($v['items'] as $row) {
                $res = InspectionResult::create([
                    'inspection_request_id' => $req->id,
                    'item_id' => $row['item_id'],
                    'purchase_order_item_id' => $row['purchase_order_item_id'] ?? null,
                    'uom_id' => $row['uom_id'] ?? null,
                    'ordered_qty' => $row['ordered_qty'] ?? null,
                    'inspected_qty' => $row['inspected_qty'],
                    'accepted_qty' => $row['accepted_qty'],
                    'rejected_qty' => $row['rejected_qty'],
                    'status' => 'approved',
                    'remarks' => null,
                ]);

                // Inventory in for accepted qty
                $accepted = (float) $row['accepted_qty'];
                if ($accepted > 0) {
                    $bal = InventoryBalance::firstOrCreate([
                        'item_id' => $row['item_id'],
                        'warehouse_id' => $row['warehouse_id'] ?? null,
                        'bin_id' => $row['bin_id'] ?? null,
                    ], ['quantity' => 0]);
                    $bal->increment('quantity', $accepted);

                    InventoryMove::create([
                        'item_id' => $row['item_id'],
                        'warehouse_id' => $row['warehouse_id'] ?? null,
                        'bin_id' => $row['bin_id'] ?? null,
                        'quantity' => $accepted,
                        'direction' => 'in',
                        'reference_type' => 'inspection_request',
                        'reference_id' => $req->id,
                        'remarks' => 'Accepted via Inspection Request '.$req->request_number,
                    ]);
                }
            }

            // Close linked IGP
            $igp = GatePass::find($v['igp_id']);
            if ($igp) {
                $igp->update(['status' => 'closed']);
            }

            return redirect()->route('gatepasses.index')->with('success', 'Inspection Request created and inventory updated.');
        });
    }

    public function cancel(Request $request, InspectionRequest $inspectionRequest): RedirectResponse
    {
        $request->validate(['reason' => 'required|string|max:500']);
        if (!(auth()->id() === $inspectionRequest->created_by || auth()->user()?->hasRole('admin') || auth()->user()?->hasRole('superadmin'))) {
            return back()->withErrors(['error' => 'You are not authorized to cancel this inspection request.']);
        }
        if (!in_array($inspectionRequest->status, ['pending','approved'])) {
            return back()->withErrors(['error' => 'This inspection request cannot be cancelled in its current status.']);
        }
        $inspectionRequest->update(['status' => 'cancelled']);
        return back()->with('success', 'Inspection Request cancelled.');
    }
}


