<?php

namespace App\Http\Controllers\Vendor;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Admin\ParlourList;
use Illuminate\Support\Facades\Validator;
use App\Models\Admin\BasicSettings;
use Illuminate\Support\Arr;
use App\Models\Vendor\ParlourHasStuff;
use Exception;
use App\Constants\GlobalConst;


class StuffController extends Controller
{
    public function index()
    {
        $page_title      = "Staff";
        $vendor_id       = auth()->user()->id;
        $stuff           = ParlourHasStuff::with('parlour')->where('vendor_id', $vendor_id)->get();
        $parlour         = ParlourList::where('vendor_id', $vendor_id)->get();
        return view('vendor.sections.stuff-section.index', compact('page_title', 'stuff', 'parlour'));
    }
    public function create()
    {
        $page_title      = "Staff";
        $vendor_id = auth()->user()->id;
        $parlour_list = ParlourList::where('vendor_id', $vendor_id)->get();
        return view('vendor.sections.stuff-section.create', compact('page_title', 'parlour_list', 'vendor_id'));
    }


    public function getStuff()
    {
        return view('vendor.components.parlour-list.stuff-item');
    }

    /**
     * Method for store parlour list information
     * @param \Illuminate\Http\Request $request
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'vendor_id'  => 'required|integer',
            'stuff_name' => 'required|string',
            'address'    => 'required|string',
            'mobile'     => 'required|string',
            'image'      => 'required|mimes:png,jpg,jpeg,webp,svg',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput($request->all());
        }

        // Validate the request data
        $validated = $validator->validate();

        // Handle the image upload
        if ($request->hasFile('image')) {
            $validated['image'] = $this->imageValidate($request, 'image');
        }

        try {
            ParlourHasStuff::insert($validated);
        } catch (Exception $e) {
            return back()->with(['error' => ["Something went wrong. Please try again."]]);
        }

        return redirect()->route('vendors.stuff.index')->with(['success' => ["Stuff added successfully!"]]);
    }


    /**
     * Method for update the parlour list information
     * @param $slug
     * @param \Illuminate\Http\Request $request
     */
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'target'           => 'required',
            'stuff_name_edit'  => 'required|string',
            'address_edit'     => 'required|string',
            'mobile_edit'      => 'required|string|max:50',
        ]);

        $parlour_list = ParlourHasStuff::where('id', $request->target)->first();

        if ($validator->fails()) {
            return back()->withErrors($validator)->with("modal", "stuff-update");
        }

        $validated = $validator->validate();


        $data = [
            'stuff_name' => $validated['stuff_name_edit'],
            'address'    => $validated['address_edit'],
            'mobile'     => $validated['mobile_edit'],
        ];


        if ($request->hasFile('image')) {
            $data['image'] = $this->imageValidate($request, "image", null);
        }

        try {
            $parlour_list->update($data);
        } catch (Exception $e) {
            return back()->with(['error' => ['Something went wrong! Please try again.']]);
        }

        return redirect()->route('vendors.stuff.index')->with(['success' => ['Stuff Updated Successfully!']]);
    }


    /**
     * Method for delete the Stuff information
     * @param \Illuminate\Http\Request $request
     */
    public function delete(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'target'    => 'required|numeric',
        ]);

        $data   = ParlourHasStuff::find($request->target);
        try {
            $data->delete();
        } catch (Exception $e) {
            return back()->with(['error'    =>  ['Something went wrong. Please try again!']]);
        }
        return back()->with(['success'  =>  ['Stuff deleted successfully.']]);
    }

    public function showAssignForm()
    {
        $page_title      = "Assign stuff";
        $vendor_id = auth()->user()->id;
        $parlour_list = ParlourList::where('vendor_id', $vendor_id)->get();
        $parlour_has_stuff = ParlourHasStuff::where('vendor_id', $vendor_id)->where('status', true)->get();
        return view('vendor.sections.assign-stuff.create', compact('page_title', 'parlour_list', 'parlour_has_stuff'));
    }

    /**
     * Method for store parlour assign information
     * @param \Illuminate\Http\Request $request
     */
    public function storeAssign(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'parlour_list_id'  => 'required|integer',
            'stuff_name'       => 'required|array',
            'stuff_name.*'     => 'required|string',
        ]);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput($request->all());
        }

        $basic_setting = BasicSettings::first();

        $validated          = $validator->validate();

        $stuff_name     = $validated['stuff_name'];

        $validated      = Arr::except($validated, ['stuff_name']);
        if ($basic_setting->min_stuff) {
            if (count($stuff_name) > $basic_setting->min_stuff) {
                return back()->with(['error' => ['Minimum Number of Stuff is  ' . $basic_setting->min_stuff . '.']]);
            }
        }
        try {
            if (count($stuff_name) > 0) {
                foreach ($stuff_name as $key => $stuff_id) {
                    ParlourHasStuff::where('id', $stuff_id)->update([
                        'parlour_list_id' => $request->parlour_list_id,
                        'status'          => GlobalConst::STATUSASSIGN,
                        'updated_at'      => now(),
                    ]);
                }
            }
        } catch (Exception $e) {
            return back()->with(['error' => ["Something went wrong.Please try again."]]);
        }
        return redirect()->route('vendors.stuff.index')->with(['success' => ["stuff  Assigned Successfully!"]]);
    }

    /**
     * Method for booking log details
     * @param $trx_id
     * @param \Illuminate\Http\Request $request
     */
    public function details(Request $request, $id)
    {
        $page_title     = "Salon Details";
        $data           = ParlourList::with(['schedules', 'stuff', 'services', 'area', 'vendor', 'manager'])->where('id', $id)->first();

        if (!$data) return back()->with(['error' => ['Data Not Found!']]);

        return view('vendor.sections.parlour-list.details', compact(
            'page_title',
            'data',
        ));
    }


    /**
     * Method for image validate
     * @param string $slug
     * @param \Illuminate\Http\Request  $request
     */
    public function imageValidate($request, $input_name, $old_image = null)
    {
        if ($request->hasFile($input_name)) {
            $image_validated = Validator::make($request->only($input_name), [
                $input_name         => "image|mimes:png,jpg,webp,jpeg,svg",
            ])->validate();

            $image = get_files_from_fileholder($request, $input_name);
            $upload = upload_files_from_path_dynamic($image, 'stuff-profile', $old_image);
            return $upload;
        }
        return false;
    }
}
