<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use App\Models\Refferal;
use Illuminate\Support\Facades\Session;
use App\Models\Transaction;
use App\Http\Controllers\Api\SeamlesWsController;
use Illuminate\Support\Str;
use App\Models\User;

class UserController extends Controller
{
    public function profile($device = 'desktop')
    {
        $user = auth()->user();
        
        // Ambil data referral
        $myReff = \Illuminate\Support\Facades\DB::table('tb_refferal')->where('user_id', $user->id)->first();
        $refCode = $myReff ? $myReff->reff_code : '-';
        $refLink = $myReff ? url('/register?ref=' . $refCode) : url('/');
        
        // Generate URL QR Code
        $qrCodeUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=' . urlencode($refLink);
    
        return view("frontend.pages.secure.profile", compact('refCode', 'refLink', 'qrCodeUrl'));
    }
    
    public function message(Request $request)
    {
        $user = auth()->user();
    
        $inbox = \Illuminate\Support\Facades\DB::table('tb_memo')
            ->where('username', $user->username)
            ->orderBy('created_at', 'desc')
            ->get();
    
        $announcements = \Illuminate\Support\Facades\DB::table('tb_memo')
            ->where('username', 'all') 
            ->orderBy('created_at', 'desc')
            ->get();
    
        return view("frontend.pages.secure.message", compact('inbox', 'announcements'));
    }
    
    public function readMessage(Request $request)
    {
        $id = $request->input('msgID');
        
        \Illuminate\Support\Facades\DB::table('tb_memo')
            ->where('id', $id)
            ->where('username', auth()->user()->username)
            ->update(['status_baca' => 1]);
    
        return response()->json(['success' => true]);
    }
    
    public function referral(Request $request)
    {
        $user = auth()->user();
        
        // 1. Ambil data referral user
        $myReff = DB::table('tb_refferal')->where('user_id', $user->id)->first();
        $refCode = $myReff ? $myReff->reff_code : '-';
        $refLink = $myReff ? url('/ref'.'?rid=' . $refCode) : url('/');
    
        // 2. Setup Filter Tanggal (Dari Daterangepicker format DD-MM-YYYY)
        $isSearch = $request->has('start_date');
        $startDate = $request->input('start_date', now()->startOfMonth()->format('Y-m-d'));
        $endDate = $request->input('end_date', now()->format('Y-m-d'));
    
        $totalReferral = 0;
        $bonusData = [];
        $totalAllBonus = 0;
        $downlineData = collect(); // Koleksi untuk tabel DataTables
    
        if ($myReff) {
            $totalReferral = DB::table('tb_refferal')->where('upline', $refCode)->count();
    
            // Query filter downline
            $query = DB::table('tb_refferal')->where('upline', $refCode)->orderBy('created_at', 'desc');
    
            if ($isSearch) {
                $query->whereBetween('created_at', [$startDate . ' 00:00:00', $endDate . ' 23:59:59']);
            }
    
            $downlines = $query->get();
    
            // 3. Looping Data Downline (Aman & Cepat karena pakai DB Lokal)
            foreach ($downlines as $downline) {
                $username = $downline->reff_code;
    
                // Ambil data stat TO & Winlose dari tabel baru
                $stats = DB::table('tb_user_stats')->where('username', $username)->first();
                $turnover = $stats ? $stats->turnover : 0;
                $winlose = $stats ? $stats->winlose : 0;
                $lastLogin = $stats ? $stats->last_login : null;
    
                // Hitung Depo/WD Pertama dan Terakhir
                $firstDepo = DB::table('tb_transaksi')->where('transaksi', 'Top Up')->where('username', $username)->where('status', 'Sukses')->orderBy('created_at', 'asc')->value('created_at');
                $lastDepo = DB::table('tb_transaksi')->where('transaksi', 'Top Up')->where('username', $username)->where('status', 'Sukses')->orderBy('created_at', 'desc')->value('created_at');
    
                // Kalkulasi Bonus (Depo - WD)
                $totalDeposit = DB::table('tb_transaksi')->where('transaksi', 'Top Up')->where('username', $username)->where('status', 'Sukses')->sum('total');
                $totalWithdraw = DB::table('tb_transaksi')->where('transaksi', 'Withdraw')->where('username', $username)->where('bonus', 'tanpabonus')->where('status', 'Sukses')->sum('total');
    
                $amount = $totalDeposit - $totalWithdraw;
                $bonus = $amount > 0 ? $amount * (10 / 100) : 0;
    
                if ($bonus > 0) {
                    $bonusData[] = [
                        'username' => $username,
                        'jumlah'   => $bonus
                    ];
                    $totalAllBonus += $bonus;
                }
    
                // Simpan data untuk dirender ke tabel Blade
                $downlineData->push((object)[
                    'username' => $username,
                    'turnover' => $turnover,
                    'winlose' => $winlose,
                    'register_date' => $downline->created_at,
                    'last_login' => $lastLogin,
                    'first_depo' => $firstDepo,
                    'last_depo' => $lastDepo,
                ]);
            }
        }
    
        // Format ulang format tanggal untuk plugin Daterangepicker di View
        $startDateFmt = date('d-m-Y', strtotime($startDate));
        $endDateFmt = date('d-m-Y', strtotime($endDate));
    
        return view("frontend.pages.secure.referral", compact(
            'totalReferral', 'bonusData', 'totalAllBonus', 
            'startDateFmt', 'endDateFmt', 'isSearch', 'refCode', 'refLink', 'downlineData'
        ));
    }
    
    public function syncHistoryMember(Request $request)
    {
        // 1. KEAMANAN: Pastikan URL ini tidak bisa diakses sembarang orang
        // Anda bisa memanggilnya dengan URL: domain.com/api/cron/sync-history?token=mantra88rahasia
        if ($request->token !== 'mantra88rahasia') {
            return response()->json(['error' => 'Unauthorized Akses!'], 401);
        }

        // 2. Batasi waktu eksekusi agar tidak terputus di tengah jalan
        set_time_limit(120); 

        // 3. AMBIL DATA DENGAN SISTEM ANTREAN
        // Ambil 30 user yang 'last_sync'-nya paling lama tertinggal / belum pernah ditarik.
        $users = DB::table('users')
            ->leftJoin('tb_user_stats', 'users.username', '=', 'tb_user_stats.username')
            ->select('users.username', 'users.extplayer', 'tb_user_stats.last_sync')
            ->orderBy('tb_user_stats.last_sync', 'asc') // Yang null atau terlama akan naik ke atas
            ->limit(30) // Proses 30 user setiap kali cron berjalan agar API tidak jebol
            ->get();

        if ($users->isEmpty()) {
            return response()->json(['message' => 'Tidak ada user untuk disinkronkan.']);
        }

        $apiController = new SeamlesWsController();
        $endTime = now()->format('Y-m-d H:i:s');
        $gameTypes = ['slot', 'casino', 'sport'];

        $berhasil = 0;

        // 4. LOOPING PROSES DATA
        foreach ($users as $u) {
            // Jika belum pernah ditarik, mulai dari awal tahun. Jika sudah, mulai dari waktu terakhir ditarik
            $startTime = $u->last_sync ? $u->last_sync : '2026-01-01 00:00:00';
            
            $newTurnover = 0;
            $newWinLose = 0;

            // Tarik API untuk setiap tipe game
            foreach ($gameTypes as $type) {
                try {
                    $apiResponse = $apiController->getGameHistory($u->extplayer, $type, $startTime, $endTime);
                    $result = json_decode($apiResponse, true);

                    if (isset($result['status']) && $result['status'] == 1 && isset($result[$type])) {
                        foreach ($result[$type] as $item) {
                            $bet = (float)($item['bet_money'] ?? 0);
                            $win = (float)($item['win_money'] ?? 0);
                            
                            $newTurnover += $bet;
                            $newWinLose += ($win - $bet);
                        }
                    }
                } catch (\Exception $e) {
                    // Abaikan error pada satu API agar user lain tetap terproses
                    continue; 
                }
            }

            // 5. UPDATE KE DATABASE LOKAL (Menggunakan Akumulasi Tambahan)
            DB::table('tb_user_stats')->updateOrInsert(
                ['username' => $u->username], // Cari berdasarkan username
                [
                    // Tambahkan nominal baru ke nominal lama (biar TO nya nambah terus)
                    'turnover' => DB::raw("turnover + $newTurnover"),
                    'winlose' => DB::raw("winlose + $newWinLose"),
                    'last_sync' => $endTime, // Catat waktu tarikan terbaru
                    'updated_at' => now()
                ]
            );

            $berhasil++;
        }

        return response()->json([
            'status' => 'success',
            'message' => "Berhasil mensinkronkan data history untuk $berhasil member.",
            'timestamp_tarikan' => $endTime
        ]);
    }
    
    public function update(Request $request)
    {
        if(Hash::check($request->oldpassword,auth()->user()->password)) {
            $user = User::find(auth()->user()->id);
            $user->password = Hash::make($request->newpassword);
            $user->save();
            return response()->json([
                'success' => true,
                'code' => 200,
                'data' => [
                    'message' => 'Kata sandi berhasil diubah'
                ]
            ]);
        } else {
            return response()->json([
                'success' => false,
                'code' => 12145,
                'data' => [
                    'message' => 'Kata sandi lama salah'
                ]
            ]);
        }
    }
    
    public function forgotPassword(Request $request)
    {
        // 1. Validasi Input (Tanpa Telegram)
        $request->validate([
            'username' => 'required|string|min:6|max:12',
            'email'    => 'required|email|max:255',
            'mobile'   => 'required|string|min:7|max:15',
        ]);

        // 2. Cek kecocokan data di Database
        $user = User::where('username', $request->username)
                    ->where('email', $request->email)
                    ->where('no_hp', $request->mobile) 
                    ->first();

        if (!$user) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Data yang Anda masukkan tidak cocok dengan sistem kami.'
            ]);
        }

        // 3. AUTO-GENERATE PASSWORD BARU
        $newPassword = Str::random(8); // 8 Karakter acak
        
        // 4. UPDATE KE DATABASE
        $user->password = Hash::make($newPassword);
        $user->save();

        // 5. Kirim balasan sukses BERSERTA PASSWORD BARU ke tampilan HTML
        return response()->json([
            'status'       => 'success',
            'message'      => 'Verifikasi berhasil! Berikut adalah password baru Anda.',
            'new_password' => $newPassword
        ]);
    }
}
