<?php

namespace App\Http\Controllers;

use Google\Auth\OAuth2;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use GuzzleHttp\Client;
use App\Models\User;
use App\Models\Course;
use App\Models\Enrollments;
use App\Models\FirebaseNotifications;

class FCMController extends Controller
{
    public function sendNotification($data)
    {
        $serviceAccountPath = storage_path('app/firebase-service-account.json'); // Your JSON file path
        $projectId = 'palsarh'; // Replace with your Firebase project ID

        // Get OAuth2 token
        $scopes = ['https://www.googleapis.com/auth/firebase.messaging'];
        $credentials = new ServiceAccountCredentials($scopes, $serviceAccountPath);
        $tokenArray = $credentials->fetchAuthToken();
        $accessToken = $tokenArray['access_token'];

        // Notification payload
        $message = [
            'message' => [
                //'topic' => 'all_users', // Or use 'token' => 'DEVICE_FCM_TOKEN'
				'token' => $data['device_token'],
                'notification' => [
                    'title' => $data['title'],
                    'body' => $data['message'],
                ],
				'data' => [
                    'course_id' => $data['course_id'],
                    'student_id' => $data['student_id'],
                    'type' => $data['type'],
                ],
                'android' => [
                    'notification' => [
                        //'sound' => 'custom_sound', // Place sound file in res/raw
                        'channel_id' => 'palsarh',
                        //'click_action' => 'FLUTTER_NOTIFICATION_CLICK',
                        
                    ],
					'priority' => 'high',
                ],
				
				
            ]
        ];

        // Send HTTP v1 API request
        $client = new Client();
        $url = "https://fcm.googleapis.com/v1/projects/{$projectId}/messages:send";
        $response = $client->post($url, [
            'headers' => [
                'Authorization' => "Bearer {$accessToken}",
                'Content-Type' => 'application/json',
            ],
            'json' => $message,
        ]);

        return response()->json([
            'success' => true,
            'response' => json_decode($response->getBody()->getContents(), true),
        ]);
    }
	
	
	public function index(Request $request)
    {
        $query = FirebaseNotifications::orderby('id', 'desc');
		if (request()->has('search') && request()->query('search') != '') {
            $query = $query->where('title', request()->query('search'));
        }
		
        $page_data['notifications'] = $query->paginate(10)->appends(request()->query());
		
        $page_data['students'] = User::where("role","student")->get();		
        $page_data['courses'] = Course::where("status","active")->get();
        return view('admin.notification.index', $page_data);
    }

    public function create()
    {
		$data = view('admin.notification.create');
		$data->students = User::where("role","student")->get();
		$data->courses = Course::where("status","active")->get();
        return $data;
    }

    public function store(Request $request)
    {
        $rules = [
            'title'     => 'required',
            'message' => 'required',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $coupon['title']    = $request->title;
        $coupon['message']  = $request->message;
        $coupon['type'] 	= $request->type;
        $coupon['course_id']   = $request->course_id;
        $coupon['student_id']   = $request->student_id;

        // insert data
        FirebaseNotifications::insert($coupon);
		if($request->type == "course"){
			$enrollments = Enrollments::where("course_id",$request->course_id)->get();
			foreach($enrollments as $kk => $enrollment){
				$user = User::find($enrollment->user_id);
				//$token = $user->device_token;
				if(empty($user->device_token) == false  && $user->device_token != "" && $user->device_token != "Fetching token..."){
					$coupon['device_token'] = $user->device_token;
					$this->sendNotification($coupon);
				}
			}			
		}else{
			$user = User::find($request->student_id);
			$token = $user->device_token;
			if($user->device_token != "" && $user->device_token != "Fetching token..."){
				$coupon['device_token'] = $user->device_token;
				$this->sendNotification($coupon);
			}
		}
		
		
		
        Session::flash('success', get_phrase('Notification sent successfully.'));
        return redirect()->back();
    }

    public function delete($id)
    {
        // check user data exists or not
        $query = FirebaseNotifications::where('id', $id);
        if ($query->doesntExist()) {
            Session::flash('error', get_phrase('Data not found.'));
            return redirect()->back();
        }

        // delete data
        $query->delete();
        Session::flash('success', get_phrase('Notification has ben deleted successfully.'));
        return redirect()->back();
    }

    public function edit($id)
    {
        // check user data exists or not
        $query = Coupon::where('id', $id)->where('user_id', auth()->user()->id);
        if ($query->doesntExist()) {
            Session::flash('error', get_phrase('Data not found.'));
            return redirect()->back();
        }

        $page_data['coupon_details'] = $query->first();
        return view('admin.coupon.edit', $page_data);
    }

    public function update(Request $request, $id)
    {
        // check user data exists or not
        $query = Coupon::where('id', $id)->where('user_id', auth()->user()->id);
        if ($query->doesntExist()) {
            Session::flash('error', get_phrase('Data not found.'));
            return redirect()->back();
        }

        $rules = [
            'code'     => "required|string|unique:coupons,code,$id",
            'discount' => 'required|numeric|between:1,100',
            'expiry'   => 'required|date|after_or_equal:today',
            'status'   => 'required|in:0,1',
        ];

        $messages = [
            'expiry.after_or_equal' => 'Expiry date must be a future date.',
            'status.in'             => 'Status must be either 0 or 1.',
        ];

        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $coupon['code']     = $request->code;
        $coupon['user_id']  = auth()->user()->id;
        $coupon['discount'] = $request->discount;
        $coupon['expiry']   = strtotime($request->expiry);
        $coupon['status']   = $request->status;

        // insert data
        Coupon::where('id', $id)->update($coupon);

        Session::flash('success', get_phrase('Coupon has been updated successfully.'));
        return redirect()->back();
    }

    public function status($id)
    {
        // check user data exists or not
        $query = Coupon::where('id', $id)->where('user_id', auth()->user()->id);
        if ($query->doesntExist()) {
            Session::flash('error', get_phrase('Data not found.'));
            return redirect()->back();
        }

        $coupon = $query->first();
        $query->update(['status' => $coupon->status ? 0 : 1]);
        Session::flash('success', get_phrase('Status has been updated'));
        return redirect(route('admin.coupons'));
    }
}
