<?php

namespace App\Http\Controllers\Api\V1\Vendor;

use App\Http\Controllers\Controller;
use App\Models\Vendor\ParlourHasStuff;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Http\Helpers\Api\Helpers as ApiResponse;
use Exception;
use App\Models\Admin\BasicSettings;
use App\Constants\GlobalConst;

class StuffController extends Controller
{

    public function index()
    {
        $vendor_id          = auth()->user()->id;
        $stuff               = ParlourHasStuff::with('parlour')->where('vendor_id', $vendor_id)->get();
        $stuff_image_path   = [
            'base_url'      => url('/'),
            'path_location' => files_asset_path_basename('stuff-profile'),
            'default_image' => files_asset_path_basename('default')
        ];
        $data = [
            'status'                =>'1 = free , 2 = assigned',
            'stuff-image-path'    => $stuff_image_path,
            'data'               => $stuff
        ];
        $message =  ['success' => [__('Stuff List')]];
        return ApiResponse::success($message, $data);
    }

      /**
     * Method to register a new stuff (API Compatible)
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        // Validate the incoming 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()) {
            $error = ['error' => [$validator->errors()->all()]];
            return ApiResponse::onlyValidation($error);
        }

        // Prepare validated data
        $validated = $validator->validated();

        $validated['stuff_name'] =  $request->stuff_name;
        $validated['address'] =  $request->address;
        $validated['vendor_id'] = $request->vendor_id;
        $validated['mobile'] = $request->mobile;

        if ($request->hasFile('image')) {
            $image = upload_file($validated['image'], 'stuff-profile');
            $upload_image = upload_files_from_path_dynamic([$image['dev_path']], 'stuff-profile');
            delete_file($image['dev_path']);
            $validated['image']     = $upload_image;
        }

        try {
            // Create the stuff
            $stuff = ParlourHasStuff::create($validated);

            $data = [
                'stuff' => $stuff,
            ];
            $message    =  ['success' => [__('Stuff registered successfully')]];
            return ApiResponse::success($message, $data);
        } catch (Exception $e) {
            $message =  ['error' => [__('Something went wrong! Please try again')]];
            return ApiResponse::onlyError($message);
        }
    }

    /**
     * Method for deleting the stuff information (API).
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete($slug)
    {
        try {

            $stuff = ParlourHasStuff::find($slug);

            if (!$stuff) {
                $message = ['error' => [__('Stuff not found')]];
                return ApiResponse::onlyError($message);
            }


            $stuff->delete();


            $data = ['Stuff' => $stuff];
            $message = ['success' => [__('Stuff deleted successfully')]];
            return ApiResponse::success($message, $data);
        } catch (Exception $e) {

            $message = ['error' => [__('Something went wrong! Please try again')]];
            return ApiResponse::onlyError($message);
        }
    }

     /**
     * Profile Update
     * @method POST
     * @param Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // Find the stuff
        $stuff = ParlourHasStuff::find($id);
        if (!$stuff) {
            $message = ['error' => [__('Stuff not found')]];
            return ApiResponse::onlyError($message);
        }

        // Validate the incoming request
        $validator = Validator::make($request->all(), [
            'stuff_name' => 'required|string',
            'address'    => 'required|string',
            'mobile'     => 'required|string',
            'image'      => 'nullable|mimes:png,jpg,jpeg,webp,svg',
        ]);

        if ($validator->fails()) {
            $error = ['error' => [$validator->errors()->all()]];
            return ApiResponse::onlyValidation($error);
        }

        // Prepare validated data
        $validated = $validator->validated();

        $validated['stuff_name'] = $request->stuff_name;
        $validated['address']    = $request->address;
        $validated['mobile']     = $request->mobile;

        // Handle image upload if a new image is provided
        if ($request->hasFile('image')) {
            $image = upload_file($validated['image'], 'stuff-profile');
            $upload_image = upload_files_from_path_dynamic([$image['dev_path']], 'stuff-profile');
            delete_file($image['dev_path']);
            $validated['image'] = $upload_image;
        }

        try {
            // Update the stuff
            $stuff->update($validated);

            $data = [
                'stuff' => $stuff,
            ];
            $message = ['success' => [__('Stuff successfully updated')]];
            return ApiResponse::success($message, $data);
        } catch (Exception $e) {
            $message = ['error' => [__('Something went wrong! Please try again')]];
            return ApiResponse::onlyError($message);
        }
    }


    /**
 * Method for storing parlour assign information (API).
 *
 * @param \Illuminate\Http\Request $request
 * @return \Illuminate\Http\JsonResponse
 */
public function stuffAssign(Request $request)
{
    // Validate the incoming request
    $validator = Validator::make($request->all(), [
        'parlour_list_id'  => 'required|integer',
        'stuff_id'       => 'required|array',
        'stuff_id.*'     => 'required|integer',
    ]);

    if ($validator->fails()) {
        $error = ['error' => $validator->errors()->all()];
        return ApiResponse::onlyValidation($error);
    }

    $basic_setting = BasicSettings::first();
    $validated     = $validator->validated();

    $stuff_name    = $validated['stuff_id'];

    // Check minimum stuff condition
    if ($basic_setting && $basic_setting->min_stuff) {
        if (count($stuff_name) > $basic_setting->min_stuff) {
            $message = ['error' => [__('Minimum number of stuff is ') . $basic_setting->min_stuff . '.']];
            return ApiResponse::onlyError($message);
        }
    }

    try {
        // Assign stuff to parlour
        foreach ($stuff_name as $stuff_id) {
            ParlourHasStuff::where('id', $stuff_id)->update([
                'parlour_list_id' => $validated['parlour_list_id'],
                'status'          => GlobalConst::STATUSASSIGN,
                'updated_at'      => now(),
            ]);
        }

        $message = ['success' => [__('Stuff assigned successfully!')]];
        return ApiResponse::onlySuccess($message);
    } catch (Exception $e) {
        $message = ['error' => [__('Something went wrong! Please try again.')]];
        return ApiResponse::onlyError($message);
    }
}


}
