<?php

namespace App\Http\Controllers\Admin;

use App\Models\LineModel;
use App\Models\PaymentTrxnModel;
use App\Models\UserModel;
use Illuminate\Http\Request;
use App\Models\NotificationModel;
use App\Models\OrderDetailsModel;
use App\Http\Controllers\Controller;
use App\Models\NotifyModel;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use App\Models\PrescriptionOrderModel;

class PendingOrderController extends Controller
{


    public function view()
    {
        // $p_order = PrescriptionOrderModel::where('o_status', 1)->get();
        $admin = Auth::User();
        $trnsction = PaymentTrxnModel::where('created_by', $admin->id)->get();
        $p_order = PrescriptionOrderModel::where('o_status', 1)->where('created_by', $admin->id)->get();
        $botIds = LineModel::where('shop_id', $admin->id)
            ->pluck('line_id', 'u_id');
        return view('admin.prescription.pending_prescrip', compact('p_order', "botIds", 'trnsction'));
    }
    public function deliver_view()
    {
        $admin_id = Auth::User();
        $d_order = PrescriptionOrderModel::where('o_status', 3)->where('created_by', $admin_id->id)->get();
        $trnsction = PaymentTrxnModel::where('created_by', $admin_id->id)->get();
        return view('admin.prescription.deliver_prescip', compact('d_order', 'trnsction'));
    }

    public function getOrderDetails(Request $request)
    {
        $order_id = $request->input('order_id');

        $orderDetails = OrderDetailsModel::where('p_id', $order_id)->get();

        // Return the order details as JSON response
        return response()->json($orderDetails);
    }
    
    public function save_duration(Request $request){
        $data = $request->validate([
            'p_order_id' => 'required|string|max:255',
            'duration' => 'required|string',
            
        ]);
        $Pending_Order =  PrescriptionOrderModel::find($data['p_order_id']);
        $Pending_Order->waiting_duration=$data['duration'];
        $Pending_Order->notify_time= Carbon::now();
        $Pending_Order->update();


    }

    public function p_sts_update($p_order_id)
    {
        $Pending_Order =  PrescriptionOrderModel::find($p_order_id);
        $userId = $Pending_Order->uid;
        $user = UserModel::find($userId);
        $data = request()->all();
        $userName = $user->fname;
        $orderNo = $Pending_Order->id;
        if ($Pending_Order->status == 0) {
            $Pending_Order->status = 1;
        } elseif ($Pending_Order->o_status == 3) {
            $Pending_Order->status = 4;
            $Pending_Order->o_status = 2;
            // $notification_title = 'Prescription Order successfully delivered';
            // $notification_descrip =  $userName . ', your prescription order #' . $orderNo . ' has been delivered.';
            $notification_title = __("pickUpComplete");
            $notification_descrip =  $userName . "" . __("pickUpCompleteDescrip1") . "" . $orderNo . "" . __("pickUpCompleteDescrip2");



            $notifyModels = NotifyModel::where('uid', 'LIKE', $userId)->get();
            $playerIds = $notifyModels->pluck('player_id');
            $this->sendPushNotificationToUser($userId, $playerIds, $notification_title, $notification_descrip, $orderNo);
        } elseif ($Pending_Order->status == 7) {
            $Pending_Order->status = 5;
            $Pending_Order->o_status = 3;
            // $notification_title = __("orderApproved");
            // $notification_descrip =  $userName ."" . __("orderApprovedDescrip1") . "" .$orderNo."". __("orderApprovedDescrip2");
            $notification_title = __("sendToDeliver");
            $notification_descrip =  $userName . "" . __("sendToDeliverDescrip1") . "" . $orderNo . "" . __("sendToDeliverDescrip2");

            $notifyModels = NotifyModel::where('uid', 'LIKE', $userId)->get();
            $playerIds = $notifyModels->pluck('player_id');
            $this->sendPushNotificationToUser($userId, $playerIds, $notification_title, $notification_descrip, $orderNo);
        } else {
            $Pending_Order->status = 0;
            // $notification_title = 'Prescription Order Approved';
            // $notification_descrip =  $userName . ', your prescription order #' . $orderNo . ' has been approved.';
            $notification_title = __("orderApproved");
            $notification_descrip =  $userName . "" . __("orderApprovedDescrip1") . "" . $orderNo . "" . __("orderApprovedDescrip2");

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

        // Get user name and order number


        $Pending_Order->save();

        $notification = new NotificationModel();
        // $notification->uid = $Pending_Order->uid;
        // $notification->date = date('Y-m-d H:i:s');
        // $notification->title = $notification_title;

        // $notification->description = $notification_descrip;
        // $notification->save();

        $this->saveNotification($notification, $userId, $notification_title, $notification_descrip, $orderNo);
        if ($Pending_Order->status == 4) {
            return redirect('admin/view-deliver-order')->with('status', 'Status updated Successfully');
        } else {
            return redirect('admin/view-pending-order')->with('status', 'Status updated Successfully');
        }
    }

    public function o_sts_update($p_order_id)
    {
        $Pending_Order =  PrescriptionOrderModel::find($p_order_id);
        $data = request()->all();
        $userId = $Pending_Order->uid;
        $user = UserModel::find($userId);
        $userName = $user->fname;
        $orderNo = $Pending_Order->id;
        if ($Pending_Order->o_status == 0) {
            $Pending_Order->o_status = 1;
        } elseif ($Pending_Order->o_status == 3) {
            $Pending_Order->status = 6;
            $Pending_Order->o_status = 0;
            // $notification_title = 'Order Deliver Failed';
            // $notification_descrip =  $userName . ', your prescription order #' . $orderNo . ' has been rejected.';
            $notification_title = __("orderRejected");
            $notification_descrip =  $userName . "" . __("orderRejectedDescrip1") . "" . $orderNo . "" . __("orderRejectedDescrip2");

            $notifyModels = NotifyModel::where('uid', 'LIKE', $userId)->get();
            $playerIds = $notifyModels->pluck('player_id');
            $this->sendPushNotificationToUser($userId, $playerIds, $notification_title, $notification_descrip, $orderNo);
        } else {
            $Pending_Order->status = 2;
            $Pending_Order->o_status = 0;
            // $notification_title = 'Prescription Order Rejected';
            // $notification_descrip =  $userName . ', your prescription order #' . $orderNo . ' has been rejected.';
            $notification_title = __("orderRejected");
            $notification_descrip =  $userName . "" . __("orderRejectedDescrip1") . "" . $orderNo . "" . __("orderRejectedDescrip2");


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



        $Pending_Order->save();
        $notification = new NotificationModel();
        $this->saveNotification($notification, $userId, $notification_title, $notification_descrip, $orderNo);

        if ($Pending_Order->status == 6) {
            return redirect('admin/view-deliver-order')->with('status', 'Status updated Successfully');
        } else {
            return redirect('admin/view-pending-order')->with('status', 'Status updated Successfully');
        }
    }


    public function cart_sts_update($p_order_id)
    {
        $Pending_Order =  PrescriptionOrderModel::find($p_order_id);
        $data = request()->all();
        $userId = $Pending_Order->uid;
        $user = UserModel::find($userId);
        $userName = $user->fname;
        $orderNo = $Pending_Order->id;
        if ($Pending_Order->cart_status == 2) {
            $Pending_Order->cart_status = 1;
            // $notification_title = 'Prescription Order Cart Ready';
            // $notification_descrip =  $userName . ', your prescription order #' . $orderNo . ' Cart Ready.';
            // $notification_title = __("redyToPuckup");
            // $notification_descrip =  $userName ."" . __("redyToPuckupDescrip1") . "" .$orderNo."". __("redyToPuckupDescrip2");
            $notification_title = __("cartReady");
            $notification_descrip =  $userName . "" . __("cartReadyDescrip1") . "" . $orderNo . "" . __("cartReadyDescrip2");


            $notifyModels = NotifyModel::where('uid', 'LIKE', $userId)->get();
            $playerIds = $notifyModels->pluck('player_id');
            $this->sendPushNotificationToUser2($userId, $playerIds, $notification_title, $notification_descrip, $orderNo);
        } else {
            $Pending_Order->cart_status = 0;
        }



        $Pending_Order->save();

        $notification = new NotificationModel();
        // $notification->uid = $Pending_Order->uid;
        // $notification->date = date('Y-m-d H:i:s');
        // $notification->title = $notification_title;

        // $notification->description = $notification_descrip;
        // $notification->save();
        $this->saveNotification($notification, $userId, $notification_title, $notification_descrip, $orderNo);

        return redirect('admin/view-pending-order')->with('status', 'Status updated Successfully');
    }


    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 sendPushNotificationToUser2($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' => 'approve', 'id' => $order_id],
            // 'data' => ['id' => $order_id],
            'contents' => ['en' => $notification_descripo],
            'headings' => ['en' => $notification_title],
        ]);
        if ($response->successful()) {
            return response()->json(['message' => 'Notification has been sent']);
        } else {
            return response()->json(['error' => 'Failed to send push notification'], $response->status());
        }
    }
}
