<?php

namespace App\Http\Controllers;

use App\Http\Resources\factorsResoruce;
use App\Models\cunsumtion;
use App\Models\part;
use App\Models\purchase_factors;
use App\Models\factors;
use Illuminate\Http\Request;
use App\Http\Resources\PurchaseFactorResource;

class FactorsController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

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

     public function consume(Request $request)
    {
        foreach ($request->consume as $item) {
            $consume = new cunsumtion();
            $consume->user_id = auth()->id();
            $consume->description = $request->description;
            $consume->date = $request->date;
            $consume->part_code = $item['part_code'];
            $consume->station_code = $item['station_code'];
            $consume->qty = $item['qty'];
            $consume->unit = $item['unit'];
            $consume->save();
        }
      
        return response()->json(
            [
                "data"=> $consume,
                "message"=>"success",
                "status"=>true,
            ]);
    }
    
    
    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try{
        $request->validate([
            'code' => 'nullable',
            'type' => 'required',
            'date' => 'required|date',
            // 'user_id' => 'required|exists:users,id',
            'userid' => 'required',
            'description' => 'nullable|string|max:1000',
            'factors' => 'required',
            'factors.*.part_code' => 'required',
            'factors.*.qty' => 'required|numeric',
        ], [
            'type.required' => 'The invoice type is required.',
            'date.required' => 'The invoice date is required.',
            'userid.required' => 'The user is required.',
            // 'user_id.exists' => 'The selected user is not valid.',
            'description.max' => 'The description cannot exceed 1000 characters.',
            'factors.required' => 'Invoice details are required.',
            'factors.array' => 'Invoice details must be an array.',
            'factors.*.part_code.required' => 'The part code in the invoice details is required.',
            'factors.*.qty.required' => 'The quantity in the invoice details is required.',
            'factors.*.qty.numeric' => 'The quantity must be a number.',
            'factors.*.qty.min' => 'The quantity must be at least 1.',
        ]);
        $unit = "";
        $factor = new factors();
        $factor->factor_number = $request->code;
        $factor->type = $request->type;
        $factor->date = $request->date;
        $factor->vendor = $request->factors[0]['vendor'];
        $factor->user_id = auth()->id();
        $factor->description = $request->description;
        $factor->save();
        foreach ($request->factors as $factor_details) {
            $purchaseFactor = new purchase_factors();
            $part = part::where('id', $factor_details['part_code'])->first();
            if ($part) {
                $new_qty = intval($part->qty) + intval($factor_details['qty']);
                $part->qty += strval($new_qty);
                $part->save();
                $unit = $part->unit;
            } else {
                return response()->json(['error' => 'Part not found for code: ' . $factor['part_code']], 404);
            }
            $new_qty = intval($factor->qty) + intval($factor_details['qty']);
            $purchaseFactor->factor_id = $factor->id;
            $purchaseFactor->user_id = $factor->user_id;
            $purchaseFactor->part_code = $factor_details['part_code'];
            $purchaseFactor->qty = strval($new_qty);
            $purchaseFactor->unit = $unit;
            $purchaseFactor->save();
        }
        
        return response()->json(
            [
                "data" => $factor->load('purchase_factors'),
                "message" => "success",
                "status" => true,
            ]
        );
        }catch (IlluminateValidationValidationException $e) {
            return response()->json([
                "d" => "Validation Error",
                "errors" => $e->validator->errors(),
                "status" => false,
            ], 422);
    
        } catch (Exception $e) {
                return response()->json([
                    "message" => "An error occurred",
                    "error" => $e->getMessage(),
                    "status" => false,
                ], 500);
            }
    }

    /**
     * Display the specified resource.
     */
    public function show(factors $factors)
    {
      
      $factors = factors::select('factors.*', 'vendors.vname', 'users.username') 
            ->join('vendors', 'factors.vendor', '=', 'vendors.id')
            ->join('users', 'factors.user_id', '=', 'users.id')
            ->get();
      return response()->json([
                    "data" => $factors,
                    "message" => "success",
                    "status" => true,
                ], 201);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(factors $factors, $id)
    {
        // $data = new factorsResoruce(factors::find($id));
        // return $data; 
        return response()->json(
            [
                "data"=> factors::where('id',$id)->get(),
                // "details"=>purchase_factors::where('factor_id', $id)->get(),
                "details" => purchase_factors::select('purchase_factors.*', 'part_name')
                ->join('parts', 'purchase_factors.part_code', '=', 'parts.id')
                ->where('purchase_factors.factor_id', $id)
                ->get(),
                "message"=>"success",
                "status"=>true,
            ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, factors $factors, $id)
    {
        $test = [];
        try {
            $request->validate([
                'date' => 'required|date',
                // 'user_id' => 'required|exists:users,id',
                'userid' => 'required',
                'description' => 'nullable|string|max:1000',
                'factors' => 'required',
                'factors.*.part_code' => 'required',
                'factors.*.qty' => 'required|numeric',
            ], [
                'type.required' => 'The invoice type is required.',
                'date.required' => 'The invoice date is required.',
                'userid.required' => 'The user is required.',
                // 'user_id.exists' => 'The selected user is not valid.',
                'description.max' => 'The description cannot exceed 1000 characters.',
                'factors.required' => 'Invoice details are required.',
                // 'factors.array' => 'Invoice details must be an array.',
                'factors.*.part_code.required' => 'The part code in the invoice details is required.',
                'factors.*.qty.required' => 'The quantity in the invoice details is required.',
                'factors.*.qty.numeric' => 'The quantity must be a number.',
                // 'factors.*.qty.min' => 'The quantity must be at least 1.',
            ]);
            $factor = factors::find($id);
            $factor->factor_number = $request->code;
            $factor->type = "buy";
            $factor->vendor = $request->factors[0]['vendor'];
            $factor->date = $request->date;
            $factor->user_id = $request->user_id;
            $factor->description = $request->description;
            $factor->save();
            $details = purchase_factors::where('factor_id', $id)->get();
            foreach ($details as $detail) {
                $part = part::where('id', $detail['part_code'])->first();
                if ($part) {
                    $new_qty = intval($part->Qty) - intval($detail['qty']);
                        $part->Qty = strval($new_qty);
                        // array_push($test, $part);
                        $part->save();
                } else {
                    return response()->json(['error' => 'Part not found for code: ' . $factor['part_code']], 404);
                }
                
                $detail->delete();
            }
            // return $test;
                $new_qty = "";
            foreach ($request->factors as $factor_details) {
                $purchaseFactor = new purchase_factors();
                $part = part::where('id', $factor_details['part_code'])->first();
                if ($part) {
                    $new_qty = intval($part->Qty) + intval($factor_details['qty']);
                    $part->Qty = strval($new_qty);
                    // return $part->Qty;
                    $part->save();
                    $unit = $part->unit;
                } else {
                    return response()->json(['error' => 'Part not found for code: ' . $factor['part_code']], 404);
                }
                // $new_qty = intval($factor_details['qty']);
                $purchaseFactor->factor_id = $factor->id;
                // $purchaseFactor->user_id = $factor->user_id;
                $purchaseFactor->user_id = auth()-id();
                $purchaseFactor->part_code = $factor_details['part_code'];
                $purchaseFactor->qty = $factor_details['qty'];
                $purchaseFactor->vendor = $factor_details['vendor'];
                $purchaseFactor->price = $factor_details['price'];
                $purchaseFactor->totall_price = $factor_details['total'];
                $purchaseFactor->unit = $unit;
                $purchaseFactor->save();
            }
            return response()->json(
                [
                    "data" => $factor->load('purchase_factors'),
                    "message" => "success",
                    "status" => true,
                ]
            );
        } catch (IlluminateValidationValidationException $e) {
            return response()->json([
                "d" => "Validation Error",
                "errors" => $e->validator->errors(),
                "status" => false,
            ], 422);

        } catch (Exception $e) {
            return response()->json([
                "message" => "An error occurred",
                "error" => $e->getMessage(),
                "status" => false,
            ], 500);
        }
    }


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