<?php

namespace Tests\Feature;

use App\Models\ClientSubscription;
use App\Models\Payment;
use App\Models\Plan;
use App\Models\Task;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class PlanFlowTest extends TestCase
{
    use RefreshDatabase;

    public function test_client_selecting_paid_plan_creates_pending_payment_intent(): void
    {
        $client = User::create(['name' => 'Plan Buyer', 'email' => 'plan-buyer@mgg.test', 'password' => 'password', 'role' => 'client']);
        $plan = Plan::create(['name' => 'Growth', 'price' => 30000, 'billing_cycle' => 'monthly', 'duration_days' => 30, 'work_limit' => 20, 'status' => 'active']);

        $this->actingAs($client)->post('/client/my-plan/select', ['plan_id' => $plan->id])
            ->assertRedirect('/client/payments');

        $this->assertDatabaseHas('payments', [
            'user_id' => $client->id,
            'plan_id' => $plan->id,
            'amount' => 30000,
            'method' => 'pending_proof',
            'status' => 'pending',
        ]);
    }

    public function test_admin_approving_plan_payment_activates_subscription_and_deactivates_old_plan(): void
    {
        $admin = User::create(['name' => 'Plan Admin', 'email' => 'plan-admin@mgg.test', 'password' => 'password', 'role' => 'admin']);
        $client = User::create(['name' => 'Plan Client', 'email' => 'plan-client-flow@mgg.test', 'password' => 'password', 'role' => 'client']);
        $oldPlan = Plan::create(['name' => 'Starter', 'price' => 15000, 'billing_cycle' => 'monthly', 'duration_days' => 30, 'work_limit' => 10, 'status' => 'active']);
        $newPlan = Plan::create(['name' => 'Premium', 'price' => 45000, 'billing_cycle' => 'monthly', 'duration_days' => 30, 'work_limit' => 35, 'status' => 'active']);
        ClientSubscription::create(['user_id' => $client->id, 'plan_id' => $oldPlan->id, 'starts_at' => now()->subMonth(), 'ends_at' => now()->addDay(), 'status' => 'active', 'usage_count' => 4]);
        $payment = Payment::create(['user_id' => $client->id, 'plan_id' => $newPlan->id, 'amount' => 45000, 'method' => 'Bank Transfer', 'status' => 'pending']);

        $this->actingAs($admin)->put('/admin/payments/'.$payment->id, [
            'user_id' => $client->id,
            'plan_id' => $newPlan->id,
            'amount' => 45000,
            'method' => 'Bank Transfer',
            'transaction_reference' => 'PLAN-001',
            'paid_at' => now()->toDateString(),
            'status' => 'approved',
            'admin_note' => 'Approved',
        ])->assertRedirect('/admin/payments');

        $this->assertDatabaseHas('client_subscriptions', ['user_id' => $client->id, 'plan_id' => $oldPlan->id, 'status' => 'inactive']);
        $this->assertDatabaseHas('client_subscriptions', ['user_id' => $client->id, 'plan_id' => $newPlan->id, 'status' => 'active', 'usage_count' => 0]);
        $this->assertNotNull($payment->refresh()->subscription_activated_at);
    }

    public function test_completed_task_increments_active_subscription_usage_once(): void
    {
        $admin = User::create(['name' => 'Usage Admin', 'email' => 'usage-admin@mgg.test', 'password' => 'password', 'role' => 'admin']);
        $client = User::create(['name' => 'Usage Client', 'email' => 'usage-client@mgg.test', 'password' => 'password', 'role' => 'client']);
        $plan = Plan::create(['name' => 'Usage Plan', 'price' => 10000, 'billing_cycle' => 'monthly', 'duration_days' => 30, 'work_limit' => 10, 'status' => 'active']);
        $subscription = ClientSubscription::create(['user_id' => $client->id, 'plan_id' => $plan->id, 'starts_at' => today(), 'ends_at' => today()->addMonth(), 'status' => 'active', 'usage_count' => 0]);
        $task = Task::create(['client_id' => $client->id, 'title' => 'Usage task', 'priority' => 'normal', 'status' => 'assigned']);

        $payload = ['title' => 'Usage task', 'client_id' => $client->id, 'designer_id' => null, 'client_request_id' => null, 'details' => null, 'notes' => null, 'priority' => 'normal', 'deadline' => null, 'status' => 'completed'];
        $this->actingAs($admin)->put('/admin/tasks/'.$task->id, $payload)->assertRedirect('/admin/tasks');
        $this->assertSame(1, $subscription->refresh()->usage_count);

        $this->actingAs($admin)->put('/admin/tasks/'.$task->id, $payload)->assertRedirect('/admin/tasks');
        $this->assertSame(1, $subscription->refresh()->usage_count);
    }

    public function test_client_request_is_blocked_when_plan_limit_is_complete(): void
    {
        $client = User::create(['name' => 'Limited Client', 'email' => 'limited-client@mgg.test', 'password' => 'password', 'role' => 'client']);
        $plan = Plan::create(['name' => 'Limited Plan', 'price' => 10000, 'billing_cycle' => 'monthly', 'duration_days' => 30, 'work_limit' => 1, 'status' => 'active']);
        ClientSubscription::create(['user_id' => $client->id, 'plan_id' => $plan->id, 'starts_at' => today(), 'ends_at' => today()->addMonth(), 'status' => 'active', 'usage_count' => 1]);

        $this->actingAs($client)->post('/client/requests', [
            'request_type' => 'design',
            'title' => 'Extra request',
            'details' => 'Should be blocked',
        ])->assertRedirect('/client/my-plan')->assertSessionHasErrors('plan');
    }
}
