<?php

function loadSliderCard($in, &$out)
{
    global $pgconn;
    $retvel = 0;
    $total_record = 0;
    $status = 'OK';
    $card_type = $in['card_type'];
    $card_count = $in['card_count'];
    $member_id = $in['member_id'];
    $out['status'] = $status;
    $out['session_valid'] = '';
    $member = getMember($member_id);
    if ($member) {
        $survey = getCardBySurvey($member);
        getCardsByType($out, $member, $card_type, $card_count);

    }

}

function getCardsByType(&$out, $member, $card_type, $limit = 10)
{
    global $pgconn;
    $member_id = $member['id'];
    switch ($card_type) {
        case 33000:
            $query = "SELECT ca.id AS assign_id, ca.subscribe, a.*, a.id AS card_id,b.name AS card_action_name,b.type AS card_action_type,b.data AS card_action_data,adr.latitude,adr.longitude,
            EXTRACT(DAY FROM (CASE WHEN a.card_expiration IS NULL THEN now() -now()  ELSE a.card_expiration -now()  END)) AS expr_val, a.card_canexpire
            FROM main_cards a
            LEFT JOIN card_actions b ON (b.id=a.card_action_id)
            LEFT JOIN address adr ON adr.id = a.card_location
            LEFT JOIN members_card_assign ca ON ca.card_id=a.id AND ca.member_id=" . $member_id . " AND ca.status=1
            WHERE a.status = 1 AND a.deleted IS NULL AND a.button1_action IN ('GOOFFERS','CARPOOL') ORDER BY a.card_order ASC";
            break;
        case 22000:
            $query = "SELECT ca.id AS assign_id, ca.subscribe, a.*, a.id AS card_id,b.name AS card_action_name,b.type AS card_action_type,b.data AS card_action_data,adr.latitude,adr.longitude,ca.trigger_key,ca.message,ca.cat,
          EXTRACT(DAY FROM (CASE WHEN a.card_expiration IS NULL THEN now() -now()  ELSE a.card_expiration -now()  END)) AS expr_val, a.card_canexpire
          FROM  members_card_assign ca
          LEFT JOIN main_cards a ON a.id=ca.card_id
          LEFT JOIN address adr ON adr.id = a.card_location
          LEFT JOIN card_actions b ON (b.id=a.card_action_id)
          WHERE ca.member_id = " . $member_id . " AND ca.status =1 AND a.status=1 AND show_area IN (" . CARD_LOCATION_DEFAULT . "," . CARD_LOCATION_MAINFEED . ") AND a.deleted IS NULL AND ca.subscribe IS NULL AND ca.completed IS NULL ORDER BY a.card_order ASC";
            break;

        case 55000:
            $query = "SELECT ca.id AS assign_id, ca.subscribe, a.*, a.id AS card_id,b.name AS card_action_name,b.type AS card_action_type,b.data AS card_action_data,adr.latitude,adr.longitude,ca.trigger_key,ca.message,ca.cat,
                 EXTRACT(DAY FROM (CASE WHEN a.card_expiration IS NULL THEN now() -now()  ELSE a.card_expiration -now()  END)) AS expr_val, a.card_canexpire
                 FROM  members_card_assign ca
                 LEFT JOIN main_cards a ON a.id=ca.card_id
                 LEFT JOIN address adr ON adr.id = a.card_location
                 LEFT JOIN card_actions b ON (b.id=a.card_action_id)
                 WHERE ca.member_id = " . $member_id . " AND a.button1_action IN ('GOOFFERS') AND  ca.subscribe IS NOT NULL ORDER BY ca.subscribe ASC";
            break;

        case 11000:
            $query = "SELECT a.*, a.id AS card_id,b.name AS card_action_name,b.type AS card_action_type,b.data AS card_action_data
                    FROM main_cards a LEFT JOIN card_actions b ON (b.id=a.card_action_id)
                    WHERE a.status = 1 AND a.deleted IS NULL  ORDER BY RANDOM()";
            break;
    }
    $deal_card_count = 0;
    $survey_card_count = 0;
    $blog_card_count = 0;
    $r = pg_query($pgconn, $query);
    $out['total_record_raw'] = pg_num_rows($r);
    $out['total_record'] = pg_num_rows($r);
    $out['retval'] = PHP_API_OK;
    $out['internal_return'] = PHP_API_OK;
    $query = $query . " LIMIT " . $limit . "";
    $r = pg_query($pgconn, $query);
    $result = [];
    if ($r && $total_record_raw = pg_num_rows($r)) {
        $ic = 0;
        while ($f = pg_fetch_assoc($r)) {
            $test_card_allowed = CARD_ADD_ALLOWED;
            if ($card_type == 22000) {
                $test_card_allowed = verifyMemberCardDescision($f, $member, $out);
            }
            $card_country_allow = true;

            if ($f["card_country"] != "") {
                $card_country_allow = false;

                if ($f["card_country"] == $member["country"]) {
                    $card_country_allow = true;
                }

            }

            $count_block = false;

            // let see i card expired
            $expr_value = $f["expr_val"];
            if ($f["card_canexpire"] == 1 && $expr_value < 0) {
                $count_block = true;
            } else {
                if ($card_type == 22000) {

                    if ($f["button1_action"] == "GOOFFERS") {
                        if ($deal_card_count > 0) {
                            $count_block = true;
                        }
                        if ($f["card_country"] == "" || $f["card_country"] == $member["country"]) {
                            $deal_card_count++;
                        }
                    }

                    if ($f["button1_action"] == "SURVEYA") {
                        if ($fsurvey_card_count > 0) {
                            $count_block = true;
                        }
                        $survey_card_count++;
                    }

                    if ($f["button1_action"] == "BLOGCARD") {
                        if ($blog_card_count > 0) {
                            $count_block = true;
                        }
                        $blog_card_count++;
                    }

                }
            } //card is not expired

            if (CARD_ADD_ALLOWED == $test_card_allowed && true == $card_country_allow && false == $count_block) {
                $suffix = str_pad($ic, 5, '0', STR_PAD_LEFT);
                //fillSuffixCard($out, $f, $suffix);
                $out['name_' . $suffix] = $f['name'];
                $out['assign_id_' . $suffix] = $f['assign_id'];
                $out['card_id_' . $suffix] = $f['card_id'];
                $out['can_save_' . $suffix] = $f['can_save'];
                $out['short_title_' . $suffix] = $f['short_title'];
                $out['title_' . $suffix] = $f['short_title'];
                $out['background_picture_' . $suffix] = $f['background_picture'];
                $out['button1_' . $suffix] = $f['button1'];
                $out['button1_text_' . $suffix] = $f['button1_text'];
                $out['button1_action_' . $suffix] = $f['button1_action'];
                $out['expires_' . $suffix] = $f['card_expiration'];
                $out['template_' . $suffix] = $f['template'];
                $out['card_canexpire_' . $suffix] = $f['card_canexpire'];
                $out['card_action_type_' . $suffix] = $f['card_action_type'];
                $out['card_action_data_' . $suffix] = $f['card_action_data'];
                $out['titleshow_' . $suffix] = $f['titleshow'];
                $out['multiple_answer_' . $suffix] = $f['multiple_answer'];
                $out['use_short_title_' . $suffix] = $f['use_short_title'];
                $out['target_key_' . $suffix] = $f['target_key'];
                $out['target_text_' . $suffix] = $f['target_text'];
                $out['description_' . $suffix] = $f['description'];
                $out['long_description_' . $suffix] = $f['long_description'];
                $out['card_behavior_' . $suffix] = $f['card_behavior'];
                $out['card_type_' . $suffix] = $f['card_type'];
                $out['card_time_' . $suffix] = $f['card_time'];
                $out['card_country_' . $suffix] = $f['card_country'];
                $out['card_location_' . $suffix] = $f['card_location'];
                $out['latitude_' . $suffix] = $f['latitude'];
                $out['longitude_' . $suffix] = $f['longitude'];
                $out['card_order_' . $suffix] = $f['card_order'];
                $out['background_color_' . $suffix] = $f['background_color'];
                $out['blog_id_' . $suffix] = $f['blog_id'];
                $out['expiration_' . $suffix] = $f['expiration'];
                if ($f["button1_action"] == "CARPOOL") {

                    $carPool = fetchRow("SELECT * FROM members_carpool_friends WHERE carpool_id IN (select id from members_carpool  WHERE member_id = " . $member_id . ") AND status = 1");

                    if ($carPool && $carPool['added']) {
                        $out['subscribe_' . $suffix] = $carPool["added"];
                    } else {
                        $out['subscribe_' . $suffix] = "";
                    }

                } else {
                    $out['subscribe_' . $suffix] = $f["subscribe"];
                }
                $ic++;
            }
        }
        $out['total_record'] = $ic;
    }

}

function verifyMemberCardDescision($cardData, $memberData, &$out)
{
    $permCard = CARD_ADD_ALLOWED;
    $behaviour = $cardData["card_behavior"];

    if (function_exists("behaviour_" . $behaviour)) {
        $permCard = call_user_func("behaviour_" . $behaviour, $memberData, $out);
    } else {
        $permCard = CARD_ADD_ALLOWED;
    }

    return $permCard;
}

function saveDashCard($in, &$out)
{
    $ret = PHP_API_BAD_PARAM;
    $member_id = $in['member_id'];
    $card_id = $in['card_id'];
    $out["saved_card_id"] = "0";
    $saveCard = fetchRow("SELECT id FROM member_saved_cards WHERE member_id=" . $member_id . " AND card_id=" . $card_id . "");

    if (empty($saveCard)) {
        $insertCard = "INSERT INTO member_saved_cards (member_id,card_id) VALUES (" . $member_id . "," . $card_id . ") RETURNING id";
        $out["saved_card_id"] = insertQuery($insertCard);
        if ($out['saved_card_id'] > 0) {
            $ret = PHP_API_OK;
        }
    }
    return $ret;
}

function loadSavedCard($in, &$out)
{
    $ret = PHP_API_BAD_PARAM;

    $member_id = $in['member_id'];

    $out["total_record"] = 0;
    $out['session_valid'] = '';
    $out['internal_return'] = PHP_API_OK;
    $saveCards = selectData("SELECT m.id AS saved_card_id, mc.*,mc.id AS card_id FROM member_saved_cards m LEFT JOIN main_cards mc ON m.card_id = mc.id WHERE m.member_id = " . $member_id . " AND m.status = 1");
    if ($saveCards != null) {
        $out["total_record"] = pg_num_rows($saveCards);
        $ic = 0;

        while ($f = pg_fetch_assoc($saveCards)) {
            $suffix = str_pad($ic, 5, '0', STR_PAD_LEFT);
            $out['name_' . $suffix] = $f['name'];
            $out['short_title_' . $suffix] = $f['short_title'];
            $out['title_' . $suffix] = $f['title'];
            $out['description_' . $suffix] = $f['description'];
            $out['short_title_' . $suffix] = $f['short_title'];
            $out['title_' . $suffix] = $f['short_title'];
            $out['background_picture_' . $suffix] = $f['background_picture'];
            $out['button1_' . $suffix] = $f['button1'];
            $out['button1_text_' . $suffix] = $f['button1_text'];
            $out['button1_action_' . $suffix] = $f['button1_action'];
            $out['can_save_' . $suffix] = $f['can_save'];
            $out['card_id_' . $suffix] = $f['card_id'];
            $out['template_' . $suffix] = $f['template'];
            $out['card_canexpire_' . $suffix] = $f['card_canexpire'];
            $out['card_canexpire_' . $suffix] = $f['card_canexpire'];
            $out['expires_' . $suffix] = $f['card_expiration'];
            //$out['card_action_type_' . $suffix] = $f['card_action_type'];
            //$out['card_action_data_' . $suffix] = $f['card_action_data'];
            $out['titleshow_' . $suffix] = $f['titleshow'];
            $ic++;
        }
    }
    $ret = PHP_API_OK;
    $out["status"] = "OK";
    return $ret;
}

function userTrackCardClick($in, &$out)
{
    $ret = PHP_API_BAD_PARAM;
    $member_id = $in['member_id'];
    $card_id = $in['card_id'];

    processCard($in, $out); // see if cleanout is needed

    $insertCard = "INSERT INTO members_cardclicktrack (member_id,card_id) VALUES (" . $member_id . "," . $card_id . ") RETURNING id";
    $out["card_track_id"] = insertQuery($insertCard);
    if ($out['card_track_id'] > 0) {
        $ret = PHP_API_OK;
    }
    return $ret;
}

function processCard($in, &$out)
{

    $ret = PHP_API_BAD_PARAM;
    $member_id = $in['member_id'];
    $card_id = $in['card_id'];

    $card = fetchRow("SELECT id,button1_action,title,expiration FROM main_cards WHERE id=" . $card_id . "");
    if ($card) {
        if ($card["button1_action"] == "CARPOOL") {
            updateQuery("UPDATE members_card_assign SET status = 0,completed=now(),updated=now() WHERE card_id=" . $card_id . " AND member_id=" . $member_id . "");
        }

        if ($card["expiration"] == 100) {
            updateQuery("UPDATE members_card_assign SET status = 0,updated=now() WHERE card_id=" . $card_id . " AND member_id=" . $member_id . "");
        }

        // let us see if this is a dynamic card
        $assignCard = fetchRow("SELECT mca.id AS assign_id,mc.dynamic_key,et.expiration,EXTRACT(EPOCH FROM now() - mca.updated)/3600 AS card_age
                            FROM members_card_assign mca LEFT JOIN main_cards mc ON mc.id=mca.card_id LEFT JOIN email_trigger et ON et.dynamic_key = mc.dynamic_key
                            WHERE mca.member_id =" . $member_id . " AND mca.trigger_key IS NOT NULL AND mca.card_id = " . $card_id . " ");
        if ($assignCard) {
            if ($assignCard["expiration"] == "EXP00002") {
                // rule 1 expire on first contact
                updateQuery("UPDATE members_card_assign SET status = 0 WHERE id= " . $assignCard['assign_id'] . " AND member_id=" . $member_id . "");
            }

        }
    }

    return $ret;
}

function userCardAdd($member_id, $card_id, &$out)
{
    global $pgconn;
    $ret = PHP_API_BAD_PARAM;
    $assignCard = fetchRow("SELECT id AS assign_id,status AS card_status FROM members_card_assign WHERE card_id=" . $card_id . " AND member_id=" . $member_id . " AND status IN (0,1)");

    if ($assignCard) {
        if ($assignCard['card_status'] == 0) {
            $click = fetchRow("SELECT expiration FROM members_cardclicktrack mc LEFT JOIN main_cards a ON a.id=mc.card_id WHERE a.id=" . $card_id . " AND mc.member_id=" . $member_id . " LIMIT 1");
            if ($click && $click['expiration'] == 0) {
                $out["status"] = "This card is expired";
            } else {
                $ret = PHP_API_OK;
            }
            $ret = updateQuery("UPDATE members_card_assign SET status = 1, updated=NOW() WHERE id = " . $assignCard['assign_id'] . " AND member_id = " . $member_id . "");

        } else {
            $out["status"] = "This card was already added";
        }
    } else {
        //insert assign card
        $insertCard = "INSERT INTO members_card_assign (card_id,member_id) VALUES (" . $card_id . "," . $member_id . ") RETURNING id";
        $out['id'] = insertQuery($insertCard);
        if ($out['id'] > 0) {
            $ret = PHP_API_OK;
        }
    }

    return $ret;
}

function getCardBySurvey($member)
{
    global $pgconn;
    $member_id = $member['id'];
    $q = "SELECT card_id FROM  members_onboarding_survey mos
            LEFT JOIN onboarding_survey_cards ca ON ca.answers_key = mos.answers_key
            LEFT JOIN main_cards a ON a.id=ca.card_id
            WHERE mos.member_id = " . $member_id . " AND a.status = 1
            AND card_id NOT IN (SELECT card_id FROM members_card_assign WHERE member_id =" . $member_id . " AND status=1)
            GROUP BY card_id";
    $r = pg_query($pgconn, $q);
    if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
        return $f;
    }
    return null;
}
