<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Transaction;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;
use Carbon\Carbon;
use App\Http\Controllers\Api\SeamlesWsController;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        $end = new SeamlesWsController();
        $result = json_decode($end->agentBalance(), true);
        if ($result['status'] == 1) {
            $agentBalance = $result['agent']['balance'] ?? 0;
        } else {
            $agentBalance = 0;
        }
        $userall = User::whereYear('created_at', now()->year)->count();
        $useralldp = User::where('deposit', 1)->whereYear('created_at', now()->year)->count();
        $userallxdp = User::where('deposit', 0)->whereYear('created_at', now()->year)->count();
        $userallwd = User::where('withdraw', 1)->whereYear('created_at', now()->year)->count();
        $dpsuccall = Transaction::where('transaksi', 'Top Up')->where('status', 'Sukses')->whereYear('created_at', now()->year)->sum('total');
        $dprejall = Transaction::where('transaksi', 'Top Up')->where('status', 'Ditolak')->whereYear('created_at', now()->year)->count();
        $wdsuccall = Transaction::where('transaksi', 'Withdraw')->where('status', 'Sukses')->whereYear('created_at', now()->year)->sum('total');
        $bonusall = Transaction::where('transaksi', 'Top Up')->where('status', 'Sukses')->whereYear('created_at', now()->year)->sum('bonus_amount');
        $profit = $dpsuccall - $wdsuccall - $bonusall;

        $useram = User::whereMonth('created_at', now()->month)->count();
        $useramdp = User::where('deposit', 1)->whereMonth('created_at', now()->month)->count();
        $useramxdp = User::where('deposit', 0)->whereMonth('created_at', now()->month)->count();
        $useramlwd = User::where('withdraw', 1)->whereMonth('created_at', now()->month)->count();
        $dpsuccm = Transaction::where('transaksi', 'Top Up')->where('status', 'Sukses')->whereMonth('created_at', now()->month)->sum('total');
        $dprejm = Transaction::where('transaksi', 'Top Up')->where('status', 'Ditolak')->whereMonth('created_at', now()->month)->count();
        $wdsuccm = Transaction::where('transaksi', 'Withdraw')->where('status', 'Sukses')->whereMonth('created_at', now()->month)->sum('total');
        $bonusm = Transaction::where('transaksi', 'Top Up')->where('status', 'Sukses')->whereMonth('created_at', now()->month)->sum('bonus_amount');

        $userays = User::whereDate('created_at', now())->count();
        $useraysdp = User::where('deposit', 1)->whereDate('created_at', now())->count();
        $useraysxdp = User::where('deposit', 0)->whereDate('created_at', now())->count();
        $userayslwd = User::where('withdraw', 1)->whereDate('created_at', now())->count();
        $dpsuccys = Transaction::where('transaksi', 'Top Up')->where('status', 'Sukses')->whereDate('created_at', now())->sum('total');
        $dprejys = Transaction::where('transaksi', 'Top Up')->where('status', 'Ditolak')->whereDate('created_at', now())->count();
        $wdsuccys = Transaction::where('transaksi', 'Withdraw')->where('status', 'Sukses')->whereDate('created_at', now())->sum('total');
        $bonusys = Transaction::where('transaksi', 'Top Up')->where('status', 'Sukses')->whereDate('created_at', now())->sum('bonus_amount');

        return view('backend.dashboard', compact('userall','useralldp','userallxdp','userallwd','dpsuccall','dprejall','wdsuccall','bonusall','profit','useram','useramdp',
        'useramxdp','useramlwd','dpsuccm','dprejm','wdsuccm','bonusm','userays','useraysdp','useraysxdp','userayslwd','dpsuccys','dprejys','wdsuccys','bonusys', 'agentBalance'));
    }

    private function generateDailyReport()
    {
        try {
            // Ambil rekap harian dari tb_transaksi
            // Ditambahkan REPLACE untuk mengatasi jika ada format angka menggunakan koma
            $dailyStats = DB::table('tb_transaksi')
                ->selectRaw("
                    DATE(created_at) as report_date,
                    COUNT(DISTINCT id_user) as members,
                    COUNT(CASE WHEN transaksi = 'Top Up' THEN 1 END) as no_deposit,
                    SUM(CASE WHEN transaksi = 'Top Up' THEN CAST(REPLACE(total, ',', '') AS DECIMAL(15,2)) ELSE 0 END) as deposit,
                    SUM(CASE WHEN transaksi = 'Top Up' AND status = 'Sukses' THEN CAST(REPLACE(total, ',', '') AS DECIMAL(15,2)) ELSE 0 END) as deposit_success,
                    SUM(CASE WHEN transaksi = 'Top Up' AND status = 'Ditolak' THEN CAST(REPLACE(total, ',', '') AS DECIMAL(15,2)) ELSE 0 END) as depo_reject,
                    SUM(CASE WHEN transaksi = 'Withdraw' THEN CAST(REPLACE(total, ',', '') AS DECIMAL(15,2)) ELSE 0 END) as withdraw,
                    SUM(CASE WHEN transaksi = 'Withdraw' AND status = 'Sukses' THEN CAST(REPLACE(total, ',', '') AS DECIMAL(15,2)) ELSE 0 END) as withdraw_success,
                    SUM(CASE WHEN transaksi = 'Withdraw' AND status = 'Ditolak' THEN CAST(REPLACE(total, ',', '') AS DECIMAL(15,2)) ELSE 0 END) as wd_reject,
                    SUM(CASE WHEN bonus_amount IS NOT NULL AND bonus_amount != '' THEN CAST(REPLACE(bonus_amount, ',', '') AS DECIMAL(15,2)) ELSE 0 END) as bonus
                ")
                ->whereNotNull('created_at')
                ->groupBy(DB::raw('DATE(created_at)'))
                ->get();

            // Masukkan atau update ke tabel reports
            foreach ($dailyStats as $stat) {
                // Rumus Profit = (Deposit Sukses) - (Withdraw Sukses) - (Total Bonus)
                $profit = $stat->deposit_success - $stat->withdraw_success - $stat->bonus;

                DB::table('reports')->updateOrInsert(
                    ['created_at' => $stat->report_date . ' 00:00:00'], // Jadikan tanggal sebagai unique key untuk hari itu
                    [
                        'members'          => (string)$stat->members,
                        'no_deposit'       => (string)$stat->no_deposit,
                        'deposit'          => (string)$stat->deposit,
                        'deposit_success'  => (string)$stat->deposit_success,
                        'depo_reject'      => (string)$stat->depo_reject,
                        'withdraw'         => (string)$stat->withdraw,
                        'withdraw_success' => (string)$stat->withdraw_success,
                        'wd_reject'        => (string)$stat->wd_reject,
                        'bonus'            => (string)$stat->bonus,
                        'profit'           => (string)$profit,
                        'updated_at'       => now()
                    ]
                );
            }
        } catch (\Exception $e) {
            // Mencegah halaman error putih jika ada query yang salah, dicatat ke log
            \Illuminate\Support\Facades\Log::error('Gagal generate daily report: ' . $e->getMessage());
        }
    }

    public function reports(Request $request)
    {
        // 1. Sinkronisasi HANYA berjalan saat akses halaman web biasa. 
        // TIDAK berjalan saat DataTables melakukan AJAX (seperti ganti halaman/filter).
        // Ini menyelamatkan server dari overload.
        if (!$request->ajax()) {
            $this->generateDailyReport();
        }

        if ($request->ajax()) {
            $query = DB::table('reports');

            // 2. Filter Custom Date
            if ($request->filled('from_date') && $request->filled('to_date')) {
                // Tambahkan waktu agar mencakup satu hari penuh
                $fromDate = $request->from_date . ' 00:00:00';
                $toDate = $request->to_date . ' 23:59:59';
                $query->whereBetween('created_at', [$fromDate, $toDate]);
            } else {
                // Default tampilkan 30 hari terakhir jika tidak ada filter
                $query->where('created_at', '>=', \Carbon\Carbon::now()->subDays(30));
            }

            $trans = $query->orderBy('created_at', 'desc');

            // Float casting (float)$row ditambahkan karena field varchar di database
            return DataTables::of($trans)
                ->addIndexColumn()
                ->editColumn('created_at', function ($row) {
                    // translatedFormat akan mengubah nama bulan ke bahasa Indonesia
                    return \Carbon\Carbon::parse($row->created_at)
                        ->translatedFormat('d F Y'); 
                })
                ->editColumn('members', function ($row) {
                    return number_format((float)$row->members);
                })
                ->editColumn('no_deposit', function ($row) {
                    return number_format((float)$row->no_deposit);
                })
                ->editColumn('deposit', function ($row) {
                    return 'Rp ' . number_format((float)$row->deposit, 0, ',', '.');
                })
                ->editColumn('deposit_success', function ($row) {
                    return '<span class="text-success fw-bold">Rp ' . number_format((float)$row->deposit_success, 0, ',', '.') . '</span>';
                })
                ->editColumn('withdraw', function ($row) {
                    return 'Rp ' . number_format((float)$row->withdraw, 0, ',', '.');
                })
                ->editColumn('withdraw_success', function ($row) {
                    return '<span class="text-danger fw-bold">Rp ' . number_format((float)$row->withdraw_success, 0, ',', '.') . '</span>';
                })
                ->editColumn('bonus', function ($row) {
                    return 'Rp ' . number_format((float)$row->bonus, 0, ',', '.');
                })
                ->editColumn('profit', function ($row) {
                    $color = (float)$row->profit >= 0 ? 'text-success' : 'text-danger';
                    return '<span class="' . $color . ' fw-bold">Rp ' . number_format((float)$row->profit, 0, ',', '.') . '</span>';
                })
                ->rawColumns(['deposit_success', 'withdraw_success', 'profit']) // Render HTML
                ->make(true);
        }

        return view('backend.report.index'); // Sesuaikan dengan path view kamu
    }

    public function balance()
    {
        $api = DB::table('api_actives')->find(1);
        $apis = DB::table('api_providers')->find($api->provider_id);

        if ($api->provider_id == 1) {
            $endpoint = $apis->url;
            $postArray = [
                'method' => $apis->apikey,
                'agent_code' => $apis->apikey,
                'agent_token' => $apis->secretkey
            ];
        } else {
            $endpoint = $apis->url;
            $postArray = [
                'method' => 'money_info',
                'agent_code' => $apis->apikey,
                'agent_token' => $apis->secretkey
            ];
        }

        $jsonData = json_encode($postArray);

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $endpoint,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $jsonData,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
            ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        $result = json_decode($response);

        $balance = number_format($result->agent->balance, 2);
        return response()->json(['balance' => $balance]);
    }

    public function cron()
    {
        $check = DB::table('reports')->whereDate('created_at', now())->first();
        $members = User::whereDate('created_at', now())->count();
        $deposit = User::where('deposit', 1)->whereDate('created_at', now())->count();
        $no_deposit = User::where('deposit', 0)->whereDate('created_at', now())->count();
        $withdraw = User::where('withdraw', 1)->whereDate('created_at', now())->count();
        $deposit_success = Transaction::where('transaksi', 'Top Up')->where('status', 'Sukses')->whereDate('created_at', now())->sum('total');
        $depo_reject = Transaction::where('transaksi', 'Top Up')->where('status', 'Ditolak')->whereDate('created_at', now())->count();
        $withdraw_success = Transaction::where('transaksi', 'Withdraw')->where('status', 'Sukses')->whereDate('created_at', now())->sum('total');
        $wd_reject = Transaction::where('transaksi', 'Withdraw')->where('status', 'Ditolak')->whereDate('created_at', now())->sum('total');
        $bonus = Transaction::where('transaksi', 'Top Up')->where('status', 'Sukses')->whereDate('created_at', now())->sum('bonus_amount');
        $profit = $deposit_success - $withdraw_success - $bonus;

        if (!$check) {
            DB::table('reports')->insert([
                'members' => $members,
                'deposit' => $deposit,
                'no_deposit' => $no_deposit,
                'withdraw' => $withdraw,
                'deposit_success' => $deposit_success,
                'withdraw_success' => $withdraw_success,
                'bonus' => $bonus,
                'depo_reject' => $depo_reject,
                'wd_reject' => $wd_reject,
                'profit' => $profit,
                'created_at' => date("Y-m-d H:i:s"),
                'updated_at' => date("Y-m-d H:i:s")
            ]);
        } else {
            DB::table('reports')->whereDate('created_at', now())->update([
                'members' => $members,
                'deposit' => $deposit,
                'no_deposit' => $no_deposit,
                'withdraw' => $withdraw,
                'deposit_success' => $deposit_success,
                'withdraw_success' => $withdraw_success,
                'bonus' => $bonus,
                'depo_reject' => $depo_reject,
                'wd_reject' => $wd_reject,
                'profit' => $profit,
                'updated_at' => date("Y-m-d H:i:s")
            ]);
        }

        return response()->json(['status' => 'Success']);
    }
}
