<?php

namespace App\Http\Controllers\user;

use App\Http\Controllers\Controller;
use App\Models\InvitationTask;
use App\Models\Purchase;
use App\Models\User;
use App\Models\UserLedger;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class InvitationTaskController extends Controller
{
    public function index()
    {
        $user = Auth::user();

        $referrals = User::where('ref_by', $user->ref_id)
            ->pluck('id');

        $totalPurchase = Purchase::whereIn('user_id', $referrals)
            ->sum('amount');

        $tasks = InvitationTask::where('status', 'active')
            ->orderBy('sort_order')
            ->get();

        $claimedTasks = DB::table('invitation_task_claims')
            ->where('user_id', $user->id)
            ->pluck('task_id')
            ->toArray();

        return view('app.main.invitation_task', compact(
            'tasks',
            'totalPurchase',
            'claimedTasks'
        ));
    }

    public function claim(Request $request)
    {
        $user = Auth::user();

        $task = InvitationTask::find($request->task_id);

        if (!$task) {
            return back()->with('error', 'Task not found');
        }

        $alreadyClaimed = DB::table('invitation_task_claims')
            ->where('user_id', $user->id)
            ->where('task_id', $task->id)
            ->exists();

        if ($alreadyClaimed) {
            return back()->with('error', 'Reward already claimed');
        }

        $referrals = User::where('ref_by', $user->ref_id)
            ->pluck('id');

        $totalPurchase = Purchase::whereIn('user_id', $referrals)
            ->sum('amount');

        if ($totalPurchase < $task->target_amount) {
            return back()->with('error', 'Target not reached');
        }

        $user->increment('balance', $task->reward_amount);

        UserLedger::create([
    'user_id' => $user->id,
    'reason' => 'Invitation Task Reward',
    'perticulation' => 'Invitation Task Reward',
    'amount' => $task->reward_amount,
    'credit' => $task->reward_amount,
    'debit' => 0,
    'status' => 'approved',
    'date' => date('Y-m-d H:i:s'),
]);

        DB::table('invitation_task_claims')->insert([
            'user_id' => $user->id,
            'task_id' => $task->id,
            'claimed_at' => now(),
            'created_at' => now(),
            'updated_at' => now()
        ]);

        return back()->with(
            'success',
            'Reward claimed successfully'
        );
    }
}