<?php

namespace App\Http\Controllers;

use App\Http\Resources\OrderListResource;
use App\Mail\OrderPlaceMail;
use App\Mail\RegistrationMail;
use App\Models\Order;
use App\Models\ServiceType;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;

class OrderController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return AnonymousResourceCollection
     */
    public function get_order_list(Request $request): AnonymousResourceCollection
    {
        $query = Order::with('assignedBy', 'assignedTo', 'serviceData', 'user');
        if ($request->input('time') == 'this' || $request->input('time') == 'prev'){
            $date = date('Y-m-d');
            if ($request->input('time') == 'prev') {
                $date = Carbon::now()->subDay()->format('Y-m-d');
            }
            $query->whereDate('created_at', $date);
        }elseif ($request->input('time') == 'between') {
            $start_date = $request->input('start_date') . ' 00.00.00' ?? Carbon::now()->format('Y-m-d') . ' 00:00:00';
            $end_date = Carbon::create($request->input('end_date'))->addDay()->format('Y-m-d') . ' 11:59:59' ?? Carbon::now()->addDay()->format('Y-m-d') . ' 11:59:59';
            $query->whereBetween('created_at', [$start_date, $end_date]);
        }
        $orders = $query->latest()->paginate(20);
        return OrderListResource::collection($orders);
    }

    /**
     * @return AnonymousResourceCollection
     */
    public function get_provider_order_list(Request $request): AnonymousResourceCollection
    {
        $query = Order::with('assignedBy', 'assignedTo', 'serviceData', 'user')->where('assigned_to', auth()->user()->id);
        if ($request->input('time') == 'this' || $request->input('time') == 'prev'){
            $date = date('Y-m-d');
            if ($request->input('time') == 'prev') {
                $date = Carbon::now()->subDay()->format('Y-m-d');
            }
            $query->whereDate('created_at', $date);
        }elseif ($request->input('time') == 'between') {
            $start_date = $request->input('start_date') . ' 00.00.00' ?? Carbon::now()->format('Y-m-d') . ' 00:00:00';
            $end_date = Carbon::create($request->input('end_date'))->addDay()->format('Y-m-d') . ' 11:59:59' ?? Carbon::now()->addDay()->format('Y-m-d') . ' 11:59:59';
            $query->whereBetween('created_at', [$start_date, $end_date]);
        }
        $orders = $query->latest()->paginate(20);
        return OrderListResource::collection($orders);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function order_history($id)
    {
        return Order::where('user_id', $id)->get();
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'phone' => 'required',
            'email' => 'required',
            'service_id' => 'required',
        ]);
        if ($request->exists('date') && $request->exists('time')) {
            $data['date_time'] = Carbon::create($request->input('date') . ' ' . $request->input('time'));
            //$data['date_time'] = $request->input('date') . ' ' . $request->input('time');
        } else {
            $data['date_time'] = $request->input('date_time');
        }

        $data['name'] = $request->input('name');
        $data['phone'] = $request->input('phone');
        $data['email'] = $request->input('email');
        $data['address'] = $request->input('address');
        $data['service_id'] = $request->input('service_id');
        $data['latitude'] = $request->input('latitude');
        $data['longitude'] = $request->input('longitude');
        $data['description'] = $request->input('description');
        $data['status'] = 1;
        $data['amount'] = $data['service_id'] == 1? 10 : ($data['service_id'] == 2 ? 40 : ($data['service_id'] == 5 ? 20: 30 ));
        $data['payment_status'] = 0;
        if ($request->input('photo')) {
            $path = '/Image/Order/';
            $timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
            $name = 'order_image_' . $timestamp;
            $file = $request->input('photo');
            $data['photo'] = ImageUploadController::uploadImage($name, $path, $file);
        } else {
            $data['photo'] = null;
        }

        $old_email = User::where('email', $request->input('email'))->first();
        if ($old_email) {
            $data['user_id'] = $old_email->id;
        }
        if ($request->exists('sign_up') && $request->input('sign_up') == 1) {
            $this->validate($request, [
                'password' => 'required|min:8',
                'phone' => 'required|unique:users,mobile',
                'email' => 'required|unique:users',
            ]);
            $user['email'] = $request->input('email');
            $user['name'] = $request->input('name');
            $user['mobile'] = $request->input('phone');
            $user['address'] = $request->input('address');
            $user['longitude'] = $request->input('longitude');
            $user['latitude'] = $request->input('latitude');
            $user['usertype'] = 3;
            $user['password'] = Hash::make($request->input('latitude'));
            $new_user = User::create($user);
            $data['user_id'] = $new_user->id;
            $details = [
                'name' => $request->input('name'),
                'email' => $request->input('email'),
                'password' => $request->input('password'),
                'phone' => $request->input('phone')
            ];
            Mail::to($request->input('email'))->send(new RegistrationMail($details));
        }

        Order::create($data);

        $service = ServiceType::findOrFail($request->input('service_id'));
        $order_details = [
            'name' => $request->input('name'),
            'email' => $request->input('email'),
            'mobile' => $request->input('phone'),
            'address' => $request->input('address'),
            'longitude' => $request->input('longitude'),
            'latitude' => $request->input('latitude'),
            'service' => $service->service_name,
            'date' => Carbon::create($data['date_time'])->toDayDateTimeString(),
        ];
        Mail::to($request->input('email'))->send(new OrderPlaceMail($order_details));
        return response()->json(['msg' => 'Order Placed Successfully']);
    }

    /**
     * Display the specified resource.
     *
     * @param \App\Models\Order $order
     * @return \Illuminate\Http\JsonResponse
     */
    public function assign_order(Request $request)
    {
        $order = Order::findOrFail($request->input('order_id'));
        $data['assigned_to'] = $request->input('assigned_to');
        $data['assigned_by'] = auth()->user()->id;
        $order->update($data);
        return response()->json(['msg' => 'Successfully Assigned']);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param \App\Models\Order $order
     * @return \Illuminate\Http\Response
     */
    public function edit(Order $order)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param \App\Models\Order $order
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Order $order)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param \App\Models\Order $order
     * @return \Illuminate\Http\Response
     */
    public function destroy(Order $order)
    {
        //
    }
}
