<?php

namespace App\Http\Controllers;

use App\Http\Requests\addOrEditServiceRequest;
use App\Http\Requests\GetServiceRequest;
use App\Http\Requests\MachineRequest;
use App\Models\Category;
use App\Models\Service;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

class ServicesController extends Controller
{
    /**
     * @var bool
     */
    private bool $api_call;
    /**
     * @brief assign true|false to $api_call by checking if the request is an API call
     *
     * @return \Illuminate\Contracts\View\View|string
     */
    public function __construct() {
        $this->api_call = request()->header('Accept') == "application/json";
    }

    /**
     * @brief fetching the required data and respond properly
     *
     * @return \Illuminate\Contracts\View\View|string
     */
    public function index() {
        if (isAdmin()) {
            // throw a 403 error if the request is an API call
            if ($this->api_call) {
                auth()->logout();
                throwForbiddenError(['errors' => ['Admin is forbidden to access this content via the API']]);
                exit();
            }
            // fetch the required content and retrieve it with the proper view
            return view('v1/02_dash-template/admin-pages/services', ['services'=>Service::join('categories', 'services.category_id', '=', 'categories.id')
                                                                                    ->select('services.id as sid', 'services.title as s_title', 'categories.title as c_title', 'icon', 'parent', 'children', 'stared', 'hourly_rate', 'daily_rate', 'quantity_per_day as qpd', 'mid')->get(),
                                                                          'categories'=>Category::get()]);
        } else {
            // fetching the required content in an array
            $result = Service::join('categories', 'services.category_id', '=', 'categories.id')
                             ->select('services.id as sid', 'services.title as s_title', 'categories.title as c_title', 'icon', 'hourly_rate', 'daily_rate', 'quantity_per_day as qpd', 'excerpt', 'description')
                             ->get();
            // delivering the proper response
            return !$this->api_call ?
                view('v1/02_dash-template/customer-pages/services', ['services'=>$result]) :
                successfulResponse($result);
        }
    }

    /**
     * @brief adds or edits a service
     *
     * @param addOrEditServiceRequest $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function addOrEditService(addOrEditServiceRequest $request) {
//        dd($request);
        if (isAdmin()) {
            /**
             * deciding weather to add or edit a service
             */
            $service = isset($request->id) ? Service::find($request->id) : new Service;
            /**
             * easy assignments
             */
            $service->title       = $request->title;
            $service->category_id = $request->category_id;
            $service->daily_rate  = $request->daily_rate;
            $service->hourly_rate = $request->hourly_rate;
            $service->stared      = isset($request->stared) ? 1 : 0;
            $service->excerpt     = $request->excerpt;
            $service->description = $request->details;
            $service->quantity_per_day = $request->quantity;
            /**
             * conditional assignments
             */
            if ($request->parent_id > 0)
                $service->parent = json_encode(Service::where('id', $request->parent_id)->select('id', 'title')->get(), JSON_UNESCAPED_UNICODE);

            if ($request->children_ids)
                foreach ($request->children_ids as $child_id) {
                    if ($child_id != 0) {
                        $service->children = json_encode(Service::whereIn('id', $request->children_ids)->select('id', 'title')->get(), JSON_UNESCAPED_UNICODE);
                        break;
                    }
                }

            if (isset($request->mid))
                if (strlen($request->mid) > 3)
                    $service->mid = $request->mid;

            /**
             * saving...
             */
            $service->save();
            return back()->with('msg', 'عملیات با موفقیت انجام شد');
        } else {

        }
    }

    /**
     * @brief fetching the required data and respond properly
     *
     * @param GetServiceRequest $request
     *
     * @return string
     */
    public function getServiceDetails(GetServiceRequest $request) {
        $result = Service::join('categories', 'services.category_id', '=', 'categories.id')
                         ->where("services.id", "=", $request->id)
                         ->select('services.id as sid', 'categories.id as cid', 'services.title as s_title', 'categories.title as c_title', 'parent', 'children', 'stared', 'hourly_rate', 'daily_rate', 'quantity_per_day as qpd', 'excerpt', 'description', 'mid')
                         ->get()[0];
        return $result;
    }

}
