<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use DateTime;
class Member extends Model
{
    use HasFactory;

    protected $fillable = [
        'first_name',
        'last_name',
        'status',
        'birth_city_id',
        'birth_province_id',
        'birth_nation_id',
        'birth_date',
        'gender',
        'address',
        'zip_code',
        'fiscal_code',
        'nation_id',
        'province_id',
        'city_id',
        'phone',
        'phone2',
        'phone3',
        'email',
        'image',
        'document_type',
        'document_number',
        'document_from',
        'document_expire_date',
        'document_files',
        'father_name',
        'father_email',
        'father_phone',
        'father_fiscal_code',
        'father_document_files',
        'mother_document_files',
        'mother_email',
        'mother_phone',
        'mother_fiscal_code',
        'father_doc_number',
        'father_doc_type',
        'mother_doc_number',
        'mother_doc_type',
        'enabled',
        'no_send_mail',
        'exclude_from_records',
        'current_status',
        'certificate',
        'certificate_date',
        'to_complete',
        'is_archived',
        'archived_date',
        'is_deleted',
        'deleted_date',
    ];
    public function nation()
    {
        return $this->belongsTo(Nation::class);
    }

    public function province()
    {
        return $this->belongsTo(Province::class);
    }

    public function city()
    {
        return $this->belongsTo(City::class);
    }

    public function birth_nation()
    {
        return $this->belongsTo(Nation::class);
    }

    public function birth_province()
    {
        return $this->belongsTo(Province::class);
    }

    public function birth_city()
    {
        return $this->belongsTo(City::class);
    }

    public function cards()
    {
        return $this->hasMany(MemberCard::class);
    }

    public function categories()
    {
        return $this->hasMany(MemberCategory::class);
    }

    public function courses()
    {
        return $this->hasMany(MemberCourse::class);
    }

    public function certificates()
    {
        return $this->hasMany(MemberCertificate::class)->orderBy('expire_date', 'DESC');
    }

    public function isAdult()
    {
        $date1 = new DateTime($this->birth_date);
        $date2 = new DateTime("now");
        $interval = $date1->diff($date2);
        return $this->birth_date == '' || $interval->y >= 18;
    }

    public function getAge()
    {
        $date1 = new DateTime($this->birth_date);
        $date2 = new DateTime("now");
        $interval = $date1->diff($date2);
        return strval($interval->y);
        return $interval->y;
    }

    public function isActive()
    {
        // Se uno ha una tessera o meno compare nella lista degli utenti (attivo/disattivo),
        // per il certificato medico compare la data di scadenza sempre nella lista utenti.
        // Se uno invece ha eseguito i pagamenti, al posto del bottone abbiamo detto che mettiamo la scritta (iscritto (ha pagato),
        //in sospeso (stato legato alla validità o meno della tessera o del certificato medico, non iscritto (non ha pagato). Io questo ho capito.

        $subscribed = $this->isSubscribed();
        $hasCard = $subscribed["status"] == 2;
        $hasCertificate = $this->hasCertificate()["status"];

        $ret = array('status' => 0, 'status_text' => '', 'date' => '');
        if ($hasCard)
        {
            if ($hasCertificate)
                $ret = array('status' => 2, 'status_text' => 'Attiva', 'date' => $subscribed["date"]);
            else
                $ret = array('status' => 1,'status_text' => 'Sospeso', 'date' => $subscribed["date"]);
        }

        /*$ret = array('status' => 0, 'status_text' => '', 'date' => '');
        $records = \App\Models\Record::where('member_id', $this->id)->where('type', 'IN')->with('causal')->get();
        foreach($records as $record)
        {
            if ($record->causal->user_status == 1)
            {
                if ($record->date < date('Y-m-d', strtotime('+1 year')))
                    $ret = array('status' => 2, 'status_text' => 'Attiva', 'date' => $newDate = date('Y-m-d', strtotime($record->date. ' + 1 years')));
                // if (!$hasCard || !$hasCertificate)
                if (!$hasCertificate)
                    $ret = array('status' => 1,'status_text' => 'Sospeso', 'date' => $newDate = date('Y-m-d', strtotime($record->date. ' + 1 years')));
            }
        }*/
        return $ret;
    }

    public function isSubscribed()
    {
        $ret = array('status' => 0, 'date' => '');
        $cards = \App\Models\MemberCard::where('member_id', $this->id)->with('card')->orderBy('expire_date')->get();
        foreach($cards as $card)
        {
            if ($card->card->use_for_user_check)
            {
                $ret = array('status' => $card->expire_date . " 23:59:59" > date("Y-m-d") ? 2 : 1, 'date' => $card->expire_date);
            }
        }
        return $ret;
    }

    public function getStatus()
    {
        $ret = array('status' => 0, 'date' => '', 'status_text' => 'Non tesserato');
        $cards = \App\Models\MemberCard::where('member_id', $this->id)->with('card')->orderBy('expire_date')->get();
        foreach($cards as $card)
        {
            if ($card->card->use_for_user_check)
            {
                $s = 0;
                if ($card->expire_date . " 23:59:59" > date("Y-m-d"))
                {
                    $c = $this->hasCertificate();
                    $s = $c["status"] == true ? 2 : 1;
                }
                $ret = array('status' => $s, 'date' => $card->expire_date, 'status_text' => $s == 2 ? 'Tesserato' : ($s == 1 ? 'Sospeso' : 'Non tesserato'));
                //$ret = array('status' => $card->expire_date . " 23:59:59" > date("Y-m-d") ? 2 : 1, 'date' => $card->expire_date, 'status_text' => $card->expire_date . " 23:59:59" > date("Y-m-d") ? 'Tesserato' : 'Sospeso');
            }
        }
        return $ret;
    }

    public function hasCertificate()
    {
        $ret = array('status' => false, 'date' => '');
        $certificates = \App\Models\MemberCertificate::where('member_id', $this->id)->orderBy('expire_date', 'DESC')->get();
        foreach($certificates as $idx => $certificate)
        {
            if ($idx == 0)
                $ret = array('status' => $certificate->expire_date . " 23:59:59" > date("Y-m-d"), 'date' => $certificate->expire_date);
        }
        return $ret;
    }

    public function getMoney()
    {
        $ret = 0;
        // Soldi virtuali caricati
        $records = \App\Models\Record::where('member_id', $this->id)->where('type', 'IN')
        ->where(function ($query)  {
            $query->where('deleted', false)->orWhere('deleted', null);
        })->get();
        //->with('causal')->get();
        foreach($records as $record)
        {
            foreach($record->rows as $r)
            {
                if ($r->causal->money == 1)
                {
                    $ret += $r->amount;
                }
            }
        }
        // Soldi virtuali spesi
        $records = \App\Models\Record::where('member_id', $this->id)->where('type', 'IN')->with('payment_method')
        ->where(function ($query)  {
            $query->where('deleted', false)->orWhere('deleted', null);
        })->get();
        foreach($records as $record)
        {
            if ($record->payment_method->money == 1)
            {
                $ret -= $record->amount;
            }
        }
        // Soldi EXTRA
        $records = \App\Models\Money::where('member_id', $this->id)->get();
        foreach($records as $record)
        {
            $ret += floatval($record->amount);
        }

        return $ret;
    }

}
