<?php

namespace App\Http\Controllers\Medicine;

use App\Helpers\ValidationHelper;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\LeafSetting;
use App\Models\Medicine;
use App\Models\Supplier;
use App\Models\Type;
use App\Models\Unit;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Validator;
use Mockery\Exception;

class MedicineController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $medicines = Medicine::query()->where('user_id', '=', Auth::id());
            if ($request->has('search')) {
                $q = $request->get('search');
                $medicines->where('medicine_name', 'LIKE', "%$q$");
            }
            if ($request->has('category_id')) {
                $medicines->where('category_id', $request->get('category_id'));
            }
            if ($request->has('medicine_company_id')) {
                $medicines->where('medicine_company_id', $request->get('medicine_company_id'));
            }
            if($request->has('order_by')){
                if($request->order_by == 'oldest'){
                    $medicines->orderBy('id', 'ASC');
                } elseif($request->order_by == 'newest'){
                    $medicines->orderBy('id', 'DESC');
                } elseif ($request->order_by == 'asc_price'){
                    $medicines->orderBy('supplier_price', 'ASC');
                } elseif ($request->order_by == 'desc_price'){
                    $medicines->orderBy('supplier_price', 'DESC');
                }
            } else {
                $medicines->orderBy('id', 'DESC');
            }


            $medicines = $medicines->paginate(20);
            return successResponseWithData($medicines, 'success', 200);
        } catch (Exception $exception) {
            return errorResponse($exception, 500);
        }
    }

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

    /**
     * Show the form for creating a new resource.
     */
    public function all_active_categorical_data(): JsonResponse
    {
        try {
            return successResponseWithData([
                'leaf_settings' => LeafSetting::query()->where(['user_id' => Auth::id()])->orderBy('id', 'DESC')->get(['id', 'leaf_type', 'total_number']),
                //                'units' => Unit::query()->where(['user_id' => Auth::id(), 'status' => '1'])->orderBy('id', 'DESC')->get(['id', 'unit_name']),
                'categories' => Category::query()->where(['user_id' => Auth::id(), 'status' => '1'])->orderBy('id', 'DESC')->get(['id', 'category_name']),
                //                'types' => Type::query()->where(['user_id' => Auth::id(), 'status' => '1'])->orderBy('id', 'DESC')->get(['id', 'type_name']),
                'suppliers' => Supplier::query()->with('medicineCompany:id,company_name')->where(['user_id' => Auth::id()])->orderBy('id', 'DESC')->get(['id', 'medicine_company_id', 'supplier_name', 'supplier_email']),
            ], 'success', 200);
        } catch (Exception $exception) {
            return errorResponse($exception, 500);
        }
    }

    public function validation($request): Validator
    {
        return ValidationHelper::validator($request, [
            'leaf_setting_id' => 'required|integer|exists:leaf_settings,id',
            //            'unit_id' => 'required|integer|exists:units,id',
            'category_id' => 'required|integer|exists:categories,id',
            //            'type_id' => 'required|integer|exists:types,id',
            'medicine_company_id' => 'required|integer|exists:medicine_companies,id',
//            'shelf_id' => 'required|integer|exists:shelves,id',
            'medicine_name' => 'required',
            'image' => 'image|extensions:jpg,png,jpeg',
            'box_mrp' => 'required',
            'supplier_price' => 'required',
            //            'status' => 'required',
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): JsonResponse
    {
        $validator = $this->validation($request);
        if ($validator->fails()) {
            return validationErrorResponse($validator);
        }

        try {
            return successResponseWithData(Medicine::newMedicine($request), 'Create successfully', 201);
        } catch (Exception $exception) {
            return errorResponse($exception, 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id): JsonResponse
    {
        try {
            return successResponseWithData(Medicine::query()->find($id), 'success', 200);
        } catch (Exception $exception) {
            return errorResponse($exception, 500);
        }
    }

    public function change_status(string $id): JsonResponse
    {
        try {
            return successResponse(Medicine::change_status($id), 200);
        } catch (Exception $exception) {
            return errorResponse($exception, 500);
        }
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id): JsonResponse
    {
        try {
            return successResponseWithData(Medicine::query()->find($id), 'success', 200);
        } catch (Exception $exception) {
            return errorResponse($exception, 500);
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id): JsonResponse
    {
        $validator = $this->validation($request);
        if ($validator->fails()) {
            return validationErrorResponse($validator);
        }

        try {
            return successResponseWithData(Medicine::updateMedicine($request, $id), 'Update successfully', 200);
        } catch (Exception $exception) {
            return errorResponse($exception, 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id): JsonResponse
    {
        try {
            $medidcine = Medicine::query()->find($id);
            if (file_exists($medidcine->image)) {
                if ($medidcine->image != 'storage/dummy.webp') {
                    unlink($medidcine->image);
                }
            }
            $medidcine->delete();

            return successResponse('Delete success', 200);
        } catch (Exception $exception) {
            return errorResponse($exception, 500);
        }
    }
}
