<?php

namespace Tests\Feature;

use App\Models\SalaryRule;
use App\Models\Task;
use App\Models\TaskSubmission;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class TaskSalaryFlowTest extends TestCase
{
    use RefreshDatabase;

    public function test_task_review_updates_points_and_salary_report(): void
    {
        $admin = User::factory()->create(['role' => 'admin']);
        $staff = User::factory()->create(['role' => 'staff']);

        SalaryRule::create([
            'point_value' => 1000,
            'monthly_target_point' => 15,
            'is_active' => true,
            'effective_from' => now()->toDateString(),
        ]);

        $this->actingAs($admin)
            ->post('/admin/tasks', [
                'assigned_to' => $staff->id,
                'title' => 'Landing Page',
                'description' => 'Build company landing page',
                'deadline' => '2026-03-30',
                'priority' => 'high',
                'point_value' => 5,
                'expected_output' => 'Working page',
            ])
            ->assertSessionHasNoErrors();

        $task = Task::firstOrFail();

        $this->actingAs($staff)
            ->post("/tasks/{$task->id}/progress", [
                'progress_percentage' => 100,
                'note' => 'Done',
            ])
            ->assertSessionHasNoErrors();

        $this->actingAs($staff)
            ->post("/tasks/{$task->id}/submit", [
                'summary' => 'Completed',
                'live_link' => 'https://example.com',
            ])
            ->assertSessionHasNoErrors();

        $submission = TaskSubmission::firstOrFail();
        Carbon::setTestNow(Carbon::parse('2026-03-26 11:00:00', 'Asia/Dhaka'));

        $this->actingAs($admin)
            ->post("/admin/submissions/{$submission->id}/review", [
                'status' => 'approved',
                'review_note' => 'Good work',
            ])
            ->assertSessionHasNoErrors();

        $this->assertDatabaseHas('points', [
            'user_id' => $staff->id,
            'task_id' => $task->id,
            'points' => 5,
        ]);

        $this->actingAs($staff)
            ->get('/salary-report')
            ->assertOk()
            ->assertSee('5.00')
            ->assertSee('5,000.00');
    }
}
