<?php

namespace App\Http\Controllers\Api;

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

class JobOrderController extends Controller
{

    public function store (Request $request)
    {
        $request->validate([
            'artist_id' => 'required|exists:users,id'
        ]);

        $request->request->add([
            'order_no' => rand(100000, 999999)
        ]);

        $jo = JobOrder::create($request->all());

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

        return $jo->order_no;
    }

    public function show (Request $request, $id)
    {
        if ($request->search) {
            $request->validate([
                'order_no' => 'required|exists:job_orders,order_no'
            ]);
        }

        $jo = JobOrder::where('order_no', $id)->first();
        $items = JobOrderItem::where('job_order_id', $jo->id)->get();
        $payments = Payment::where('job_order_id', $jo->id)->get();

        return [
            'job_order' => $jo,
            'items' => $items,
            'payments' => $payments,
        ];
    }

    public function update (Request $request, $id)
    {
        if ($request->customer) {
            $request->validate([
                'customer_name' => 'required',
                'mobile_no' => 'required',
                'email' => 'required|email'
            ]);

            $jo = JobOrder::find($id);
            $jo->update($request->all());
            return 1;
        }

        if ($request->verify) {
            $request->validate([
                'otp' => 'required|exists:one_time_pins,otp'
            ]);

            $jo = JobOrder::find($id);
            $jo->status = 'Confirmed';
            $jo->save();
            return 'A';
        }
    }

}
