<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class GrowthDailyJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function handle(): void
    {
        // Enforce Trial with Penalty and Challenge reward; update wallet_ledger/trials
        $now = now();
        $trials = \DB::table('trials')->where('status', 'active')->where('ends_at','<=',$now)->get();
        foreach ($trials as $t) {
            // Simple rule: if penalty_points > 0 → failed; else succeeded
            $status = ($t->penalty_points ?? 0) > 0 ? 'failed' : 'succeeded';
            \DB::table('trials')->where('id', $t->id)->update(['status' => $status, 'updated_at' => $now]);
            if ($status === 'failed') {
                \DB::table('wallet_ledger')->insert([
                    'user_id' => $t->user_id,
                    'type' => 'debit',
                    'amount_irr' => -config('growth.trial_penalty', 0),
                    'reason' => 'trial_penalty',
                    'meta_json' => json_encode(['trial_id' => $t->id]),
                    'created_at' => $now, 'updated_at' => $now,
                ]);
            } else {
                \DB::table('wallet_ledger')->insert([
                    'user_id' => $t->user_id,
                    'type' => 'credit',
                    'amount_irr' => config('growth.challenge_reward', 0),
                    'reason' => 'challenge_reward',
                    'meta_json' => json_encode(['trial_id' => $t->id]),
                    'created_at' => $now, 'updated_at' => $now,
                ]);
            }
        }
    }
}
