<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use App\Models\Task;
use App\Models\TaskRequest;
use App\Models\Deposit;
use App\Models\Mining; // Added Mining model reference
use App\Models\UserLedger;
use Carbon\Carbon;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $fillable = [
        'name', 'email', 'password', 'ref_id', 'ref_by',
        'username', 'code', 'bonus_code', 'balance',
        'receive_able_amount', 'phone', 'vip_level',
        'package_id', 'gateway_method', 'trx_wallet',
        'gateway_number', 'gateway_name', 'usdt_name',
        'usdt_number', 'usdt_password', 'bdt_password', 'status',
    ];

    protected $hidden = ['password', 'remember_token'];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'balance' => 'double',
        'receive_able_amount' => 'double',
    ];

    // --- Relationship: Purchases/Mining ---
    public function purchases() {
        return $this->hasMany(Mining::class, 'user_id'); 
    }

    // --- Referral Relationships ---
    public function referrals() {
        return $this->hasMany(User::class, 'ref_by', 'ref_id');
    }

    public function secondLevel() {
        $firstLevelIds = $this->referrals()->pluck('ref_id')->toArray();
        return User::whereIn('ref_by', $firstLevelIds);
    }

    public function thirdLevel() {
        $secondLevelIds = $this->secondLevel()->pluck('ref_id')->toArray();
        return User::whereIn('ref_by', $secondLevelIds);
    }

    public function getTeamSizeAttribute() {
        return $this->referrals()->count() + $this->secondLevel()->count() + $this->thirdLevel()->count();
    }

    public function deposits() {
        return $this->hasMany(Deposit::class);
    }

    /**
     * Weekly Member Balance Logic (Total Referrals - Claimed Task Requirements)
     * This matches your logic: 11 joins - 10 claimed = 1 remaining.
     */
    public function weeklyQualifiedCount() {
        $startOfWeek = Carbon::now()->startOfWeek();
        $endOfWeek = Carbon::now()->endOfWeek();

        // 1. Total stock of approved referrals this week
        $totalReferrals = User::where('ref_by', $this->ref_id)
            ->whereBetween('created_at', [$startOfWeek, $endOfWeek])
            ->whereHas('deposits', function($query) {
                $query->where('status', 'approved');
            })
            ->count();

        // 2. Points mapping for claimed tasks
        $tasksData = [
            1 => 3, 2 => 6, 3 => 10, 4 => 15, 5 => 30, 6 => 45
        ];

        // 3. Subtract points of tasks already claimed
        $claimedTaskIds = TaskRequest::where('user_id', $this->id)
            ->whereBetween('created_at', [$startOfWeek, $endOfWeek])
            ->pluck('task_id')
            ->toArray();

        $membersUsed = 0;
        foreach ($claimedTaskIds as $tid) {
            if (isset($tasksData[$tid])) {
                $membersUsed += $tasksData[$tid];
            }
        }

        // 4. Final remaining member balance
        $remaining = $totalReferrals - $membersUsed;

        return ($remaining < 0) ? 0 : $remaining;
    }
}
