<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\ServiceRequest;
use App\Http\Resources\Api\CategoryResource;
use App\Http\Resources\Api\ChildrenResource;
use App\Http\Resources\Api\CourseResource;
use App\Http\Resources\Api\EventsResource;
use App\Http\Resources\Api\ServiceResource;
use App\Http\Resources\Api\SliderResource;
use App\Http\Resources\Api\SubscriptionResource;
use App\Models\Absence;
use App\Models\Category;
use App\Models\Child;
use App\Models\Course;
use App\Models\Event;
use App\Models\Slider;
use App\Models\Subscription;
use App\Models\Wallet;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class HelperController extends Controller
{
    public function categories(Request $request)
    {

        $result = Category::OrderBy('id', 'asc')->where('status', true);

        if (isset($request->search)) {
            $result->where(function ($q) use ($request) {
                $q->where('name_ar', 'like', '%' . $request->search . '%')->Orwhere('name_en', 'like', '%' . $request->search . '%');
            });
        }
        $data = CategoryResource::collection($result->get())->response()->getData(true);;
        return msgdata(true, trans('lang.data_display_success'), $data, success());
    }
    public function sliders(Request $request)
    {

        $result = Slider::OrderBy('id', 'asc')->where('status',true);

        if (isset($request->search)) {
            $result->where(function ($q) use ($request) {
                $q->where('name_ar', 'like', '%' . $request->search . '%')->Orwhere('name_en', 'like', '%' . $request->search . '%');
            });
        }
        $data = SliderResource::collection($result->get())->response()->getData(true);;
        return msgdata(true, trans('lang.data_display_success'), $data, success());
    }

    public function services(Request $request)
    {

        $result = Category::OrderBy('id', 'asc')->where('status', true);
        if(isset($request->category_id)){
            $result->where('category_id', $request->category_id);
        }
        if(isset($request->type)){
            $result->where('type', $request->type);
        }

        if (isset($request->search)) {
            $result->where(function ($q) use ($request) {
                $q->where('name_ar', 'like', '%' . $request->search . '%')->Orwhere('name_en', 'like', '%' . $request->search . '%');
            });
        }
        $data = ServiceResource::collection($result->get())->response()->getData(true);;
        return msgdata(true, trans('lang.data_display_success'), $data, success());
    }
    public function events(Request $request)
    {

        $result = Event::OrderBy('id', 'asc')->where('status', true);
        if(isset($request->category_id)){
            $result->where('category_id', $request->category_id);
        }
        if (isset($request->search)) {
            $result->where(function ($q) use ($request) {
                $q->where('name_ar', 'like', '%' . $request->search . '%')->Orwhere('name_en', 'like', '%' . $request->search . '%');
            });
        }
        $data = EventsResource::collection($result->get())->response()->getData(true);;
        return msgdata(true, trans('lang.data_display_success'), $data, success());
    }
    public function myEvents(Request $request)
    {

        $parent = Auth::guard('api')->user();

        $subscriptions = $parent->subscriptions()->with('event')->get();

        $upcomingEvents = $subscriptions->filter(function ($subscription) {
            return $subscription->event && $subscription->event->date > Carbon::now();
        })->pluck('event');

        $oldEvents = $subscriptions->filter(function ($subscription) {
            return $subscription->event && $subscription->event->date <= Carbon::now();
        })->pluck('event');
        $upcomingEventsPaginated = $this->paginateCollection($upcomingEvents, 10); // 10 per page
        $oldEventsPaginated = $this->paginateCollection($oldEvents, 10);

        $data['upcoming_events'] = EventsResource::collection($upcomingEventsPaginated)->response()->getData(true);
        $data['old_events'] = EventsResource::collection($oldEventsPaginated)->response()->getData(true);


        return msgdata(true, trans('lang.data_display_success'), $data, success());
    }
    public function myCourses(Request $request)
    {

        $parent = Auth::guard('api')->user();

        $subscriptions = $parent->courseSubscriptions()->with('course')->select('course')->paginate(10);

        return msgdata(true, trans('lang.data_display_success'), $subscriptions, success());
    }

    public function courses(Request $request)
    {

        $result = Course::OrderBy('id', 'asc')->where('status', true);
        if(isset($request->category_id)){
            $result->where('category_id', $request->category_id);
        }else{
            $result->where('category_id', 3);
        }
        if (isset($request->search)) {
            $result->where(function ($q) use ($request) {
                $q->where('name_ar', 'like', '%' . $request->search . '%')->Orwhere('name_en', 'like', '%' . $request->search . '%');
            });
        }
        $data = CourseResource::collection($result->get())->response()->getData(true);;
        return msgdata(true, trans('lang.data_display_success'), $data, success());
    }
    public function subscription(Request $request)
    {

        $result = Subscription::OrderBy('id', 'asc')->where('status', true);

        $data = SubscriptionResource::collection($result->get())->response()->getData(true);;
        return msgdata(true, trans('lang.data_display_success'), $data, success());
    }
    public function children(Request $request)
    {

        $result = Child::where('parent_id',Auth::guard('api')->user()->id)->OrderBy('id', 'asc');

        $data = ChildrenResource::collection($result->get())->response()->getData(true);;
        return msgdata(true, trans('lang.data_display_success'), $data, success());
    }

    public function storeAbsence(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'child_id' => 'required|exists:children,id',
            'employee_id' => 'required|exists:employee,id',
            'type' => 'required|in:in,out',
        ]);
        if (!is_array($validator) && $validator->fails()) {
            return msg(false, $validator->errors()->first(), validation());
        }

        $child = Child::find($request->child_id);
        $data = new Absence();
        $data->child_id=$request->child_id;
        $data->employee_id=$request->employee_id;
        $data->parent_id=$child->parent_id;
        $data->type=$request->type;
        $data->save();

        return msgdata(true, trans('lang.Success_text'), (object)[], success());

    }

    public function wallet(Request $request)
    {
        $wallet_balance = Auth::guard('api')->user()->wallet_balance;

        $transactions = Wallet::OrderBy('id','desc')->where('parent_id',Auth::guard('api')->user()->id)->paginate(10);
        $data['balance'] = $wallet_balance;
        $data['transactions'] = $transactions;

        return msgdata(true, trans('lang.Success_text'), $data, success());

    }
    public function storeWallet(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'price' => 'required',
        ]);
        if (!is_array($validator) && $validator->fails()) {
            return msg(false, $validator->errors()->first(), validation());
        }

        $data=  Wallet::create([
            'parent_id'=>Auth::guard('api')->user()->id,
            'price'=>$request->price,
            'type'=>'deposit',
        ]);
        $total = $request->price + Auth::guard('api')->user()->wallet_balance;
        Auth::guard('api')->user()->update(['wallet_balance'=>$total]);

        return msgdata(true, trans('lang.Success_text'), $data, success());

    }

    public function storeEmployeeAbsence(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'child_id' => 'required|exists:children,id',
            'employee_id' => 'required|exists:employee,id',
            'type' => 'required|in:in,out',
        ]);
        if (!is_array($validator) && $validator->fails()) {
            return msg(false, $validator->errors()->first(), validation());
        }

        $child = Child::find($request->child_id);
        $data = new Absence();
        $data->child_id=$request->child_id;
        $data->employee_id=$request->employee_id;
        $data->parent_id=$child->parent_id;
        $data->type=$request->type;
        $data->save();

        return msgdata(true, trans('lang.Success_text'), (object)[], success());

    }


    private function paginateCollection($collection, $perPage)
    {
        $page = request()->get('page', 1);
        $paginatedCollection = $collection->forPage($page, $perPage);

        return new \Illuminate\Pagination\LengthAwarePaginator(
            $paginatedCollection,
            $collection->count(),
            $perPage,
            $page,
            ['path' => request()->url(), 'query' => request()->query()]
        );
    }

}
