<?php

namespace Tests\Feature;

use App\Http\Middleware\LogAdminActivity;
use App\Models\Admin;
use App\Models\DailyEntry;
use App\Models\DailySheet;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;

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

        $this->createTables();
        Config::set('finance.daily_pin', '4321');
    }

    public function test_finance_store_ignores_blank_rows_and_tracks_admin_creator(): void
    {
        $admin = $this->makeAdmin();

        $response = $this->withoutMiddleware([
            LogAdminActivity::class,
        ])->actingAs($admin, 'admin')->post(route('admin.finance.store'), [
            'sheet_date' => '2026-03-24',
            'count_i' => 3,
            'count_b' => 1,
            'count_lab' => 0,
            'count_loc' => 2,
            'notes' => 'Daily closing note',
            'pin' => '4321',
            'entries' => [
                [
                    'khat' => 'Recharge Commission',
                    'type' => 'in',
                    'amount' => '150.50',
                    'remark' => 'Morning batch',
                ],
                [
                    'khat' => '',
                    'type' => 'out',
                    'amount' => '',
                    'remark' => '',
                ],
                [
                    'khat' => 'Office Snacks',
                    'type' => 'out',
                    'amount' => '25',
                    'remark' => 'Tea',
                ],
            ],
        ]);

        $response->assertRedirect(route('admin.finance.index', [
            'from' => '2026-03-24',
            'to' => '2026-03-24',
        ]));
        $response->assertSessionHas('success');

        $sheet = DailySheet::query()->whereDate('sheet_date', '2026-03-24')->first();

        $this->assertNotNull($sheet);
        $this->assertSame($admin->id, (int) $sheet->created_by);
        $this->assertSame(3, (int) $sheet->count_i);
        $this->assertSame(1, (int) $sheet->count_b);
        $this->assertSame(0, (int) $sheet->count_lab);
        $this->assertSame(2, (int) $sheet->count_loc);
        $this->assertSame('Daily closing note', $sheet->notes);
        $this->assertSame(2, DailyEntry::query()->count());
    }

    public function test_finance_index_prefills_existing_sheet_for_selected_day(): void
    {
        $admin = $this->makeAdmin();

        $sheet = DailySheet::query()->create([
            'sheet_date' => '2026-03-24',
            'count_i' => 1,
            'count_b' => 2,
            'count_lab' => 3,
            'count_loc' => 4,
            'notes' => 'Existing day note',
            'created_by' => $admin->id,
        ]);

        DailyEntry::query()->create([
            'sheet_id' => $sheet->id,
            'khat' => 'Existing Income',
            'type' => 'in',
            'amount' => 200,
            'remark' => 'Saved earlier',
        ]);

        $response = $this->withoutMiddleware([
            LogAdminActivity::class,
        ])->actingAs($admin, 'admin')->get(route('admin.finance.index', [
            'from' => '2026-03-24',
            'to' => '2026-03-24',
        ]));

        $response->assertOk();
        $response->assertSee('এই তারিখে আগের এন্ট্রি আছে');
        $response->assertSee('Existing Income');
        $response->assertSee('Existing day note');
    }

    public function test_finance_export_streams_csv_without_date_cast_errors(): void
    {
        $admin = $this->makeAdmin();

        $sheet = DailySheet::query()->create([
            'sheet_date' => '2026-03-24',
            'created_by' => $admin->id,
        ]);

        DailyEntry::query()->create([
            'sheet_id' => $sheet->id,
            'khat' => 'Recharge Commission',
            'type' => 'in',
            'amount' => 99.5,
            'remark' => 'CSV row',
        ]);

        $response = $this->withoutMiddleware([
            LogAdminActivity::class,
        ])->actingAs($admin, 'admin')->get(route('admin.finance.export', [
            'from' => '2026-03-24',
            'to' => '2026-03-24',
        ]));

        $response->assertOk();
        $response->assertHeader('content-type', 'text/csv; charset=UTF-8');

        $csv = $response->streamedContent();

        $this->assertStringContainsString('2026-03-24', $csv);
        $this->assertStringContainsString('Recharge Commission', $csv);
        $this->assertStringContainsString('CSV row', $csv);
    }

    private function makeAdmin(): Admin
    {
        return Admin::query()->create([
            'name' => 'Finance Admin',
            'email' => 'finance-admin@example.com',
            'password' => Hash::make('secret-123'),
            'is_super_admin' => true,
            'project_permissions' => [],
        ]);
    }

    private function createTables(): void
    {
        Schema::dropIfExists('daily_entries');
        Schema::dropIfExists('daily_sheets');
        Schema::dropIfExists('admins');

        Schema::create('admins', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->boolean('is_super_admin')->default(false);
            $table->json('project_permissions')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });

        Schema::create('daily_sheets', function (Blueprint $table) {
            $table->id();
            $table->date('sheet_date')->unique();
            $table->unsignedInteger('count_i')->default(0);
            $table->unsignedInteger('count_b')->default(0);
            $table->unsignedInteger('count_lab')->default(0);
            $table->unsignedInteger('count_loc')->default(0);
            $table->text('notes')->nullable();
            $table->unsignedBigInteger('created_by')->nullable();
            $table->timestamps();
        });

        Schema::create('daily_entries', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('sheet_id');
            $table->string('khat');
            $table->string('type', 10);
            $table->decimal('amount', 14, 2);
            $table->string('remark')->nullable();
            $table->timestamps();
        });
    }
}
