<?php

namespace Tests\Feature;

use App\Http\Controllers\Admin\DashboardController;
use App\Models\GmailSale;
use App\Models\GmailSellSetting;
use App\Models\IncomeHistory;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;

class AdminDashboardHiddenBalanceTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        $this->createTables();
        Http::fake();
    }

    public function test_dashboard_fund_totals_exclude_hidden_users(): void
    {
        User::factory()->create([
            'balance' => 125.5,
            'voucher_balance' => 30,
            'is_active' => 1,
            'is_hidden' => 0,
        ]);

        User::factory()->create([
            'balance' => 999,
            'voucher_balance' => 777,
            'is_active' => 1,
            'is_hidden' => 1,
        ]);

        $view = (new DashboardController())->index();
        $data = $view->getData();

        $this->assertSame('admin.dashboard', $view->getName());
        $this->assertSame(125.5, (float) $data['totalBalanceFund']);
        $this->assertSame(30.0, (float) $data['totalVoucherFund']);
        $this->assertSame(1, (int) $data['totalUsers']);
        $this->assertSame(1, (int) $data['activeUsers']);
    }

    public function test_dashboard_gmail_cards_include_user_payment_all_and_admin_profit(): void
    {
        Carbon::setTestNow(Carbon::create(2026, 3, 17, 12, 0, 0, 'Asia/Dhaka'));

        GmailSellSetting::create([
            'price' => 10.00,
            'admin_price' => 15.00,
        ]);

        GmailSale::create([
            'rate' => 10.00,
            'admin_price' => 15.00,
            'upline_commissions_snapshot' => [0.50, 0.25],
            'status' => 'completed',
            'updated_at' => now('Asia/Dhaka'),
            'created_at' => now('Asia/Dhaka'),
        ]);

        GmailSale::create([
            'rate' => 8.00,
            'admin_price' => 12.00,
            'upline_commissions_snapshot' => [1.00],
            'status' => 'completed',
            'updated_at' => now('Asia/Dhaka'),
            'created_at' => now('Asia/Dhaka'),
        ]);

        GmailSale::create([
            'rate' => 99.00,
            'admin_price' => 199.00,
            'upline_commissions_snapshot' => [50.00],
            'status' => 'pending',
            'updated_at' => now('Asia/Dhaka'),
            'created_at' => now('Asia/Dhaka'),
        ]);

        $view = (new DashboardController())->index();
        $data = $view->getData();

        $this->assertSame(19.75, (float) $data['gmailUserPaymentAll']);
        $this->assertSame(9.0, (float) $data['gmailAdminProfit']);
        $this->assertSame(18.0, (float) $data['gmailTotalAmount']);

        Carbon::setTestNow();
    }

    public function test_dashboard_gmail_cards_use_legacy_income_history_when_sale_snapshots_are_missing(): void
    {
        Carbon::setTestNow(Carbon::create(2026, 3, 17, 12, 0, 0, 'Asia/Dhaka'));

        GmailSellSetting::create([
            'price' => 10.00,
            'admin_price' => 15.00,
            'upline_commissions' => [0.50, 0.25],
        ]);

        $seller = User::factory()->create([
            'referral_code' => 'SELL-200',
            'balance' => 0,
            'is_hidden' => 0,
        ]);

        $upline = User::factory()->create([
            'referral_code' => 'UP-200',
            'balance' => 0,
            'is_hidden' => 0,
        ]);

        $sale = GmailSale::create([
            'user_id' => $seller->id,
            'status' => 'completed',
            'created_at' => now('Asia/Dhaka'),
            'updated_at' => now('Asia/Dhaka'),
        ]);

        IncomeHistory::create([
            'user_id' => $seller->id,
            'source' => 'gmail_sale',
            'amount' => 8.25,
            'description' => 'Legacy Gmail payout for Submission #' . $sale->id,
        ]);

        IncomeHistory::create([
            'user_id' => $upline->id,
            'source' => 'gmail_sale_referral',
            'amount' => 1.50,
            'description' => 'Legacy referral from ' . $seller->name . ' (' . $seller->referral_code . ') Submission #' . $sale->id,
        ]);

        $view = (new DashboardController())->index();
        $data = $view->getData();

        $this->assertSame(8.25, (float) $data['gmailTotalAmount']);
        $this->assertSame(9.75, (float) $data['gmailUserPaymentAll']);
        $this->assertSame(6.75, (float) $data['gmailAdminProfit']);

        Carbon::setTestNow();
    }

    public function test_dashboard_gmail_cards_start_fresh_after_stats_reset_time(): void
    {
        Carbon::setTestNow(Carbon::create(2026, 3, 17, 12, 0, 0, 'Asia/Dhaka'));

        Schema::getConnection()->table('gmail_sell_settings')->insert([
            'price' => 10.00,
            'admin_price' => 15.00,
            'stats_reset_at' => now(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $oldSale = GmailSale::create([
            'rate' => 9.00,
            'admin_price' => 14.00,
            'upline_commissions_snapshot' => [1.00],
            'status' => 'completed',
        ]);

        $newSale = GmailSale::create([
            'rate' => 11.00,
            'admin_price' => 16.00,
            'upline_commissions_snapshot' => [0.50],
            'status' => 'completed',
        ]);

        Schema::getConnection()->table('gmail_sales')->where('id', $oldSale->id)->update([
            'created_at' => now()->subHour(),
            'updated_at' => now()->subHour(),
        ]);

        Schema::getConnection()->table('gmail_sales')->where('id', $newSale->id)->update([
            'created_at' => now()->addMinute(),
            'updated_at' => now()->addMinute(),
        ]);

        $view = (new DashboardController())->index();
        $data = $view->getData();

        $this->assertSame(11.0, (float) $data['gmailTotalAmount']);
        $this->assertSame(11.5, (float) $data['gmailUserPaymentAll']);
        $this->assertSame(5.0, (float) $data['gmailAdminProfit']);

        Carbon::setTestNow();
    }

    private function createTables(): void
    {
        Schema::dropIfExists('income_histories');
        Schema::dropIfExists('balance_logs');
        Schema::dropIfExists('in_accounts');
        Schema::dropIfExists('fb_submissions');
        Schema::dropIfExists('recharges');
        Schema::dropIfExists('gmail_sell_settings');
        Schema::dropIfExists('gmail_sales');
        Schema::dropIfExists('withdraws');
        Schema::dropIfExists('users');

        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->string('mobile')->nullable();
            $table->string('referred_by')->nullable();
            $table->string('referral_code')->nullable();
            $table->decimal('balance', 12, 2)->default(0);
            $table->decimal('voucher_balance', 12, 2)->default(0);
            $table->boolean('is_active')->default(false);
            $table->boolean('is_banned')->default(false);
            $table->boolean('is_hidden')->default(false);
            $table->dateTime('activated_at')->nullable();
            $table->timestamps();
        });

        Schema::create('withdraws', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable();
            $table->decimal('amount', 12, 2)->default(0);
            $table->string('status')->nullable();
            $table->timestamps();
        });

        Schema::create('gmail_sales', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable();
            $table->decimal('rate', 12, 2)->nullable();
            $table->decimal('admin_price', 12, 2)->nullable();
            $table->json('upline_commissions_snapshot')->nullable();
            $table->string('status')->nullable();
            $table->timestamps();
        });

        Schema::create('gmail_sell_settings', function (Blueprint $table) {
            $table->id();
            $table->decimal('price', 12, 2)->default(0);
            $table->decimal('admin_price', 12, 2)->default(0);
            $table->timestamp('stats_reset_at')->nullable();
            $table->json('upline_commissions')->nullable();
            $table->timestamps();
        });

        Schema::create('balance_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable();
            $table->decimal('amount', 12, 2)->default(0);
            $table->string('type')->nullable();
            $table->timestamps();
        });

        Schema::create('income_histories', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable();
            $table->string('source');
            $table->decimal('amount', 12, 2)->default(0);
            $table->text('description')->nullable();
            $table->timestamps();
        });

        Schema::create('recharges', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable();
            $table->decimal('amount', 12, 2)->default(0);
            $table->string('status')->nullable();
            $table->timestamps();
        });

        Schema::create('fb_submissions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable();
            $table->string('status')->nullable();
            $table->dateTime('created_at')->nullable();
        });

        Schema::create('in_accounts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable();
            $table->string('status')->nullable();
            $table->timestamps();
        });
    }
}
