<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use App\Models\Traits\AuthenticatableTrait;

class User extends BaseModel implements AuthenticatableContract
{
    use HasFactory, Notifiable, HasApiTokens, AuthenticatableTrait;

    // protected $table = 'emp_company_details';

    protected $fillable = [
        'name',
        'email',
        'mobile_number',
        'email_verified_at',
        'password',
        'remember_token',
        'user_type',
        'active_status',
        'is_enable_login',
        'total_workspace',
        'total_active_workspace',
        'total_user',
        'current_workspace_id',
        'current_company',
        'current_company_workspace',
        'avatar',
        'active_plan_id',
        'plan_expire_date',
        'created_by',
        'del',
        'permissions_setup',
        'cus_id',
        'referral_code',
        'referred_by',
        'referral_code_used',
        'referral_clicks',
        'status',
        'company_name',
        'abn',
        'company_logo',
        'trade_id',
        'company_number',
        'customer_id',
        'workspace_id',
    ];

    protected $hidden = [
        'password',
    ];

    protected $casts = [
        'plan_expire_date' => 'datetime',
        'email_verified_at' => 'datetime',
    ];

    // protected $with =['plan'];

    public function plan()
    {
        return $this->belongsTo(Plan::class, 'active_plan_id', 'id');
    }

    public function customDomainRequests()
    {
        return $this->hasMany(CustomDomainRequest::class, 'created_by');
    }

    // Referral relationships
    public function referrer()
    {
        return $this->belongsTo(User::class, 'referred_by');
    }

    public function referrals()
    {
        return $this->hasMany(User::class, 'referred_by');
    }

    public function referralLeads()
    {
        return $this->hasMany(ReferralLead::class, 'referral_user_id');
    }

    public function referralCommissions()
    {
        return $this->hasMany(ReferralCommission::class, 'referral_user_id');
    }

    public function referralPayouts()
    {
        return $this->hasMany(ReferralPayout::class, 'referral_user_id');
    }

    // Helper methods for referrals
    public function generateReferralCode()
    {
        do {
            $code = 'REF' . strtoupper(substr(md5(uniqid()), 0, 8));
        } while (static::where('referral_code', $code)->exists());
        
        return $code;
    }

    public function isReferralUser()
    {
        return in_array($this->user_type, [2, 4]); // Customer (2) and Referral partner (4) user types
    }

    public function getAvailableCommissions()
    {
        return $this->referralCommissions()
            ->where('status', 'approved')
            ->whereDoesntHave('commissionPayouts', function($query) {
                $query->whereIn('status', ['requested', 'completed']);
            })
            ->with(['customer:id,name,email'])
            ->orderBy('created_at', 'desc')
            ->get();
    }

    /**
     * Get the contact persons for the subcontractor.
     */
    public function contactPersons()
    {
        return $this->hasMany(SubcontractorContactPerson::class, 'subcontractor_id');
    }

    /**
     * Get the subcontractor company associations (multiple customers).
     */
    public function subcontractorCompanies()
    {
        return $this->hasMany(SubcontractorCompany::class, 'user_id');
    }
}
