<?php

namespace App\Http\Controllers\Admin;

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

use Illuminate\Support\Facades\Log;

class CalenderController extends Controller
{
    public function view()
    {

        $admin_id = Auth::User();
        $order_details = OrderDetailsModel::with('prescription_order')->orderBy('m_days', 'Asc')->where('created_by', $admin_id->id)->get();

        Log::error($order_details); // Log the exception for debugging purposes
        Log::info('Order Details: ', $order_details->toArray());


        $id = 365;
        $botIds = LineModel::where('shop_id', $admin_id->id)
            ->pluck('line_id', 'u_id');

        $trnsction = PaymentTrxnModel::where('created_by', $admin_id->id)->get();
        return view('admin.calender.viewcalender', compact('order_details', 'id', 'botIds', 'trnsction'));
    }
    public function pagination(Request $request)
    {
        $admin_id = Auth::User();
        $page_id = $request->query('page_id');
        // Initialize the $id variable with a default value
        $id = null;
        // Use a switch statement to set the value of $id based on $page_id
        switch ($page_id) {
            case 1:
                $id = 2;
                break;

            case 2:
                $id = 7;
                break;

            case 3:
                $id = 30;
                break;
            case 4:
                $id = 365;
                break;

            // Add more cases if needed for other values of $page_id

            default:
                // Set a default value for $id if none of the cases match
                // For example, set it to 0 or leave it as null.
                $id = 0;
                break;
        }

        // Fetch your $order_details here...

        // Pass the $id variable along with $order_details to the view
        // $order_details = OrderDetailsModel::all();
        $order_details = OrderDetailsModel::orderBy('m_days', 'Asc')->where('created_by', $admin_id->id)->get();
        $botIds = LineModel::where('shop_id', $admin_id->id)
            ->pluck('line_id', 'u_id');
        return view('admin.calender.viewcalender', compact('order_details', 'id', 'botIds'));
    }


    public function notification_sts(Request $request)
    {

        $data = $request->validate([
            'status' => 'required|string|max:255',

        ]);

        $result = $data['status'];
        if ($result === 'success') {
            session()->flash('status', 'Notification sent successfully'); // Set success flash message
        } else {
            session()->flash('status', 'Failed to send notification'); // Set error flash message
        }
        return redirect('admin/view-calender');
    }

    public function notification(Request $request)
    {
        $data = $request->validate([
            'notes' => 'required|string|max:255',
            'userid' => 'required|string',
            'orderid' => 'required|string',
            'notification_title' => 'required|string'

        ]);


        $notification_descrip = $data['notes'];
        $notification_title = $data['notification_title'];
        $result = $this->sendPushNotificationToUser($notification_title, $data['userid'], $notification_descrip, $data['orderid']);


        if ($result === 'success') {
            session()->flash('status', 'Notification sent successfully'); // Set success flash message
        } else {
            session()->flash('status', 'Failed to send notification'); // Set error flash message
        }
        return response(['message' => $result], 200);
        //return redirect('admin/view-calender');

    }

    public function allnotification(Request $request)
    {
        $data = $request->validate([
            'page_id' => 'required|string|max:255',
        ]);
        $admin_id = Auth::User();
        $page_id = $data['page_id'];
        $order_details = OrderDetailsModel::orderBy('m_days', 'Asc')->where('created_by', $admin_id->id)->get();
        $usersToSendNotification = [];
        foreach ($order_details as $details) {
            if ($details->prescription_order->o_status == 2) {

                $userid = $details->prescription_order->user->id ?? 'N/A';
                $userlastname = $details->prescription_order->user->lname ?? 'N/A';
                $userfirstname = $details->prescription_order->user->fname ?? 'N/A';

                $fullname = $userfirstname . ' ' . $userlastname;
                $mTitle = $details->m_title ?? 'N/A';
                $medicine_name = $mTitle;
                $order_id = $details->prescription_order->id;

                $createdAt = strtotime($details->prescription_order->updated_at);
                $currentDate = time();
                $timeDifference = $currentDate - $createdAt;
                $totaldays = ceil($timeDifference / (60 * 60 * 24));

                $remaining = ($details->m_days) - $totaldays;

                if ($remaining > 0 && $remaining <= $page_id) {

                    $usersToSendNotification[] = [
                        'userid' => $userid,
                        'fullname' => $fullname,
                        'medicine_name' => $medicine_name,
                        'remaining' => $remaining,
                        'p_id' => $order_id,

                    ];
                }

            }
        }

        foreach ($usersToSendNotification as $user) {
            // $description = $user['remaining'] . ' days ' . __('remaningFor') . ' ' . $user['medicine_name'];
            $description = $user['fullname'] . __('remindertext1') . "「" . $user['medicine_name'] . "」" . __('remindertext2') . $user['remaining'] . __('remindertext3') . $admin_id->shopname . __('remindertext4');
            $notification_title = __('medicineReminder');
            $result = $this->sendPushNotificationToUser($notification_title, $user['userid'], $description, $user['p_id']);

            if ($result === 'success') {
                session()->flash('status', 'Notification sent successfully'); // Set success flash message
            } else {
                session()->flash('status', 'Failed to send notification'); // Set error flash message
            }
        }
        return response(['message' => "success"], 200);
        //return redirect('admin/view-calender');

        // echo("<script>console.log('PHP: " . "sadfa" . "');</script>");

    }


    public function sendPushNotificationToUser($notification_title, $userid, $notification_descripo, $orderid)
    {


        $notifyModels = NotifyModel::where('uid', 'LIKE', $userid)->get();
        $playerIds = $notifyModels->pluck('player_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' => $orderid],
                    'contents' => ['en' => $notification_descripo],
                    'headings' => ['en' => $notification_title],
                ]);

        if ($response->successful()) {
            // Notification sent successfully
            $this->saveNotification($userid, $notification_title, $notification_descripo, $orderid);
            return 'success'; // Return success message


        } else {
            // Failed to send notification
            return 'error'; // Return error message
        }
    }

    public function saveNotification($userid, $notification_title, $notification_descripo, $orderid)
    {
        $notification = new NotificationModel();
        $notification->uid = $userid;
        $notification->oid = $orderid;
        $notification->date = date('Y-m-d H:i:s');
        $notification->title = $notification_title;
        //neeed to add order id
        $notification->description = $notification_descripo;
        $notification->save();
    }
}
