<?php

namespace App\Models;

use App\Http\Controllers\CompensationPlanCalculatorController;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Exception;
use App\Http\Traits\Timezone;
use Symfony\Component\HttpFoundation\Response;

class BV extends Model
{
    const SOURCE_PURCHASE = 1;
    const SOURCE_BERGMAN = 2;
    const SOURCE_CCW = 3;
    const SOURCE_ADMIN = 4;
    const SOURCE_COUPON_REDEEM = 5;

    const ORIGIN_PLACEMENT_SPONSOR = 1;
    const ORIGIN_PERSONAL_SPONSOR = 2;
    use HasFactory, Timezone;

    protected $casts = [
        'created_at' => 'datetime:d-m-Y H:i:s'
    ];
    //
    public $timestamps = false;

    protected $table = 'bv';
    protected $fillable = [
        'user_id',
        'value',
        'data',
        'source',
        'origin',
        'created_at',
        'updated_at',
    ];
    protected $appends = ['calculationDay'];

    public static function boot()
    {
        parent::boot();
        self::created(function ($model) {
            BV::processBv($model, $model->user, $model->value);
        });
    }

    public static function qbvSources()
    {
        return [
            self::SOURCE_PURCHASE,
            self::SOURCE_CCW,
            self::SOURCE_ADMIN,
            self::SOURCE_COUPON_REDEEM,
        ];
    }
    public  static function processBv($bv, $user, $value)
    {
        try {
            //code...
            $user->update([
                'abv' => DB::raw("abv + $value"),
                'qbv' => DB::raw("qbv + $value"),
                'tsv' => DB::raw("tsv + $value"),
                'wtsv' => DB::raw("wtsv + $value"),

            ]);

            if ($user->personal_sponsor_id) {
                $pgvValue = $value * 0.25;

                $member = Member::where('user_id',$user->personal_sponsor_id)->first();
                if($member){
                    $member->update([
                        'pgv' => DB::raw("pgv + $pgvValue"),
                        'qbv' => DB::raw("qbv + $pgvValue"),
                    ]);
                }
                $bv->refresh();

                $sponsor = $user->personalSponsor;
                for ($level = 2; $level <= 5; ++$level) {
                    $sponsor = $sponsor->personalSponsor;
                    if (!$sponsor) {
                        break;
                    }
                    $sponsor->update([
                        'qbv' => DB::raw("qbv + $pgvValue")
                    ]);
                }
            }

            $users = Member::whereIn('id', $bv->origin == BV::ORIGIN_PERSONAL_SPONSOR ? $user->allPersonalSponsorUplineIds() : $user->getAllSponsorIds($user->sponsor_id));
            if($users){

                $users->update([
                    'wtsv' => DB::raw("wtsv + $value"),
                    'tsv' => DB::raw("tsv + $value"),
                ]);
            }
        } catch (Exception $e) {
            reportLog($e);
            DB::rollBack();
            return response()->json(['status' => false, 'msg' => __('Internal Server Error'), 'data' => null], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    public static function commissionSources()
    {
        return [
            self::SOURCE_PURCHASE,
            self::SOURCE_CCW,
            self::SOURCE_ADMIN,
            self::SOURCE_COUPON_REDEEM,
        ];
    }

    public function user()
    {
        return $this->belongsTo(Member::class, 'user_id', 'id');
    }

    protected function CalculationDay(): Attribute
    {
        return Attribute::make(
            function () {
                if (isset($this->attributes['created_at'])) {
                    return CompensationPlanCalculatorController::getCalculationDayForDate($this->attributes['created_at']);
                }
                return "";
            }
        );
    }
}
