<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\JobOrder;
use App\Models\JobOrderItem;
use App\Models\JobOrderSession;
use Illuminate\Http\Request;

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {

        $request->validate([
            'employee_id' => 'required|exists:employees,id',
            'orders' => 'required|array'
        ]);

        $jo = JobOrder::create([
            'created_by' => $request->employee_id,
            'order_no' => rand(100000, 999999)
        ]);

        foreach ($request->orders as $key => $order) {
            $jo_item = JobOrderItem::create([
                'job_order_id' => $jo->id,
                'service_category_id' => $order['service_category_id'],
                'service_category' => $order['service_category'],
                'service_name' => $order['service_name'],
                'standard_price' => $order['standard_price'],
                'list_price' => $order['list_price'],
                'sessions' => $order['sessions'],
            ]);

            if ($order['others']) {
                foreach (is_array($order['others']) ? $order['others'] : json_decode($order['others'], true) as $other) {
                    JobOrderSession::create([
                        'job_order_item_id' => $jo_item->id,
                        'session' => $other['session'],
                        'percent' => $other['percent'],
                        'amount' => $other['amount'],
                        'employees' => json_encode($other['employees'])
                    ]);
                }
            }

        }

        return $jo->order_no;
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        $jo = JobOrder::where('order_no', $id)->with('jobOrderItems','jobOrderItems.jobOrderSessions')->first();
        return $jo;
    }

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

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