<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use App\Providers\RouteServiceProvider;

class SocialController extends Controller
{
    // GOOGLE LOGIN
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }

    public function handleGoogleCallback()
    {
        $googleUser = Socialite::driver('google')->stateless()->user();

        $u_role = DB::select('SELECT * FROM `roles` WHERE `name`="Subscriber"');
        $e_user = DB::table('users')->where('email', $googleUser->email)->first();

        if (!$e_user) {

            //  add user in database
            $id = DB::table('users')->insertGetId([
                'name' => $googleUser->name,
                'email' => $googleUser->email,
                'password' => Hash::make(rand(100000, 999999)),
                'google_id' => json_encode(array("id" => $googleUser->id, "token" => $googleUser->token)),
                'created_at' => date('Y-m-d H:i:s'),
            ]);

            if ($id) {
                $lr_id = DB::table('model_has_roles')->insertGetId([
                    'role_id' => $u_role[0]->id,
                    'model_type' => 'App\Models\User',
                    'model_id' => $id,
                ]);

                Session::put('f_user_login', 1);
                Session::put('user_id', $id);
                Session::put('username', $googleUser->name);

                return redirect()->route('my_account');
            }
        } else {
            Session::put('f_user_login', 1);
            Session::put('user_id', $e_user->id);
            Session::put('username', $googleUser->name);

            return redirect()->route('my_account');
        }
    }


    // LINKEDIN LOGIN
    public function linkedinRedirect()
    {
        return Socialite::driver('linkedin')->setScopes(['openid profile email'])->redirect();
    }

    public function linkedinCallback()
    {
        // Handle the LinkedIn callback
        $token_url = 'https://www.linkedin.com/oauth/v2/accessToken';
        $token_params = [
            'grant_type' => 'authorization_code',
            'code' => $_GET['code'],
            'client_id' => $_ENV['LINKEDIN_CLIENT_ID'],
            'client_secret' => $_ENV['LINKEDIN_CLIENT_SECRET'],
            'redirect_uri' => $_ENV['LINKEDIN_CLIENT_REDIERECT']
        ];
        $ch = curl_init($token_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($token_params));
        $token_response = curl_exec($ch);
        curl_close($ch);

        $token_data = json_decode($token_response, true);

        if (isset($token_data['error'])) {
            echo 'Error: ' . $token_data['error_description'];
            exit;
        }

        // Use the access token to get user data
        $api_url = 'https://api.linkedin.com/v2/userinfo';
        $api_headers = [ 'Authorization: Bearer ' . $token_data['access_token'], ];
        $api_response = @file_get_contents($api_url, false, stream_context_create([
            'http' => [ 'header' => implode("\r\n", $api_headers), ],
        ]));

        ob_end_clean();

        if ($api_response === false) {
            echo 'Failed to retrieve LinkedIn user data.';
            exit;
        }

        $linkedinUser = json_decode($api_response, true);

        $u_role = DB::select('SELECT * FROM `roles` WHERE `name`="Subscriber"');
        $e_user = DB::table('users')->where('email', $linkedinUser['email'])->first();

        if (!$e_user) {

            //  add user in database
            $id = DB::table('users')->insertGetId([
                'name' => $linkedinUser['name'],
                'email' => $linkedinUser['email'],
                'password' => Hash::make(rand(100000, 999999)),
                'linkedin_id' => json_encode(array("id" => $linkedinUser['sub'])),
                'created_at' => date('Y-m-d H:i:s'),
            ]);

            if ($id) {
                $lr_id = DB::table('model_has_roles')->insertGetId([
                    'role_id' => $u_role[0]->id,
                    'model_type' => 'App\Models\User',
                    'model_id' => $id,
                ]);

                Session::put('f_user_login', 1);
                Session::put('user_id', $id);
                Session::put('username', $linkedinUser['name']);

                return redirect()->route('my_account');
            }
        } else {
            Session::put('f_user_login', 1);
            Session::put('user_id', $e_user->id);
            Session::put('username', $linkedinUser['name']);

            return redirect()->route('my_account');
        }
    }
}
