<? php
namespace App\Models;

use CodeIgniter\Model;

class class userCardBehaviours extends Model{

    /*Default no bahaviour attached*/
    public function behaviour_BH0001($in, $out)
    {
        $ret = CARD_ADD_ALLOWED;
        return $ret;
    }
    
    /*Users selects 'maybe later' to cc permision or user hits 'disconnect' */
    public function behaviour_BH0002($in, $out)
    {
        global $pgconn;
    
        $ret = CARD_ADD_DENIED;
        $member_id = $in['id'];
        //$out = $in; //  loadMemberDescisionData(member_id, $out);
        $query = "SELECT count(*) AS members_bank_count FROM members_bank_accounts WHERE member_id =  " . $member_id . "";
        $r = pg_query($pgconn, $query);
        if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
            if ($in["last_acct"] == "" & $f["members_bank_count"] == 0) {
                // no account data
                $ret = CARD_ADD_ALLOWED;
            }
        }
    
        return $ret;
    }

/*Users selects 'maybe later' to gmail permision*/
public function behavior_BH0003($in, $out)
{
    $ret = CARD_ADD_DENIED;
    $member_id = $in['id'];

    $query = "SELECT count(id) as email_pull_atempt FROM oauth2_pull_jobs WHERE member_id  =  " . $member_id . "";
    $r = pg_query($pgconn, $query);
    if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
        if ($in["last_email"] == "" & $f["email_pull_atempt"] == 0) {
            // no account data
            $ret = CARD_ADD_ALLOWED;
        }
    }
    return $ret;
}

/*No Credit Card & Email','Users selects ''maybe later'' to gmail & cc permision*/
public function behavior_BH0004($in, $out)
{
    $ret = CARD_ADD_DENIED;
    $member_id = $in['id'];

    $query = "SELECT count(id) as email_pull_atempt FROM oauth2_pull_jobs WHERE member_id  =  " . $member_id . "";
    $r = pg_query($pgconn, $query);
    if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
        if ($in["last_email"] == "" & $f["email_pull_atempt"] == 0) {
            // no account data
            $ret = CARD_ADD_ALLOWED;
        }
    }
    return $ret;
}
//

/*CC & email synced BUT no Transactions or Transactions cease for 7 days*/
public function behavior_BH0005($member, $out)
{
    $ret = CARD_ADD_DENIED;
$this->weeklyMemberSpending($member, $out);
    if ($out["weekly_total"] == 0) {
        $ret = CARD_ADD_ALLOWED;
    }
    return $ret;
}

/*User didn't set budget on sign-up*/
public function behavior_BH0006($member, $out)
{
    $ret = CARD_ADD_DENIED;
    $out = $member;
    if ($out["max_budget"] == 0) {
        $ret = CARD_ADD_ALLOWED;
    }
    return $ret;
}

/*Timezone hits a certain time, card displays for 1 hour.*/
public function behavior_BH0007($in, $out)
{
    $ret = CARD_ADD_DENIED;
    return $ret;
}

/*Users spending exceeds budget, card displayed on Tuesdays & Fridays*/
public function behavior_BH0008($member, $out)
{
    $ret = CARD_ADD_DENIED;
$this->weeklyMemberSpending($member, $out);
    if ($out["over_spending"] > 0 && $out["under_spending"] == 0) {
        $ret = CARD_ADD_ALLOWED;
    }
    return $ret;
}

/*Users spending falls below budget, card displayed on Tuesdays & Fridays*/
public function behavior_BH0009($in, $out)
{
    $ret = CARD_ADD_DENIED;
$this->weeklyMemberSpending($member, $out);
    if ($out["under_spending"] > 0 && $out["over_spending"] == 0 && $out["user_budget_percentbelow"] > 0) {
        $ret = CARD_ADD_ALLOWED;
    }
    return $ret;
}

/*Use selects 'allow' to GPS permission*/
public function behavior_BH0010($in, $out)
{
    $ret = CARD_ADD_DENIED;
    $member_id = $in['id'];
    if (enableGPS($member_id)) {
        $ret = CARD_ADD_ALLOWED;
    }
    return $ret;
}

/*CC Synced, Email Synced, Transations coming through, GPS Sycned*/
public function behavior_BH0011($in, $out)
{
    $ret = CARD_ADD_DENIED;
    $member_id = $in['id'];

    $out = $in; // loadMemberDescisionData(member_id, $out);
    $member_id = $in['id'];
    if (enableGPS($member_id) == false && $out["last_acct"] != "" && $out["last_email"] != "") {
        $ret = CARD_ADD_ALLOWED;
    }
    return $ret;
}

/*Users selects 'no' to GPS permission*/
public function behavior_BH0013($in, $out)
{
    // for version 01, the only way is if I see no GPS entery
    $ret = CARD_ADD_DENIED;
    $member_id = $in['id'];
    if (enableGPS($member_id) == false) {
        $ret = CARD_ADD_ALLOWED;
    }
    return $ret;
}

/*Back office identifies a 'Uber' receipt*/
public function behavior_BH0012($in, $out)
{
    $ret = CARD_ADD_DENIED;
    $member_id = $in['id'];
    return $ret;
}

/*User Spending Above Average*/
public function behavior_BH0014($member, $out)
{
    $ret = CARD_ADD_DENIED;
$this->weeklyMemberSpending($member, $out);
    if ($out["user_budget_percentabove"] > 0) {
        $ret = CARD_ADD_ALLOWED;
    }
    return $ret;
}

/*User Spending Below Average*/
public function behavior_BH0015($member, $out)
{
    $ret = CARD_ADD_DENIED;
$this->weeklyMemberSpending($member, $out);
    if ($out["user_budget_percentbelow"] > 0) {
        $ret = CARD_ADD_ALLOWED;
    }
    return $ret;
}

/*Show if The User Country is Known*/
public function behavior_BH0016($in, $out)
{
    $ret = CARD_ADD_DENIED;
    /* $member_id = $in['id'];
    detectMemberLocation($member_id, $out); */
    return $ret;
}

/*Show if The User Country Not Known*/
public function behavior_BH0017($in, $out)
{
    $ret = CARD_ADD_DENIED;
    /* $member_id = $in['id'];
    detectMemberLocation($member_id, $out); */
    return $ret;
}

/*No Budgt Set*/
public function behavior_BH0018($in, $out)
{
    $ret = CARD_ADD_DENIED;
    /*  $member_id = $in['id'];
    detectMemberLocation($member_id, $out); */
    if ($in["min_budget"] + $in["max_budget"] == 0) {
        $ret = CARD_ADD_ALLOWED;
    }
    return $ret;
}

public function enableGPS($member_id)
{
    global $pgconn_gps;
    $r = pg_query($pgconn_gps, "SELECT count(*) as num FROM members_tracking WHERE member_id=" . $member_id . "");
    if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
        if ($f['num'] > 0) {
            return true;
        }
    }
    return false;
}
public function weeklyMemberSpending($member, &$out)
{
    {
        global $pgconn;
        $member_id = $member['id'];
        $out["over_spending"] = "0";
        $out["under_spending"] = "0";
        $out["weekly_total"] = "0";

        $total_bank = 0;
        $total_email = 0;
        $total_weekly_spend = 0;

        // loadMemberDescisionData( member_id, out);
        $out["user_budget_percentbelow"] = "0";
        $out["user_budget_percentabove"] = "0";

        // LOCAL AVERAGE -----------------------------------------------
        $out["user_less_localavergperm"] = "0";
        $out["user_more_localavergperm"] = "0"; // we start with zero
        $out["population_average"] = 0; // we start with zero
        $out["member_average"] = 0; // we start with zero

        $population = fetchRow("SELECT avg(amount) *0.01 AS population_average FROM members_bankimport WHERE category IN (SELECT category FROM activity_listcategory) AND currency='USD'");
        if ($population) {
            $out['population_average'] = $population['population_average'];
        }
        $member_average = fetchRow("SELECT avg(amount) *0.01 AS member_average FROM members_bankimport WHERE category IN (SELECT category FROM activity_listcategory) AND member_id = " . $member_id . " AND currency='USD'");
        if ($member_average) {
            $out['member_average'] = $member_average['member_average'];
        }
        if ($out['member_average'] > 0 && $out['member_average'] > $out['population_average']) {
            $out["user_more_localavergperm"] = $out['member_average'] - $out['population_average'];
        }
        if ($out['member_average'] > 0 && $out['member_average'] < $out['population_average']) {
            $out["user_less_localavergperm"] = $out['population_average'] - $out['member_average'];
        }
        // END LOCAL AVERAGE -------------------------------------

        $total_weekly_budget = ($member["min_budget"] + $member["max_budget"]) / 200;

        // bank import total
        $bankImport = fetchRow("SELECT * FROM (SELECT round(0.01*sum(amount),2) AS total FROM members_bankimport
                WHERE member_id= " . $member_id . "  AND LOWER(category) IN (SELECT LOWER(category) FROM activity_listcategory)
                AND date_trunc('day', time) > (current_date - 8)
                AND date_trunc('day', time) < current_date) AS c WHERE c.total IS NOT NULL");

        if ($bankimport) {
            $total_bank = $bankImport["total"];
        }

        $totalEmail = fetchRow("SELECT * FROM (SELECT round(sum(a.cost),2) AS total
        FROM parsedemail_item a, trackedemail_item b WHERE b.id=a.trackedemail_item_id
        AND b.member_id= " . $member_id . "  AND a.dup_id IS NULL AND  date_trunc('day', a.travel_date_end) > (current_date - 8)
        AND date_trunc('day', a.travel_date_end) < current_date) AS c WHERE c.total IS NOT NULL");

        if ($totalEmail) {
            $total_email = $totalEmail["total"];
        }

        $total_weekly_spend = $total_bank + $total_email;

        if ($total_weekly_spend > $total_weekly_budget && $total_weekly_budget > 0) {
            $over_spending = $total_weekly_spend - $total_weekly_budget;
            $out["over_spending"] = $over_spending;
            $out["user_budget_percentabove"] = ($over_spending / $total_weekly_budget);
        }

        if ($total_weekly_budget > $total_weekly_spend && $total_weekly_budget > 0) {
            $under_spending = $total_weekly_budget - $total_weekly_spend;
            $out["under_spending"] = $under_spending;
            $out["user_budget_percentbelow"] = ($under_spending / $total_weekly_budget);
        }

        $out["weekly_total"] = $total_weekly_spend;

        return 0;
    }
}

public function detectMemberLocation($member_id, &$out)
{
    return 0;
}




}
