<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use App\Models\User;
use App\Models\Provider;
use App\Models\Transaction;
use App\Models\Refferal;
use App\Models\Bank;
use Illuminate\Support\Facades\Cache;
use App\Http\Controllers\Api\NexusController;
use App\Http\Controllers\Api\SgxController;

class HomeController extends Controller
{
    public function index()
    {
        // 1. Ambil 6 Game Slot Random untuk "HOT SLOT GAMES"
        $hotGames = DB::table('game_lists')
            ->where('game_type', 'slot')
            ->where('status', 1)
            ->inRandomOrder()
            ->limit(6)
            ->get();

        // 2. Ambil 6 Game Random untuk "POPULAR GAMES"
        $popularGames = DB::table('game_lists')
            ->where('game_type', 'slot')
            ->where('status', 1)
            ->inRandomOrder()
            ->limit(6)
            ->get();

        // Kirim datanya ke View Blade
        return view('frontend.pages.home.index', compact('hotGames', 'popularGames'));
    }
    
    public function ref(Request $request)
    {
        if ($request->has('rid')) {
            session(['referral_code' => $request->query('rid')]);
        }
    
        // Setelah simpan session, lempar ke fungsi register di atas
        return $this->register($request);
    }

    public function register(Request $request) 
    {
        // Ambil dari session, kalau kosong defaultnya null
        $referral = session('referral_code', null); 
        
        return view("frontend.pages.register.index", compact('referral'));
    }
    
    public function getBannerList()
    {
        // Menggunakan logika query persis seperti yang Anda minta
        $banner = \Illuminate\Support\Facades\DB::table('tb_banner')
                    ->where('status', 'active') // Mengambil banner yang statusnya active
                    ->get();

        // Template Javascript / frontend biasanya membutuhkan balikan berupa JSON
        return response()->json([
            'success' => true,
            'data'    => $banner
        ], 200);
    }
    
    public function game($device, $type, $slug = null)
    {
        if (is_null($slug)) {
            
            $cacheProviderKey = "providerlist_{$device}_{$type}";
            
            // Hapus cache jika sedang dalam tahap testing/development
            Cache::forget($cacheProviderKey);
            $type = navbar($type);
            // Ambil data provider dari Database
            $providers = Cache::remember($cacheProviderKey, now()->addHours(1), function () use ($type) {
                return Provider::where('status', 1) // Hanya yang aktif
                    ->where('game_type', strtolower($type)) // Filter berdasar game_type (slot, casino, dll)
                    ->orderBy('sequence', 'ASC') // Mengurutkan berdasarkan kolom sequence
                    ->get();
            });
            Cache::forget("providerlist_{$device}_{$type}"); 

            // Return ke view halaman daftar provider dengan melempar variabel $providers
            return view("frontend.{$device}.pages.game.provider", compact('type', 'providers'));
        }
    
        $slug = navbar($slug); // Asumsi ini adalah helper custom Anda
        
        // PERBAIKAN 1: Tambahkan $type ke Cache Key
        $cacheKey = "gamelist_{$device}_{$type}_{$slug}";
        
        // Hapus cache jika sedang dalam tahap testing/development (Hapus baris ini saat produksi live)
        Cache::forget($cacheKey); 
        
        // PERBAIKAN 2: Tambahkan $type pada bagian `use ($slug, $type)`
        $games = Cache::remember($cacheKey, now()->addHours(1), function () use ($slug, $type) {
            return \App\Models\Games::where('status', 1) // Asumsi 1 = Aktif
                ->where(function($query) use ($slug, $type) {
                    
                    // Cari berdasarkan provider_code atau provider name
                    // Catatan: Jika 'BOOONGO' tadinya hardcode, saya sarankan ganti jadi strtoupper($slug) agar dinamis
                    $query->where('provider_code', strtoupper($slug)) 
                          ->where('game_type', strtolower($type))
                          ->orWhere('provider', 'LIKE', '%' . str_replace('-', ' ', $slug) . '%');
                })
                // Menambahkan pengurutan berdasarkan kolom sequence dari yang terkecil (ASC)
                ->orderBy('sequence', 'ASC')
                ->get();
        });
    
        // Ambil nama provider dinamis untuk Header (Default ke slug jika kosong)
        $providerName = $games->first()->provider ?? strtoupper(str_replace('-', ' ', $slug));
        Cache::forget("gamelist_{$device}_{$type}_{$slug}"); 
        return view("frontend.{$device}.pages.game.list", compact('games', 'providerName', 'type', 'slug'));
    }
    
    public function promotions()
    {
        // Mengambil data promo yang aktif
        $promotion = DB::table('tb_bonus')
            ->where('status', 'active')
            ->where('type', '=', 1)
            ->get();
    
        return view("frontend.pages.secure.promotions", compact('promotion'));
    }
    
    public function registers(Request $request)
    {
        $request->validate([
            'username'  => 'required|min:6|max:12',
            'email'     => 'required|email',
            'password'  => 'required|min:6',
            'cpassword' => 'required|min:6',
            'phone'     => 'required',
            'bankName'  => 'required',
            'accNumber' => 'required',
            'accName'   => 'required',
        ]);
        
        // 3. Sanitasi Username
        $username = strtolower(preg_replace("/[^a-zA-Z0-9]+/", "", $request->username));
    
        // 4. Cek Duplikasi Data
        if (User::where('username', $username)->exists()) {
            return response()->json([
                'success' => false,
                'message' => 'Username telah terdaftar'
            ], 409);
        }
    
        if (User::where('no_hp', $request->phone)->exists()) {
            return response()->json([
                'success' => false,
                'message' => 'Nomor Telepon telah terdaftar.'
            ], 409);
        }
    
        if ($request->filled('referral') && $request->referral !== 'admin') {
            $checkReferral = Refferal::where('reff_code', $request->referral)->exists();
            
            if (!$checkReferral) {
                return response()->json([
                    'success' => false,
                    'message' => 'Kode Referral tidak valid atau tidak ditemukan!'
                ], 404); // 404: Not Found
            }
        }
        
        $endSgx = new SgxController();
        $endNxs = new NexusController();
        $extplayer = $username . random_string(2);
        $resultNxs = $endNxs->user_create($extplayer);
        $resultSgx = $endSgx->user_create($extplayer);
    
        if ($resultNxs['status'] !== 1 && $resultSgx['status'] !== 200) {
            return response()->json([
                'success' => false,
                'message' => 'Bad Gateway (Masalah dari API pihak ketiga)'
            ], 502); // 502: Bad Gateway (Masalah dari API pihak ketiga)
        }
    
        // 6. Simpan User
        $hashedPassword = Hash::make($request->password);
    
        $user = User::create([
            'extplayer'      => $extplayer,
            'username'       => $username,
            'email'          => $username . '@gmail.com',
            'password'       => $hashedPassword, 
            'cpassword'      => $request->cpassword,
            'nama_lengkap'   => $request->accName,
            'no_hp'          => $request->phone,
            'level'          => 'user',
            'balance'        => 0,
            'refferal'       => $request->referral,
            'status'         => 1,
            'status_game'    => 1,
            'nama_bank'      => $request->bankName,
            'nomor_rekening' => $request->accNumber,
            'nama_pemilik'   => $request->accName,
        ]);
    
        // 7. Simpan Data Referral Baru untuk user tersebut
        $reffs = new Refferal();
        $reffs->user_id = $user->id;
        $reffs->reff_code = $user->username; // Sekarang dia jadi upline buat orang lain
        $reffs->upline = $request->referral;
        $reffs->save();
    
        // 8. Finalisasi
        Auth::login($user);
        return response()->json([
            'success' => true,
            'message' => 'Registrasi Sukses, Selamat Bergabung!',
            'redirect_url' => route('secure.home')
        ], 201);
    }


    public function v2_acc_login(Request $request)
    {
        // 1. Cari User
        $check_us = User::where('username', $request->username)->first();
        if (empty($check_us)) {
            return response()->json(['success' => false, 'message' => 'Username tidak ditemukan'], 403);
        }
    
        // 2. Validasi Input Kosong (Hanya Password)
        if (empty($request->password)) {
            return response()->json(['success' => false, 'message' => 'Kata sandi tidak boleh kosong'], 403);
        }
    
        // 3. Cek Kecocokan Password
        if (!Hash::check($request->password, $check_us->password)) { 
            return response()->json([
                'success' => false,
                'message' => 'Kata sandi tidak sesuai.',
                'redirect_url' => '/'
            ], 403);
        } 
    
        // 4. Login Berhasil
        Auth::login($check_us);
        
        return response()->json([
            'success' => true,
            'message' => 'Logging in..',
            'redirect_url' => route('secure.home')
        ], 200);
    }
    
    // --- FUNGSI UTAMA (HELPER) ---
    private function generateCaptcha($sessionName, $width = 70, $height = 34, $length = 3)
    {
        // Ukuran font yang pas
        $fontSize = 18; 
        // Sangat disarankan menggunakan font Serif Italic (seperti Times New Roman Italic) agar 100% mirip
        $font_file = storage_path('app/public/uploads/Oswald-VariableFont_wght.ttf');
        $use_ttf = file_exists($font_file);
    
        // 1. Generate Kode (HANYA ANGKA)
        $chars = '0123456789';
        $captcha_code = '';
        for ($i = 0; $i < $length; $i++) {
            $captcha_code .= $chars[rand(0, strlen($chars) - 1)];
        }
    
        Session::put($sessionName, $captcha_code);
        Session::save();
    
        // 2. Canvas & Warna (DIUBAH KE TEMA PUTIH)
        $image = imagecreatetruecolor($width, $height);
        
        $bg_color = imagecolorallocate($image, 255, 255, 255);       // Background Putih
        $text_color = imagecolorallocate($image, 0, 0, 0);           // Teks Utama Hitam
        $bg_text_color = imagecolorallocate($image, 200, 200, 200);  // Teks Background Abu-abu Terang
    
        imagefill($image, 0, 0, $bg_color);
    
        // 3. Teks Background Berulang (Menggantikan titik & garis agar mirip foto)
        if ($use_ttf) {
            $bg_text = $captcha_code . "6a"; // Pola teks di belakang
            $start_x_bg = -10;
            $start_y_bg = 15;
            
            for ($baris = 0; $baris < 3; $baris++) {
                $x_bg = $start_x_bg;
                for ($kolom = 0; $kolom < 8; $kolom++) {
                    // Ukuran font background dibuat lebih kecil (12)
                    imagettftext($image, 12, 0, $x_bg, $start_y_bg, $bg_text_color, $font_file, $bg_text[$kolom % strlen($bg_text)]);
                    $x_bg += 15; // Jarak horizontal teks background
                }
                $start_y_bg += 15; // Jarak vertikal
                $start_x_bg += 5;  // Geser miring
            }
        } else {
            // Fallback jika font TTF tidak terbaca
            for($i = 0; $i < 30; $i++) {
                imagechar($image, 3, rand(-10, $width), rand(-10, $height), $chars[rand(0,9)], $bg_text_color);
            }
        }
    
        // 4. Teks Utama Hitam
        if ($use_ttf) {
            // Jarak antar huruf diperkecil menjadi 12 agar angkanya tumpang tindih (overlap)
            $char_width = 12; 
            $start_x = ($width - ($length * $char_width)) / 2;
    
            for ($i = 0; $i < $length; $i++) {
                $y = rand(24, 26); 
                $angle = rand(-5, 5); // Kemiringan dibuat tipis saja
                
                // Render Teks Hitam
                imagettftext($image, $fontSize, $angle, $start_x, $y, $text_color, $font_file, $captcha_code[$i]);
                
                $start_x += $char_width;
            }
        } else {
            $char_width = imagefontwidth(5);
            $start_x = ($width - ($length * $char_width) - (($length - 1) * 2)) / 2;
            
            for ($i = 0; $i < $length; $i++) {
                $y = ($height - imagefontheight(5)) / 2;
                imagechar($image, 5, $start_x, $y + rand(-2, 2), $captcha_code[$i], $text_color);
                $start_x += $char_width + 2;
            }
        }
    
        // 5. Output (Cara Standar Laravel)
        ob_start();
        imagejpeg($image, NULL, 100); // Kualitas dinaikkan ke 100% agar bersih
        $imageData = ob_get_clean();
        imagedestroy($image);
    
        // Kembalikan sebagai Response Laravel
        return response($imageData)
            ->header('Content-Type', 'image/jpeg')
            ->header('Cache-Control', 'no-cache, no-store, must-revalidate'); // Mencegah browser menyimpan gambar lama
    }
    
    // --- PUBLIC FUNCTIONS (TINGGAL PANGGIL) ---
    
    public function captchaimg() 
    {
        // BENAR: Abaikan parameter '?value=' dari URL.
        // Langsung tetapkan (hardcode) nama session-nya sebagai 'capreg'
        // agar persis sama dengan yang dicari oleh HomeController@registers
        $sessionName = 'captchaimg'; 
        
        return $this->generateCaptcha($sessionName); 
    }
    
    // Contoh logika pembuatan Captcha khusus Login
    public function captchaimg_login() 
    {
        $sessionName = 'capimg'; // Pakai nama ini agar pas dengan pengecekan di fungsi login
        return $this->generateCaptcha($sessionName); 
    }
    
    public function showPage($slug)
    {
        // Daftar halaman yang diizinkan beserta judulnya
        $pages = [
            'aboutus' => 'Tentang Kami',
            'tnc' => 'Syarat & Ketentuan',
            'policy' => 'Kebijakan Pribadi',
            'responsible-gaming' => 'Tanggung Jawab',
            'faq' => 'Pusat Info',
            'contact' => 'Hubungi Kami'
        ];

        // Jika user mengakses URL ngawur, lempar ke halaman 404
        if (!array_key_exists($slug, $pages)) {
            abort(404);
        }

        $title = $pages[$slug];

        // Kirim $slug dan $title ke view
        return view("frontend.pages.secure.info", compact('slug', 'title'));
    }
}
