<?php

namespace App\Http\Controllers\API;

use Exception;
use App\Models\User;
use App\Models\LineModel;
use App\Models\UserModel;
use App\Models\CountryCode;
use App\Models\NotifyModel;
use Illuminate\Http\Request;
use App\Mail\NotificationEmail;
use App\Models\PaymentTrxnModel;
use App\Models\BasicSettingModel;
use App\Models\NotificationModel;
use App\Models\OrderDetailsModel;
use App\Mail\UserAcceptOrderEmail;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use App\Models\PrescriptionOrderModel;
use App\Http\Requests\Admin\AcceptOrderRequest;
use App\Http\Requests\Admin\CancelOrderRequest;
use Illuminate\Http\Resources\Json\JsonResource;
use App\Http\Requests\admin\PrescriptionOrderFormRequest;

class PrescriptionOrderController extends Controller
{
    // public function order_from_api(PrescriptionOrderFormRequest $request)
    // {

    //     $data = $request->validated();

    //     $user = UserModel::find($data['uid']);
    //     if (!$user) {
    //         return response()->json(['message' => 'Invalid User'], 404);
    //     }

    //     if ($user->status == 0) {
    //         return response(['message' => 'Your account has been deactivated'], 404);
    //     }else{

    //         $prescriptionOrderModel = new PrescriptionOrderModel;

    //     // $prescriptionOrderModel->uid = $data['uid'];
    //     $prescriptionOrderModel->uid = $user->id;

    //     $files = $request->file('p_image');
    //     $image_name = '';

    //     // foreach($files as $file){
    //     //     $filename = uniqid() . '.' . $file->getClientOriginalExtension();
    //     //     $file->move('uploads/prescriptions/',$filename);
    //     //     $image_name = $image_name."uploads/prescriptions/".$filename.";";
    //     // }
    //     // $prescriptionOrderModel->p_image= $image_name;

    //     $lastIndex = count($files) - 1;
    //     foreach ($files as $index => $file) {
    //         $filename = uniqid() . '.' . $file->getClientOriginalExtension();
    //         $file->move('uploads/prescriptions/', $filename);
    //         $image_name .= "uploads/prescriptions/" . $filename;

    //         if ($index !== $lastIndex) {
    //             $image_name .= ";";
    //         }
    //     }

    //     $prescriptionOrderModel->p_image = $image_name;

    //     $prescriptionOrderModel->save();
    //     // create a new notification
    //     $userName = $user->fname;
    //     $order_id = $prescriptionOrderModel->id;
    //     $notification = new NotificationModel();


    //     $notification_title = 'Order Recieved';
    //     $notification_descrip =  $userName . ', your prescription order #' . $order_id . ' has been Recieved.';


    //     $userId = $user->id;

    //     $notifyModels = NotifyModel::where('uid', 'LIKE', $userId)->get();
    //     $playerIds = $notifyModels->pluck('player_id');
    //     $this->sendPushNotificationToUser($userId, $playerIds, $notification_title, $notification_descrip, $order_id);
    //     $this->saveNotification($notification, $userId, $notification_title,$notification_descrip, $order_id);

    //     // $notification->uid = $userId;
    //     // $notification->date = date('Y-m-d H:i:s');
    //     // $notification->title = $notification_title;
    //     // //neeed to add order id
    //     // $notification->description = $notification_descrip;
    //     // $notification->save();

    //     return response()->json(['message' => 'Prescription added succesfully'], 200);

    //     }


    // }

    public function order_from_api(Request $request)
    {
        try {
            $rules = [
                'uid' => 'required|integer',
                'shop_id' => 'required|integer',
                'gen_status' => 'required|integer',
                'p_image' => 'required',
            ];

            $data = $request->validate($rules);

            $user = UserModel::find($data['uid']);
            if (!$user) {
                // return response()->json(['message' => 'Invalid User'], 404);
                return response()->json(['message' => __("invalidUser")], 404);
            }

            if ($user->status == 0) {
                // return response()->json(['message' => 'Your account has been deactivated'], 404);
                return response()->json(['message' => __("accountDeactivated")], 404);
            }

            $prescriptionOrderModel = new PrescriptionOrderModel;
            $prescriptionOrderModel->uid = $user->id;
            $prescriptionOrderModel->gen_status = $data['gen_status'];
            $prescriptionOrderModel->created_by = $data['shop_id'];

            $files = $request->file('p_image');
            $image_name = '';

            $lastIndex = count($files) - 1;
            foreach ($files as $index => $file) {
                $filename = uniqid() . '.' . $file->getClientOriginalExtension();
                $file->move('uploads/shop_' . $data['shop_id'] . '/prescriptions/', $filename);
                $image_name .= "uploads/shop_" . $data['shop_id'] . "/prescriptions/" . $filename;

                if ($index !== $lastIndex) {
                    $image_name .= ";";
                }
            }



            $prescriptionOrderModel->p_image = $image_name;

            $prescriptionOrderModel->save();

            $lineModel = new LineModel;

            $botIds = BasicSettingModel::where('created_by', $data['shop_id'])->first();

            if ($botIds) {

                $checkExistLine = LineModel::where('u_id', $user->id)->where('shop_id', $data['shop_id'])->first();

                if (!$checkExistLine) {

                    $botId = $botIds->bot_id;

                    if ($botId !== null) {
                        $lineModel->u_id = $user->id;
                        $lineModel->shop_id = $data['shop_id'];
                        $lineModel->bot_id = $botId;
                        $lineModel->save();
                    }
                }
            }


            // create a new notification
            $userName = $user->fname;
            $order_id = $prescriptionOrderModel->id;
            $notification = new NotificationModel();



            $notification_title =  __("orderRecievdTitle");
            $notification_descrip =  $userName . "" . __("orderRecievdDescrip1") . "" . $order_id . "" . __("orderRecievdDescrip2");

            $userId = $user->id;

            $notifyModels = NotifyModel::where('uid', 'LIKE', $userId)->get();
            $playerIds = $notifyModels->pluck('player_id');
            $this->sendPushNotificationToUser($userId, $playerIds, $notification_title, $notification_descrip, $order_id);
            $this->saveNotification($notification, $userId, $notification_title, $notification_descrip, $order_id);

            $admin = User::find($data['shop_id']);
            $email = $admin->email;
            Mail::to($email)->send(new NotificationEmail());

            // return response()->json(['message' => 'Prescription added successfully'], 200);
            return response()->json(['message' => __("prescriptionAddedSuccessfully")], 200);
            // return response()->json(['message' => $botId], 200);
        } catch (\Illuminate\Database\QueryException $e) {
            // Database-related errors
            Log::error($e); // Log the exception for debugging purposes

            // return response()->json(['message' => 'Server error: ' . $e->getMessage()], 500);
            return response()->json(['message' => __("serverError") . $e->getMessage()], 500);
        } catch (\Exception $e) {
            // Other errors
            Log::error($e); // Log the exception for debugging purposes

            // return response()->json(['message' => 'Internal server error: ' . $e->getMessage()], 500);
            return response()->json(['message' => __("internalServerError") . $e->getMessage()], 500);
        }
    }


    // public function order_from_api(PrescriptionOrderFormRequest $request)
    // {
    //     try {
    //         $data = $request->validated();

    //         $user = UserModel::find($data['uid']);
    //         if (!$user) {
    //             return response()->json(['message' => 'Invalid User'], 404);
    //         }

    //         if ($user->status == 0) {
    //             return response()->json(['message' => 'Your account has been deactivated'], 404);
    //         }

    //         $prescriptionOrderModel = new PrescriptionOrderModel;

    //         // $prescriptionOrderModel->uid = $data['uid'];
    //         $prescriptionOrderModel->uid = $user->id;

    //         $files = $request->file('p_image');
    //         $image_name = '';

    //         $lastIndex = count($files) - 1;
    //         foreach ($files as $index => $file) {
    //             $filename = uniqid() . '.' . $file->getClientOriginalExtension();
    //             $file->move('uploads/prescriptions/', $filename);
    //             $image_name .= "uploads/prescriptions/" . $filename;

    //             if ($index !== $lastIndex) {
    //                 $image_name .= ";";
    //             }
    //         }

    //         $prescriptionOrderModel->p_image = $image_name;

    //         $prescriptionOrderModel->save();
    //         // create a new notification
    //         $userName = $user->fname;
    //         $order_id = $prescriptionOrderModel->id;
    //         $notification = new NotificationModel();

    //         // $notification_title = 'Order Received';
    //         // $notification_title = "{{ __('orderRecievdTitle') }}";
    //         // $notification_descrip = $userName . "{{ __('orderRecievdDescrip1') }}" . $order_id . "{{ __('orderRecievdDescrip2') }}";
    //         $notification_title = __("orderRecievdTitle");
    //         $notification_descrip =  $userName ."" . __("orderRecievdDescrip1") . "" .$order_id."". __("orderRecievdDescrip2");


    //         $userId = $user->id;

    //         $notifyModels = NotifyModel::where('uid', 'LIKE', $userId)->get();
    //         $playerIds = $notifyModels->pluck('player_id');
    //         $this->sendPushNotificationToUser($userId, $playerIds, $notification_title, $notification_descrip, $order_id);
    //         $this->saveNotification($notification, $userId, $notification_title, $notification_descrip, $order_id);

    //         Mail::to('dev.xorgeek@gmail.com')->send(new NotificationEmail());
    //         return response()->json(['message' => 'Prescription added successfully'], 200);
    //     } catch (\Illuminate\Database\QueryException $e) {
    //         // Database-related errors
    //         Log::error($e); // Log the exception for debugging purposes

    //         return response()->json(['message' => 'Database error: '.$e->getMessage()], 500);
    //     } catch (\Exception $e) {
    //         // Other errors
    //         Log::error($e); // Log the exception for debugging purposes

    //         return response()->json(['message' => 'Internal server error: '.$e->getMessage()], 500);
    //     }
    // }

    public function saveNotification($notification, $userId, $notification_title, $notification_descrip, $order_id)
    {

        $notification->uid = $userId;
        $notification->oid = $order_id;
        $notification->date = date('Y-m-d H:i:s');
        $notification->title = $notification_title;
        //neeed to add order id
        $notification->description = $notification_descrip;
        $notification->save();
    }


    public function sendPushNotificationToUser($id, $playerIds, $notification_title, $notification_descripo, $order_id)
    {

        $response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'Authorization' => 'Basic NmNjZTI2NDEtMTY4Zi00M2ZhLThhMWMtN2YyMGU2ZjZmODcx',
        ])->post('https://onesignal.com/api/v1/notifications', [
            'app_id' => '6f8b95c7-430b-4395-be4d-c8a983cace33',
            'include_player_ids' => $playerIds,
            "android_group" => 1,
            "android_channel_id" => "22160e8f-8253-48d1-b4e4-b927f3956f71",
            'data' => ['Page' => 'Prescriptions', 'id' => $order_id],
            'contents' => ['en' => $notification_descripo],
            'headings' => ['en' => $notification_title],
        ]);

        // Check the response status and handle accordingly
        if ($response->successful()) {
            // Notification sent successfully
            return response()->json(['message' => 'Notification has been sent']);
        } else {
            // Failed to send notification
            return response()->json(['error' => 'Failed to send push notification'], $response->status());
        }
    }

    public function api_show($user_id, Request $request)
    {
        $o_status = $request->input('o_status');

        // $prescriptionOrder = PrescriptionOrderModel::where('uid', $user_id)->get();
        $prescriptionOrderQuery = PrescriptionOrderModel::where('uid', $user_id);

        if (!empty($o_status)) {
            $prescriptionOrderQuery->where('o_status', $o_status);
        }

        $prescriptionOrder = $prescriptionOrderQuery->get();

        if ($prescriptionOrder->isEmpty()) {

            return response()->json(['message' => __("noOrderFound")], 401);
        }
        return response()->json(['data' => $prescriptionOrder], 200);
    }

    public function order_medicine_list($order_id)
    {
        // return 'This is Dashboard';
        $orderDetailsModel = OrderDetailsModel::where('p_id', $order_id)->get();

        // if ($orderDetailsModel->isEmpty()) {
        //     return response()->json(['message' => 'Medicine cart is not ready yet'], 401);
        // }


        foreach ($orderDetailsModel as $item) {
            $item->m_image = "uploads/shop_" . $item->created_by . "/medicines/" . $item->m_image;
        }

        return response()->json(['data' => $orderDetailsModel], 200);
    }


    public function rejectOrder(CancelOrderRequest $request, $order_id)
    {
        $data = $request->validated();

        $prescriptionOrder = PrescriptionOrderModel::find($order_id);
        // $user = UserModel::where('id', $user_id)->first();

        if ($prescriptionOrder) {

            $prescriptionOrder->o_status =  $data['o_status'];
            $prescriptionOrder->status = $data['status'];


            $prescriptionOrder->update();

            return response($prescriptionOrder, 200);
            // return response()->json(['message' => 'Order Canceled'], 200);
        } else {

            // return response()->json(['message' => 'Order not found'], 404);
            return response()->json(['message' => __("noOrderFound")], 404);
        }
    }

    public function payment_trxn(Request $request)
    {

        $data = $request->validate([
            'p_id' =>  'required',
            'u_id' =>  'required',
            'trxn_id' =>  'required',
            'status' =>  'required',
            'amount' =>  'required',
        ]);

        $add_trxn = new PaymentTrxnModel;

        $add_trxn->p_id = $data['p_id'];
        $add_trxn->u_id = $data['u_id'];
        $add_trxn->trxn_id = $data['trxn_id'];
        $add_trxn->status = $data['status'];
        $add_trxn->amount = $data['amount'];

        $add_trxn->save();

        return response()->json(['message' => 'added succesfully'], 200);
    }

    // public function top_order_func($user_id){
    //     $prescriptionOrder = PrescriptionOrderModel::where('uid', $user_id)
    //     ->where('o_status', 1)
    //     ->orWhere('o_status', 3)
    //     ->orderBy('created_at', 'desc') // Order by the created_at column in descending order
    //     ->first();
    //     if ($prescriptionOrder) {
    //         return response($prescriptionOrder, 200);
    //     }else{
    //         return response()->json(['message' => __("noOrderFound")], 404);
    //     }


    // }

    public function top_order_func(int $user_id) {
        try {
            $prescriptionOrder = PrescriptionOrderModel::where(function($query) {
                $query->where('o_status', 1)
                      ->orWhere('o_status', 3);
            })
            ->where('uid', $user_id)
            ->orderBy('created_at', 'desc')
            ->first();

            if ($prescriptionOrder) {
                return response()->json($prescriptionOrder, 200);
            } else {
                return response()->json(['message' => __("noOrderFound")], 404);
            }
        } catch (Exception $e) {
            // Handle any exceptions (e.g., database connection issues) here
            return response()->json(['message' => 'Internal Server Error'], 500);
        }
    }


    public function acceptOrder(AcceptOrderRequest $request, $order_id)
    {
        //$data = $request->validated();

        $data = $request->validate([
            'o_status' => ['required', 'integer', new ValidateInteger],
            'status' => ['required', 'integer', new ValidateInteger],
            'pay_methode' => 'required|string',

            'p_id' =>  ['required', 'integer', new ValidateInteger],
            'u_id' =>  ['required', 'integer', new ValidateInteger],
            'trxn_id' =>  'required',
            'trxn_status' =>  'required',
            'amount' =>  'required',
        ]);

        $user = UserModel::find($data['u_id']);

        $prescriptionOrder = PrescriptionOrderModel::find($order_id);
        // $user = UserModel::where('id', $user_id)->first();

        if ($prescriptionOrder) {

            $prescriptionOrder->o_status =  $data['o_status'];
            $prescriptionOrder->status = $data['status'];
            $prescriptionOrder->pay_methode = $data['pay_methode'];
            $prescriptionOrder->pay_type_id = $request->input('pay_type');

            $prescriptionOrder->update();

            $add_trxn = new PaymentTrxnModel;

            $add_trxn->p_id = $data['p_id'];
            $add_trxn->u_id = $data['u_id'];
            $add_trxn->pay_type = $request->input('pay_type');
            $add_trxn->trxn_id = $data['trxn_id'];
            $add_trxn->status = $data['trxn_status'];
            $add_trxn->amount = $data['amount'];
            // $add_trxn->created_by =$request->input('created_by');
            $add_trxn->created_by = $prescriptionOrder->created_by;

            $add_trxn->save();

            $userName = $user->fname;
            $notification = new NotificationModel();
            $userId = $user->id;

            $notification_title =  __("userOrderAcceptedTitle");
            $notification_descrip =  $userName . "" . __("userOrderAcceptedDescrip1");



            $notifyModels = NotifyModel::where('uid', 'LIKE', $userId)->get();
            $playerIds = $notifyModels->pluck('player_id');
            $this->sendPushNotificationToUser($userId, $playerIds, $notification_title, $notification_descrip, $order_id);
            $this->saveNotification($notification, $userId, $notification_title, $notification_descrip, $order_id);

            $admin = User::find($prescriptionOrder->created_by);
            $email = $admin->email;
            Mail::to($email)->send(new UserAcceptOrderEmail());

            return response($prescriptionOrder, 200);
        } else {

            // return response()->json(['message' => 'Order not found'], 404);
            return response()->json(['message' => __("noOrderFound")], 404);
        }
    }

    //getOrderDetails
    public function getOrderDetails($order_id)
    {


        $prescriptionOrder = PrescriptionOrderModel::find($order_id);

        if ($prescriptionOrder) {

            return response($prescriptionOrder, 200);
        } else {

            // return response()->json(['message' => 'Order details not found'], 404);
            return response()->json(['message' => __("orderDetailsNotFound")], 404);
        }
    }

    //medicine_book
    public function medicine_book($user_id)
    {

        $orders = PrescriptionOrderModel::where('uid', $user_id)->where('o_status', 2)->with('orderDetails')->get();

        if ($orders->isEmpty()) {
            return response()->json(['message' => __("noMedicineFound")], 404);
        }

        foreach ($orders as $order) {
            foreach ($order->orderDetails as $orderDetail) {
                $orderDetail->m_image = "uploads/shop_" . $orderDetail->created_by . "/medicines/" . $orderDetail->m_image;
            }
        }

        return PrescriptionOrderResource::collection($orders);
    }
}

use Illuminate\Contracts\Validation\Rule;

class ValidateInteger implements Rule
{
    public function passes($attribute, $value)
    {
        return is_int($value);
    }

    public function message()
    {
        return 'The :attribute must be an integer.';
    }
}


class PrescriptionOrderResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'updated_at' => $this->updated_at,
            // Include other desired fields here
            'order_details' => $this->orderDetails,
        ];
    }
}
