<?php

namespace App\Http\Controllers;

use App\Models\POParts;
use App\Http\Resources\POPartsResource;
use Illuminate\Http\Request;

class POPartsController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $parts = POParts::all()->select('part_name', 'part_number');
        return $parts;
    }

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $part = new POParts();
        $part->part_name = $request->part_name;
        $part->part_number = $request->part_code;
        $part->isdeleted = false;
        $part->description = $request->description;
        $part->save();
        return response()->json(
            [
                "data" => $part,
                "message" => "success",
                "status" => true,
            ]
        );
    }

    /**
     * Display the specified resource.
     */
    public function show(POParts $pOParts)
    {
        $data = POParts::all();
        return response()->json(
            [
                "data" => POPartsResource::collection($data),
                "message" => "success",
                "status" => true,
            ]
        );
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(POParts $pOParts, Request $request, $id)
    {
        $data = $pOParts::where('id', $id)->get();
        return response()->json(
            [
                "data" => $data,
                "message" => "success",
                "status" => true,
            ]
        );
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, POParts $pOParts, $id)
    {
        // پیدا کردن رکورد با استفاده از find
        $data = $pOParts::find($id);
    
        // بررسی وجود رکورد
        if (!$data) {
            return response()->json([
                "message" => "Record not found",
                "status" => false,
            ], 404);
        }
    
        // به‌روزرسانی فیلدها
        $data->update([
            'part_name' => $request->part_name,
            'part_number' => $request->part_number,
            'isdeleted' => false,
            'description' => $request->description,
        ]);
    
        return response()->json([
            "data" => $data,
            "message" => "success",
            "status" => true,
        ]);
    }
    /**
     * Remove the specified resource from storage.
     */
    public function destroy(POParts $pOParts)
    {

    }
}
