<?php

namespace App\Http\Controllers;

use App\Models\purchase_order;
use Illuminate\Http\Request;

class PurchaseOrderController extends Controller
{
    /**
     * Display a listing of the resource.
     */
        // return purchase_order::all();
//         use App\Models\PurchaseOrder;
// use Illuminate\Support\Facades\DB;
    public function index()
    {
        // دریافت همه رکوردها، اما فقط رکوردهای منحصربه‌فرد بر اساس part_name, part_code, price
        $result = purchase_order::select('invoce_no', 'part_name', 'part_code', 'price', 'created_at', 'station_id', 'user_id')
            ->distinct()
            ->get();
    
        return $result;
    }

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

    }

    /**
     * Store a newly created resource in storage.
     */
   public function store(Request $request)
    {
        $accepted = [];
        foreach ($request->details as $key => $value) {
            $order = new purchase_order();
            $order->order_id = now()->format('YmdHis');
            $order->invoce_no = $request->invoice_no;
            $order->station_id = $request->station;
            $order->user_id = auth()->id();
            $order->vendor = $request->selectedVendor;
            $order->description = $request->description;
            // بررسی وجود selectedPart و id
            if (isset($request->details[$key]['selectedPart'])) {
                $selectedPart = $request->details[$key]['selectedPart'];
                $order->part_name = $selectedPart; // استفاده از title اگر id وجود داشته باشد
                $order->part_code = $request->details[$key]['part_code'];
            } else {
                // اگر selectedPart وجود نداشته باشد
                $order->part_name = $request->details[$key]['part_code'];
                $order->part_code = $request->details[$key]['part_code'];
            }
    
            $order->qty = $request->details[$key]['qty'];
            $order->price = $request->details[$key]['price'];
            $order->paid = $request->details[$key]['paid'];
            $order->recived = $request->details[$key]['recived'];
            $order->save();
            array_push($accepted, $order);
        }
        return $accepted;
    }

    /**
     * Display the specified resource.
     */
    public function show(purchase_order $purchase_order)
    {
        $purchaseOrders = purchase_order::join('users', 'purchase_orders.user_id', '=', 'users.id')
        ->join('vendors', 'purchase_orders.vendor', '=', 'vendors.id')
        ->join('stations', 'purchase_orders.id', '=', 'stations.id')
        ->select('purchase_orders.*', 'users.username as username', 'vendors.vname as vname', 'stations.station_name')
        ->get();
       $result = $purchaseOrders->sortByDesc('created_at')->groupBy('order_id')->map(function ($group) {
            return $group->first();
        })->values()->toArray();
        return response()->json([
            "data" => $result,
            "message" => "success",
            "status" => true,
        ]);
    }

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, purchase_order $purchase_order, $id)
    {

    // اعتبارسنجی داده‌ها
        $request->validate([
            'invoice_no' => 'required|string',
            'selectedVendor' => 'required|integer',
            'description' => 'nullable|string',
            'details' => 'required|array',
            'details.*.selectedPart' => 'required', // فرض بر این است که selectedPart به عنوان نام پارت ارسال می‌شود
            'details.*.part_code' => 'required|string',
            'details.*.qty' => 'required|integer',
            'details.*.price' => 'required|numeric',
            'details.*.paid' => 'required|boolean',
            'details.*.recived' => 'required|boolean',
        ]);

        // پیدا کردن سفارش بر اساس ID
        $order = purchase_order::where('order_id', '=', $id);
        $order->delete();
        $accepted = [];


        foreach ($request->details as $key => $value) {
            $order = new purchase_order();
            $order->order_id = now()->format('YmdHis');
            $order->invoce_no = $request->invoice_no;
            $order->user_id = auth()->id();
            $order->vendor = $request->selectedVendor;
            $order->description = $request->description;
            $order->part_name = $request->details[$key]['selectedPart'];
            $order->part_code = $request->details[$key]['part_code'];
            $order->qty = $request->details[$key]['qty'];
            $order->price = $request->details[$key]['price'];
            $order->paid = $request->details[$key]['paid'];
            $order->recived = $request->details[$key]['recived'];
            $order->save();
            array_push($accepted, $order);
        }

        return response()->json($accepted);
    }

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