<?php

namespace App\Http\Controllers;

use App\Http\Helpers\FileUploader;
use App\Models\Rating;
use App\Models\Service;
use App\Models\ServiceOrder;
use App\Notifications\ServiceOrderNotification;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Stripe\Review;

class ServiceOrderController extends Controller
{
    public function __construct()
    {
        $this->middleware('service-orders');
    }
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        //
    }

    public function store(Request $request)
    {
        
        try {
            $transaction = DB::transaction(function () use ($request) {
                $service = Service::find($request->service_id);
                $serviceOrder = $request->user()->serviceOrders()->create($request->validate([
                    'service_id' => ['required', Rule::exists('services', 'id')],
                    'tier' => ['int', 'min:0', 'max:2'],
                ]));
                $serviceOrder->addMilestone([
                    'name' => $service->title,
                    'amount' => $service->getTierPrice($request->tier),
                    'duration' => $service->getTierDuration($request->tier),
                    'deliverables' => array_values($service->tierOptions()->where($service->getTierEnabled($request->tier), true)->get('title as name')->toArray()),
                ]);
                
                $milestone = $serviceOrder->milestones()->get()->first();
                if($request->client_signature){
                    $request['client_signature'] = FileUploader::storeBase64('signatures/', $request->client_signature);
                }
                $session = $milestone->pay($request->client_signature, $request->use_wallet);
                return $session ? Inertia::location($session['url']) : back(303)->with(["success" => "success"]);
                    });
                    return is_null($transaction)
                        ? back(303)->with(["success" => "success"])
                        : $transaction;
                } catch (Exception $exception) {
                    return redirect()->back()->withErrors(["error" => $exception->getMessage()])->with(["error" => $exception->getMessage()]);
                }
    }

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

    /**
     * Display the specified resource.
     *
     * @param ServiceOrder $serviceOrder
     * @return Response
     */
    public function show(ServiceOrder $serviceOrder)
    {
        $service = $serviceOrder->service;

        $service->load([
            "images",
            "skills",
            "location",
            "tierOptions",
            "serviceable" => ['user', 'location'],
        ]);

        $milestone = $serviceOrder->milestones?->first?->get()?->load([
            "files",
            "deliverables",
            "transaction"
        ]);

        // dd($service);

        // this user's reviews
        $review = Rating::where('user_id', $serviceOrder->user?->id)->where('rateable_id', $service->id)->where('rateable_type', 'App\Models\Service')->with('user')->first();
        $service['user_rates'] = $review ?  [$review] : null;
        return Inertia::render('ServiceOrders/Index',[
           "service"=> $service,
            "order"=>$serviceOrder,
            "milestone"=>$milestone,
            "isUser"=> $serviceOrder->user?->id === Auth::user()?->id,
            "user"=>$serviceOrder->user,
            "worker"=>$serviceOrder->service->serviceable,
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param ServiceOrder $serviceOrder
     * @return Response
     */
    public function edit(ServiceOrder $serviceOrder)
    {
        //
    }


    public function update(Request $request)
    {
        // TODO:: is this updatable ?
        $order = ServiceOrder::find($request->id);

    }


    public function destroy(ServiceOrder $serviceOrder)
    {
        $serviceOrder->delete();
        return back(303)->with(['success' => 'success']);
    }
}
