<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;


// use DB;


class SocialiteController extends Controller
{
    public function redirectToGoogle()
    {
        session(['previous_url' => url()->previous()]);

        return Socialite::driver('google')->redirect();
    }


    public function sendPassword($email, $kode)
    {


        $html = '<!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8" />
                    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
                    <title>BACABUKU.COM</title>
                    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
                    <style>
                    * {
                        box-sizing: border-box;
                        margin: 0;
                        padding: 0;
                    }
                    body {
                        background-color: #f5f8fa;
                        color: #28303f;
                        font-family: "Inter", sans-serif;
                    }
                    a {
                        text-decoration: none;
                        color: #28303f;
                    }
                    .container {
                        background-color: #f3f7f9;
                        padding-top: 30px;
                        padding-bottom: 30px;
                    }
                    .email-wrapper {
                        width: 640px;
                        margin: 0 auto;
                        background-color: #ffffff;
                        border-radius: 10px;
                    }
                    </style>
                </head>
                <body>
                    <div class="container">
                    <table align="center" cellpadding="0" cellspacing="0" class="email-wrapper">
                        <tbody>
                        <tr>
                            <td>
                            <table width="100%">
                                <tbody>
                                <tr style="padding: 10px 0">
                                    <td style="padding: 16px 24px; text-align: center">
                                    <img src="https://bacabuku.com/images/logo-bacabuku.png" alt="logo bacabuku.com" height="40" />
                                    <p style="margin: 24px 0; font-size: 14px; color: #333; font-family: Arial, sans-serif; line-height: 1.5;">
                                        Selamat, Anda telah terdaftar di 
                                        <a href="https://bacabuku.com" style="color: #0066cc; text-decoration: none;">
                                            <img src="https://bacabuku.com/images/logo-bacabuku.png" alt="BacaBuku" height="20" style="vertical-align: middle; margin-left: 5px;"/>
                                        </a>
                                    </p>
                                    <p style="margin: 24px 0; font-size: 14px; color: #333">Berikut adalah password Anda:</p>
                                    <p style="margin: 12px 0; font-size: 28px; font-weight: bold; color: #333">' . $kode . '</p>
                                    <p style="margin: 24px 0; font-size: 14px; color: #333">Akun ini bisa Anda gunakan di aplikasi bacabuku.com sebagai reader.</p>
                                    </td>
                                </tr>
                                <tr>
                                    <table width="100%">
                                    <tbody>
                                        <tr style="padding: 10px 0">
                                        <td style="padding: 16px 24px 0 24px; text-align: center">
                                            <div style="padding: 24px; border-top: 1px dashed #d9d9d9; display: flex; align-items: center; justify-content: center; font-size: 12px">&copy; 2024 PT. Enam Kubuku Indonesia. All rights reserved.</div>
                                        </td>
                                        </tr>
                                    </tbody>
                                    </table>
                                </tr>
                                </tbody>
                            </table>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                    </div>
                </body>
                </html>';

        $this->insertEmail($email, $html, 'Password BACABUKU.COM', 'BACABUKU.COM <berita@kubuku.co.id>');

        return response()->json(['code' => 200, 'message' => 'Password sent successfully!']);
    }

    public function handleGoogleCallback()
    {
        try {
            $googleUser = Socialite::driver('google')->user();
            $kodeMitraToko = env("KODE_MITRA_TOKO", 'BACABUKU.COM');
            $user = User::where('email', $googleUser->user['email'])->where('kode_mitra_toko', $kodeMitraToko)->first();

            if ($user) {
                Auth::login($user);
                return redirect(session('previous_url', '/'))->with('success', 'Berhasil Login!');

                return redirect()->back()->with('success', 'Berhasil Login!');
            } else {
                try {
                    $kodeMitraToko = env("KODE_MITRA_TOKO", 'BACABUKU.COM');

                    // $randomPassword = $this->generateRandomPassword();
                    // $hashedPassword = Hash::make($randomPassword);
                    // $hashedPassword = password_hash($randomPassword, PASSWORD_BCRYPT, array('cost' => 12));


                    $kode = 'USRGOO' . $this->getRandomString(9);
                    $hashedPassword = Hash::make($kode);

                    $user = new User;
                    $user->kode = $kode;
                    $user->kode_mitra_toko = $kodeMitraToko;
                    $user->email = $googleUser->user['email'];
                    $user->password = $hashedPassword;
                    $user->nama = $googleUser->user['name'];
                    $user->aktif = '1';
                    $user->tgl_input = now();
                    $user->save();
                    

                    $checkReader = DB::table('_pengguna_reader')->where('email', $googleUser->user['email'])->first();
                    if (!$checkReader) {
                        DB::table('_pengguna_reader')->insert([
                            'kode' => $kode,
                            'email' => $googleUser->user['email'],
                            'password' => $hashedPassword,
                            'nama' => $googleUser->user['name'],
                            'aktif' => '1',
                            'tgl_input' => now(),
                        ]);
                    }

                    Auth::login($user, true);

                    $this->sendPassword($googleUser->user['email'], $kode);

                    return redirect(session('previous_url', '/'))->with('success', 'Berhasil Login!');

                    // return response()->json(['code' => 200, 'message' => 'successfully!']);
                } catch (\Exception $e) {
                    return response()->json(['code' => 500, 'message' => 'Error occurred while creating new user.']);
                }
            }
        } catch (\Throwable $th) {
            Log::error('Error in Google Callback: ' . $th->getMessage());
            return redirect()->route('login')->with('error', 'Something went wrong with Google login.');
        }
    }



    function generateRandomPassword($length = 8)
    {
        $alpha  = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $number = '0123456789';
        $char   = '!@#$%^&*()';

        $chars = $alpha . $number . $char;

        $password = '';
        for ($i = 0; $i < $length; $i++) {
            $password .= $chars[rand(0, strlen($chars) - 1)];
        }

        return $password;
    }


    function insertEmail($email, $message, $subject, $pengirim)
    {
        DB::connection('mysql2')->table('kubuku_email.email_outbox')->insert([
            'email_penerima' => $email,
            'html_email' => $message,
            'email_pengirim' => $pengirim,
            'image' => '',
            'attachment' => '',
            'smtp_server' => 'mail.kubuku.co.id',
            'smtp_port' => '25',
            'smtp_user' => 'berita@kubuku.co.id',
            'smtp_password' => 'Miracle2021',
            'subject' => $subject,
            'ins_date' => now(),
            'prioritas' => 2
        ]);
        return true;
    }


    function getRandomString($n)
    {
        return bin2hex(random_bytes($n / 2));
    }

    public function handleGoogleOneTap(Request $request)
    {
        try {
            $email = $request->input('email');
            // dd($email);
            $user = User::where('email', $email)->first();

            if ($user) {
                Auth::login($user);
                // return response()->json(['success' => true]);
                return response()->json(['success' => true, 'redirect' => route('beranda')]);
            } else {
                return response()->json(['error' => 'User not found.'], 404);
            }
        } catch (\Throwable $th) {
            return response()->json(['error' => 'Something went wrong.'], 500);
        }
    }
    public function handleOneTap(Request $request)
    {
        // Validate the request
        $request->validate([
            'credential' => 'required|string',
        ]);

        // Decode the JWT token sent by Google
        $idToken = $request->input('credential');
        $payload = $this->decodeGoogleJwt($idToken);

        // Extract email from the payload
        $email = $payload['email'];

        // Check if the user exists in your database
        $user = User::where('email', $email)->first();

        if ($user) {
            // Log the user in
            Auth::login($user);

            return response()->json(['success' => true, 'redirect' => route('home')]);
        } else {
            // Handle the case where the user does not exist
            return response()->json(['success' => false, 'message' => 'User not found'], 404);
        }
    }

    private function decodeGoogleJwt($idToken)
    {
        $parts = explode('.', $idToken);
        if (count($parts) !== 3) {
            throw new \Exception('Invalid JWT token');
        }

        $payload = base64_decode($parts[1]);
        return json_decode($payload, true);
    }
}
