<?php

namespace App\Http\Controllers;

use App\Models\cunsumtion;
use App\Models\part;
use Illuminate\Http\Request;
use App\Http\Resources\CosumtionResource;
class CunsumtionController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // return (cunsumtion::with("station")->orderBy("date", "desc")->get());
   
return cunsumtion::leftJoin('users', 'cunsumtions.user_id', '=', 'users.id')
    ->leftJoin('stations', 'cunsumtions.station_code', '=', 'stations.id')
    ->leftJoin('parts', 'cunsumtions.part_code', '=', 'parts.id')
    ->select('cunsumtions.*', 'users.username', 'stations.station_name', 'parts.part_name') 
    ->orderBy('cunsumtions.date', 'desc')
    ->get();

    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {

    }
    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        // Validate inputs with custom error messages
        $request->validate([
            // 'user_id' => 'required|exists:users,id',
            'description' => 'string|max:255',
            'date' => 'required|date',
            'consume' => 'required|array',
            'consume.*.part_code' => 'required|exists:parts,id',
            'consume.*.qty' => 'required|numeric|min:0',
        ], [
            // 'user_id.exists' => 'The selected user ID is invalid.',
            // 'description.required' => 'The description is required.',
            'description.string' => 'The description must be a string.',
            'description.max' => 'The description may not be greater than 255 characters.',
            'date.required' => 'The date is required.',
            'date.date' => 'The date is not a valid date.',
            'consume.required' => 'The consume field is required.',
            // 'consume.array' => 'The consume field must be an array.',
            'consume.*.part_code.required' => 'The part code is required for each consume item.',
            'consume.*.part_code.exists' => 'The selected part code is invalid.',
            'consume.*.qty.required' => 'The quantity is required for each consume item.',
            'consume.*.qty.numeric' => 'The quantity must be a number.',
            'consume.*.qty.min' => 'The quantity must be at least 0.',
        ]);

        $accepted = [];

        foreach ($request->consume as $item) {
            $consumption = new cunsumtion();
            $part = Part::where('id', $item['part_code'])->first();
            $qtyFromRequest = floatval($item['qty']);
            $currentQty = floatval($part->Qty);

            if ($currentQty < $qtyFromRequest) {
                return response()->json([
                    'message' => 'Error: Not enough quantity available for part "' . $part->part_name . '". Requested quantity: ' . $qtyFromRequest . ', Available quantity: ' . $currentQty,
                    "data" => $accepted,
                    "notice" => "Accepted consumptions are present in the data!",
                ], 400);
            }

            $newQty = $currentQty - $qtyFromRequest;
            $part->Qty = $newQty;
            $part->save(); 

            $consumption->user_id = auth()->id();
            $consumption->description = $request->description;
            $consumption->date = $request->date;
            $consumption->station_code = $item['station_code'];
            $consumption->part_code = $item['part_code'];
            $consumption->qty = $item['qty'];

            $consumption->save();
            $accepted[] = $consumption;
        }

        return response()->json([
            "data" => $accepted,
            "message" => "Operation completed successfully.",
            "status" => true,
        ]);
    }

    /**
     * Display the specified resource.
     */
    public function show(cunsumtion $cunsumtion)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(cunsumtion $cunsumtion, $id)
    {
        $consumption = cunsumtion::find($id);
         return response()->json([
            "data" => $consumption,
            "message" => "success",
            "status" => true,
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, cunsumtion $cunsumtion, $id)
    {
         $request->validate([
            // 'user_id' => 'required|exists:users,id',
            'userid' => 'required',
            'description' => 'string|max:255',
            'date' => 'required|date',
            'consume' => 'required|array',
            'consume.*.part_code' => 'required|exists:parts,id',
            'consume.*.qty' => 'required|numeric|min:0',
        ], [
            'userid.required' => 'The username is required.',
            // 'user_id.exists' => 'The selected user ID is invalid.',
            // 'description.required' => 'The description is required.',
            'description.string' => 'The description must be a string.',
            'description.max' => 'The description may not be greater than 255 characters.',
            'date.required' => 'The date is required.',
            'date.date' => 'The date is not a valid date.',
            'consume.required' => 'The consume field is required.',
            // 'consume.array' => 'The consume field must be an array.',
            'consume.*.part_code.required' => 'The part code is required for each consume item.',
            'consume.*.part_code.exists' => 'The selected part code is invalid.',
            'consume.*.qty.required' => 'The quantity is required for each consume item.',
            'consume.*.qty.numeric' => 'The quantity must be a number.',
            'consume.*.qty.min' => 'The quantity must be at least 0.',
        ]);

        $accepted = [];

        foreach ($request->consume as $item) {
            $consumption = cunsumtion::find($id);
            $part = Part::where('id', $item['part_code'])->first();

            $lastqty = $consumption->qty;
            $qtyFromRequest = floatval($item['qty']);
            $currentQty = floatval($part->Qty);
            $new_qty = $qtyFromRequest - $lastqty;
            $new_qty = $currentQty - $new_qty;
            if ($new_qty < 0) {
                return response()->json([
                    'message' => 'Error: Not enough quantity available for part "' . $part->part_name . '". Requested quantity: ' . $qtyFromRequest . ', Available quantity: ' . $currentQty,
                    "data" => $accepted,
                    "notice" => "Accepted consumptions are present in the data!",
                ], 400);
            }
            $part->Qty = $new_qty;
            $part->save();

            $consumption->user_id = $request->userid;
            $consumption->description = $request->description;
            $consumption->date = $request->date;
            $consumption->station_code = $item['station_code'];
            $consumption->part_code = $item['part_code'];
            $consumption->qty = $item['qty'];

            $consumption->save();
            $accepted[] = $consumption;
        }

        return response()->json([
            "data" => $accepted,
            "message" => "Operation completed successfully.",
            "status" => true,
        ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(cunsumtion $cunsumtion)
    {
        //
    }
}
