<?php
/****************************
 * File : dealer.php
 * Author : Cygnusa
 * @2018
 ****************************/

//SECURITY
if (!defined('APPLICATION_PATH')) {
    exit('No direct script access allowed');
}

//FUNCTION LISTS

class dealer
{

    public function __construct($parent)
    {

        //GET PAGE MESSAGE
        $this->page_data = globalfunc::getMessage($parent, $parent->lang, 'dealer');
        if (count($parent->params) == 0) {
            $parent->response(array('response' => 'failed', 'message' => 'PAGE NOT FOUND'), 404);

        } else {
            $qry_params = explode("?", $parent->params[0]);
            $parameter_val = strtolower($qry_params[0]);

            switch ($parameter_val) {
                case "userlist":
                case "dsestatusupdate":
                case "dseactivetinactivelist":
                    $this->$parameter_val($parent);
                    break;

                default:
                    $parent->response(array('response' => 'failed', 'message' => 'PAGE NOT FOUND'), 404);
                    break;
            }

        }
        $parent->response(array('response' => 'failed', 'message' => 'PAGE NOT FOUND'), 404);
    }

    /* /////////////////////////////// USERLIST //////////////////////////////////////////////// */
    private function userlist($parent)
    {

        globalfunc::checkMethodType($parent, array('GET', 'POST'));
        //globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('7', '14'));

        if ($parent->current_user_role == '7') {
            $REQUEST_KEYS = array('dealer_code' => 'string');
            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

            $dealer_code = escape_str($parent->_request['dealer_code']);
        } else {
            $dealer_code = $parent->current_user_data->dealer_code;
            $segment = escape_str($parent->params[1]);
            $history = escape_str($parent->params[2]);
            $segment_cond = $user_cond = "";

            switch ($segment) {
                case '1':
                    $segment_cond .= " AND e.segment = 1";
                    break;
                case '2':
                    $segment_cond .= " AND e.segment = 2";
                    break;
                default:
                    //$segment_cond .= " AND e.segment = 2;
                    break;
            }
            // if (!empty($segment)) {}
            $user_cond .= ($history == '1') ? " AND u.status='1' AND u.is_deleted=0 AND e.is_current='1' " : " AND e.is_current='1'";
        }

        //GET DATA FROM EMPLOYEE
        $query_str = "SELECT e.smpin,e.fname,e.lname,e.mobile,CASE WHEN u.userid is NULL THEN '0' WHEN u.userid is NOT NULL AND u.status=1 THEN '1' ELSE '2' END as userstatus ,CASE WHEN u.userid is NULL THEN '3' WHEN u.userid is NOT NULL AND u.status=1 THEN '1' ELSE '2' END as userorder,COALESCE(u.profile_photo,'') as profile_photo FROM " . DMS_EMPLOYEE . " e LEFT JOIN " . TABLE_USER . " u ON u.smpin=e.smpin  WHERE e.status=1 AND e.dealer_code='" . $dealer_code . "' " . $segment_cond . $user_cond . " ORDER BY userorder ASC,e.fname ASC";
        $data_arr = $parent->getQueryValue($query_str);

        $data = (count($data_arr) > 0) ? $data_arr : array();

        $s3 = awsfileserver::connectS3();
        foreach ($data as $key => $res) {
            $data[$key]->profile_photo = ($res->profile_photo != '') ? awsfileserver::getS3FileUrl($s3, S3_BUCKET, S3_PROFILE_IMAGE_URL . $res->profile_photo) : '';
        }

        //LOG
        $logstr = 'DEALER USER DATA';
        globalfunc::insertUserLog($parent, $logstr, $parent->current_user_id);
        $parent->response(array('response' => 'success', 'data' => $data, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// DSEACTIVETINACTIVELIST //////////////////////////////////////////////// */
    private function dseactivetinactivelist($parent)
    {
        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('7', '14'));
        $status = escape_str($parent->params[1]);

        $query_getuserarr = $parent->selectQuery(TABLE_DSE_ACTIVE_DEACTIVE_LIST, "  `id`, `name`, `created_on`, `modified_on`", "status='" . $status . "' ");

        //LOG
        $logstr = 'DSE ACTIVE DEACTIVE DATA';
        globalfunc::insertUserLog($parent, $logstr, $parent->current_user_id);
        $parent->response(array('response' => 'success', 'data' => $query_getuserarr['result'], 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// DSESTATUSUPDATE //////////////////////////////////////////////// */
    private function dsestatusupdate($parent)
    {

        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('7', '14'));

        $REQUEST_KEYS = array('smpin' => 'string', 'status' => 'number');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $smpin = escape_str($parent->_request["smpin"]);
        $status = (escape_str($parent->_request["status"]) == 1) ? "1" : "2";
        $remark = escape_str($parent->_request["remark"]);
        $remarkoption = escape_str($parent->_request["remarkoption"]);

        if ($parent->current_user_role == '7') {
            $REQUEST_KEYS = array('dealer_code' => 'string');
            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

            $dealer_code = escape_str($parent->_request['dealer_code']);
        } else {
            $dealer_code = $parent->current_user_data->dealer_code;
        }

        //CHECK USER EXIST
        $query_str = "SELECT fname, lname, userid, dealer_code, smpin FROM " . TABLE_USER . " WHERE dealer_code='" . $dealer_code . "' AND smpin='" . $smpin . "' AND role>7 and role<14 LIMIT 1";
        $data_arr = $parent->getQueryValue($query_str);
        if (!count($data_arr) > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error2']), 406);
        }

        //UPDATE
        $cond_str = ($status == 2) ? ",inactivated_on='" . NOW . "',auth_token='' " : "";
        $parent->executeQuery("UPDATE " . TABLE_USER . " SET status='" . $status . "' " . $cond_str . " WHERE userid='" . $data_arr[0]->userid . "'");

        $insert_qry = "INSERT INTO " . TABLE_USER_STATUS_HISTORY . " ( `userid`, `action_user`,status, `remarks`, `remarkoption`,`created_on`) VALUES ('" . $data_arr[0]->userid . "', '" . $parent->current_user_id . "','" . $status . "', '" . $remark . "','" . $remarkoption . "','" . NOW . "')";
        $parent->executeQuery($insert_qry);

        $query_getdealerarr = $parent->selectQuery(DMS_DEALER, " email, rm_name, rm_email, am_name, am_email, dealer_code ", "dealer_code='" . $data_arr[0]->dealer_code . "' ");

        if ($status == 1) {
            $to_mail = $query_getdealerarr['result'][0]->email;
            $subject = 'Dealer Activation | DSE ' . trim($data_arr[0]->fname . " " . $data_arr[0]->lname) . " (" . $data_arr[0]->smpin . ") ";
            $message = '<table width="100%" bgcolor="#dfdfdf" border="0" cellspacing="10" cellpadding="0" style="padding-top:10px;">
              <tbody>
                <tr>
                  <td>
                    <table width="700" border="0" align="center" cellpadding="0" cellspacing="0" style="background:#ffffff; margin-top:0px;">
                      <tbody>
                        <tr>
                          <td bgcolor="#2d2d2d" height="36" style="font-size:12px;  font-family:Arial, Helvetica, sans-serif;   color:#e4e4e4;  text-align:left;    font-weight:bold; padding-left:14px; border-bottom:2px solid black">' . $subject . '</td>
                        </tr>
                        <tr>
                          <td>
                            <table width="85%" align="center">
                              <tbody>
                                <tr>
                                  <td height="30" style="font-size:11px;    font-family:Arial, Helvetica, sans-serif;   color:#3f3f3f;  text-align:left;padding-left: 10px;
                                line-height: 1.5;">
                                    <div style="font-family:arial; color:#333; font-size:12px; padding:5px;">Dear San,</div>
                                  </td>
                                </tr>
                                <tr>
                                  <td height="30" style="font-size:11px;    font-family:Arial, Helvetica, sans-serif;   color:#3f3f3f;  text-align:left;padding-left: 10px;
                                line-height: 1.5;">
                                    <div style="font-family:arial; color:#333; font-size:12px; padding:5px;">I have activated the HYPER-M App access of ' . trim($data_arr[0]->fname . ' ' . $data_arr[0]->lname) . ' (SMPIN: ' . $data_arr[0]->smpin . ')</div>
                                  </td>
                                </tr>
                              </tbody>
                            </table>
                          </td>
                        </tr>
                        <tr>
                          <td style="padding-top:0px; padding-bottom:10px;"></td>
                        </tr>
                        <tr>
                        <td style="font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#3f3f3f; background:#fafafa; line-height:30px; text-align:center; border-bottom:2px solid black"><div class="footer-con">  <p>Thanks &amp; Regards, <strong style="color:#070000;">HYPER-M App Support Team</strong></p>
                         </div></td>
                        </tr>
                      </tbody>
                    </table>
                  </td>
                </tr>
              </tbody>
            </table>';

            // Notification Details
            $notificationtitle = 'Dealer Activation';
            $notificationtext = $data_arr[0]->fname . ' ' . $data_arr[0]->lname . ' & ' . $data_arr[0]->smpin . ' has been re-activated  by ' . $query_getdealerarr['result'][0]->am_name . ' on ' . date('Y-m-d');
            $notificationtype = '5';

            // Notification user id
            $query_str = "SELECT userid FROM " . TABLE_USER . " WHERE dealer_code = '" . $query_getdealerarr['result'][0]->dealer_code . "' AND role = 14 LIMIT 1";
            $notification_data_arr = $parent->getQueryValue($query_str);
            $notification_user_id = $notification_data_arr[0]->userid;

        } else if ($status == 2) {
            // Reason
            $query_getreasonarr = $parent->selectQuery(TABLE_DSE_ACTIVE_DEACTIVE_LIST, " name ", "id='" . $remarkoption . "' ");

            $to_mail = $query_getdealerarr['result'][0]->rm_email;
            $subject = 'Dealer Deactivation ' . trim($data_arr[0]->fname . " " . $data_arr[0]->lname) . " (" . $data_arr[0]->smpin . ") ";
            $message = '<table width="100%" bgcolor="#dfdfdf" border="0" cellspacing="10" cellpadding="0" style="padding-top:10px;">
              <tbody>
                <tr>
                  <td>
                    <table width="700" border="0" align="center" cellpadding="0" cellspacing="0" style="background:#ffffff; margin-top:0px;">
                      <tbody>
                        <tr>
                          <td bgcolor="#2d2d2d" height="36" style="font-size:12px;  font-family:Arial, Helvetica, sans-serif;   color:#e4e4e4;  text-align:left;    font-weight:bold; padding-left:14px; border-bottom:2px solid black">' . $subject . '</td>
                        </tr>
                        <tr>
                          <td>
                            <table width="85%" align="center">
                              <tbody>
                                <tr>
                                  <td height="30" style="font-size:11px;    font-family:Arial, Helvetica, sans-serif;   color:#3f3f3f;  text-align:left;padding-left: 10px;
                                line-height: 1.5;">
                                    <div style="font-family:arial; color:#333; font-size:12px; padding:5px;">Dear San,</div>
                                  </td>
                                </tr>
                                <tr>
                                  <td height="30" style="font-size:11px;    font-family:Arial, Helvetica, sans-serif;   color:#3f3f3f;  text-align:left;padding-left: 10px;
                                line-height: 1.5;">
                                    <div style="font-family:arial; color:#333; font-size:12px; padding:5px;">I have de-activated the HYPER-M App access of ' . trim($data_arr[0]->fname . ' ' . $data_arr[0]->lname) . ' (SMPIN: ' . $data_arr[0]->smpin . ') due to following reason </div>
                                    <div style="font-family:arial; color:#333; font-size:12px; padding:5px;">' . $query_getreasonarr['result'][0]->name . ' </div>
                                  </td>
                                </tr>
                              </tbody>
                            </table>
                          </td>
                        </tr>
                        <tr>
                          <td style="padding-top:0px; padding-bottom:10px;"></td>
                        </tr>
                        <tr>
                        <td style="font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#3f3f3f; background:#fafafa; line-height:30px; text-align:center; border-bottom:2px solid black"><div class="footer-con">  <p>Thanks &amp; Regards, <strong style="color:#070000;">HYPER-M App Support Team</strong></p>
                         </div></td>
                        </tr>
                      </tbody>
                    </table>
                  </td>
                </tr>
              </tbody>
            </table>';

            // Notification Details
            $notificationtitle = 'Dealer Deactivation';
            $notificationtext = $data_arr[0]->fname . ' ' . $data_arr[0]->lname . ' & ' . $data_arr[0]->smpin . ' has been marked ' . $query_getreasonarr['result'][0]->name . ' by ' . $data_arr[0]->fname . ' ' . $data_arr[0]->lname . ' & ' . $data_arr[0]->dealer_code . ' on ' . date('Y-m-d');
            $notificationtype = '5';

            // Notification user id
            $query_str = "SELECT userid FROM " . TABLE_USER . " WHERE emailid = '" . $query_getdealerarr['result'][0]->am_email . "' AND role = 7 LIMIT 1";
            $notification_data_arr = $parent->getQueryValue($query_str);
            $notification_user_id = $notification_data_arr[0]->userid;

        }

        $obj = array();
        $obj['from'] = SUPPORT_EMAIL;
        $obj['to'] = $to_mail;
        $obj['subject'] = $subject;
        $obj['message'] = $message;
        // globalfunc::sendMai($parent, $obj);

        //SEND NOTIFICATION
        $nobj = new stdClass();
        $nobj->notificationtitle = $notificationtitle;
        $nobj->notificationtext = $notificationtext;
        $nobj->notificationtype = $notificationtype;
        $nobj->notificationdata = new stdClass();
        // projectfunc::sendUserNotification($parent, $nobj, $notification_user_id);

        //LOG
        $logstr = 'USER STATUS UPDATE';
        globalfunc::insertUserLog($parent, $logstr, $parent->current_user_id);
        $parent->response(array('response' => 'success', 'message' => $this->page_data['success1']), 200);
    }

}
