<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Note_model extends CI_Model {

    var $topnum = false;
    var $orderby = false;
    var $pn_send = false;
    var $search = false;
    var $pn_txn_id=false;
    var $pn_payment_status = false;

    function __construct() {
        parent::__construct();
        $this->HT = $this->load->database('HT', TRUE);
        //$this->DEST = $this->load->database('DEST', TRUE);
    }

    public function init() {
        $this->topnum = false;
        $this->pn_send = false;
        $this->search = false;
        $this->pn_payment_status = false;
        $this->pn_txn_id = false;
        // $this->orderby = ' ORDER BY pn.pn_sn DESC ';
        $this->orderby = ' ORDER BY pn_datetime desc,pn_payer desc ';
        //$this->pn_payment_status=' AND pn_payment_status= ';
    }

    public function unsend($topnum = 2) {
        $this->init();
        $this->topnum = $topnum;
        $this->pn_send = " AND (pn_send='unsend' OR pn_send IS NULL) ";
        return $this->get_list();
    }

    public function failnotec($topnum = 2) {
        $this->init();
        $this->topnum = $topnum;
        $this->pn_send = " AND (pn_send='sendfail'  OR pn_send='') AND pn_payment_status='Completed' ";
		//$this->orderby = ' ORDER BY pn.pn_sn ASC ';
        return $this->get_list();
    }

    public function failnote($topnum = 2) {
        $this->init();
        $this->topnum = $topnum;
        $this->pn_send = " AND (pn_send='sendfail'  OR pn_send='') ";
		//$this->orderby = ' ORDER BY pn.pn_sn ASC ';
        return $this->get_list();
    }

    public function notestatus($topnum = 2, $status = '') {
        $this->init();
        $this->topnum = $topnum;
        $sql = " AND pn_memo NOT LIKE '{\"id\":\"WH-%' ";
        $x_status = strtolower($status) === 'reversal' ? 'revers' : $status;
        $sql1 = in_array(strtolower($status), ["completed", 'pending']) ? " AND (pn_payment_status='$status' ) " : "";
        $sql2 = in_array(strtolower($status), ["refunded", "reversal"]) ? " AND (pn_payment_status like '%$x_status%' ) " : "";
        $sql3 = in_array(strtolower($status), ["others"]) ? " AND (pn_payment_status='failed' OR pn_payment_status='denied' ) " : "";
        $sql4 = in_array(strtolower($status), ["case"]) ? " AND (pn_memo like '{\"txn_type\":\"new_case\"%' AND pn_mc_gross = '0' ) " : "";
        $this->pn_send = $sql1 . $sql2 . $sql3 . $sql4 . $sql;
        // $this->orderby=" ORDER BY pn_payment_date DESC, pn.pn_sn ASC ";
        $this->orderby=" ORDER BY CASE pn.pn_send WHEN 'sendfail' THEN 1 ELSE 2 END ,pn.pn_sn DESC ";
        return $this->get_list();
    }

    public function noteaccount($topnum = 2, $account = '') {
        $this->init();
        $this->topnum = $topnum;
        $x_str = strtolower($account);
        $sql4 = " AND (pn_memo like '%\"business\":\"$x_str\"%') ";
        $this->pn_send = $sql4;
        return $this->get_list();
    }

    public function search_date($date) {
        $this->init();
        $search_sql = " AND (pn.pn_datetime BETWEEN '$date 00:00:00' AND '$date 23:59:59' OR isnull(pn_send,'') in ('sendfail','unsend','')) AND pn_memo NOT LIKE '{\"id\":\"WH-%' "; // {"id":"WH-
        $this->search = $search_sql;
        // $this->orderby=" ORDER BY CASE pn.pn_send WHEN 'sendfail' THEN 1 ELSE 2 END ,pn.pn_sn DESC ";
        $this->orderby=" ORDER BY CASE WHEN pn.pn_send='sendfail' AND pn.pn_payment_status='Completed' THEN 1 WHEN pn.pn_send = 'sendfail' THEN 2 ELSE 9 END ,pn.pn_sn DESC ";
        // WHEN pn.pn_send = 'sendfail' THEN 2

        return $this->get_list();
    }

    public function note($pn_txn_id, $pn_sn=NULL){
        $this->init();
        $this->topnum=1;
        $this->pn_txn_id=" AND  pn.pn_txn_id=".$this->HT->escape($pn_txn_id);
        $this->pn_txn_id .= !($pn_sn) ? "" : " AND  pn.pn_sn=".$this->HT->escape($pn_sn);
        $this->orderby=" ORDER BY pn_payment_date, pn_payer desc ";
        return $this->get_list();
    }

    public function search_key($search_key) {
        $this->init();
        $this->topnum = 300; //限制最大数量，防止查询单词过短
        $search_sql = '';
        $search_key = trim($search_key);
        if (!empty($search_key)) {
            $search_sql.=" AND ( pn.pn_txn_id = '$search_key'
                                    OR pn.pn_invoice like '%$search_key%'
                                    OR pn.pn_custom like '%$search_key%'
                                    OR pn.pn_item_name like '%$search_key%'
                                    OR pn.pn_item_number like '%$search_key%'
                                    OR pn.pn_payer like '%$search_key%'
                                    OR pn.pn_payer_email like '%$search_key%' )";
        }
        $this->search = $search_sql;
        return $this->get_list();
    }

    //存储paypal的实时通知
    public function save_paypal_note($pn_txn_id, $pn_invoice, $pn_custom, $pn_mc_gross, $pn_item_name, $pn_item_number, $pn_mc_currency, $pn_payment_status, $pn_payer, $pn_payer_email, $pn_payment_date, $pn_memo) {
        $sql = "
                INSERT INTO paypal_note
                  (
                    pn_txn_id,pn_invoice,pn_custom, pn_mc_gross, pn_item_name, pn_item_number,pn_mc_currency, pn_payment_status,pn_payer,pn_payer_email,pn_payment_date, pn_memo,pn_datetime,pn_send
                  )
                VALUES
                  (
                    ?,N?,N?,?,N?,N?,?,?,N?,N?,?, N?, GETDATE(),'unsend'
                  )
        ";
        $query = $this->HT->query($sql, array($pn_txn_id, $pn_invoice, $pn_custom, $pn_mc_gross, mb_substr($pn_item_name, 0, 250) , $pn_item_number, $pn_mc_currency, $pn_payment_status, $pn_payer, $pn_payer_email, $pn_payment_date, $pn_memo));
        $insertid = $this->HT->last_id('paypal_note');
        return $query;
    }

    public function get_list() {
        $this->topnum ? $sql = "SELECT TOP " . $this->topnum : $sql = "SELECT ";
        $sql .= "
                    pn.pn_sn
                  ,pn.pn_txn_id
                  ,dbo.GetOrderCusCountry(pn_invoice) as payer_country
                  ,replace(replace(pn.pn_invoice,char(13),' '),char(10),' ') pn_invoice
                  ,pn.pn_custom
                  ,pn.pn_mc_gross
                  ,pn.pn_item_name
                  ,pn.pn_item_number
                  ,pn.pn_mc_currency
                  ,pn.pn_payment_status
                   ,pn.pn_payer
                  ,pn.pn_payer_email
                  ,pn.pn_memo
                  ,pn.pn_datetime
                  ,pn.pn_payment_date
                  ,pn.pn_send
            FROM   paypal_note pn
            WHERE 1=1
                 ";
        $this->pn_send ? $sql.=$this->pn_send : false;
        $this->search ? $sql.=$this->search : false;
        $this->pn_txn_id ? $sql.=$this->pn_txn_id : false;
        $this->orderby ? $sql.=$this->orderby : false;
        log_message('error',$sql);
        $query = $this->HT->query($sql);
        // print_r($this->HT->queries);
        if ($this->topnum === 1) {
            if ($query->num_rows() > 0) {
                $row = $query->row();
                $this->set_fundsource($row);
                return $row;
            } else {
                return FALSE;
            }
        } else {
            $result = $query->result();
            array_walk($result, 'note_model::set_fundsource');
            return $result;
        }
    }
    private $code_fundsource = array(
        "pay@trippest.com" => "Trippest", // business":"pay@trippest.com"
        "pays@chinahighlights.com" => "", // "CHT",
        "paypal@chinahighlights.com" => "2", // "CHT",
        "0" => "unknown",
    );
    public function set_fundsource(&$ele)
    {
        $ele->fundsource = "";
        $raw = json_decode($ele->pn_memo);
        $business = isset($raw->business) ? $raw->business : (isset($raw->receiver_email) ? $raw->receiver_email : '0');
        if ($this->code_fundsource[$business]) {
            $ele->fundsource = $this->code_fundsource[$business];
        }
        if ( ! isset($raw->ipn_track_id) && (isset($raw->id) && strpos($raw->id, "WH-") === 0)) {
            $ele->fundsource = '';
        }
        $ele->parent_txn_id = isset($raw->parent_txn_id) ? $raw->parent_txn_id : '';
    }

    public function update_send($pn_txn_id, $pn_send, $pn_sn=NULL) {
        $sql = "
            UPDATE paypal_note
            SET    pn_send       = ?
            WHERE  pn_txn_id     = ?
        ";
        $sql .= ($pn_sn===NULL) ? "" : " and pn_sn=$pn_sn ";
        return $this->HT->query($sql, array($pn_send, $pn_txn_id));
    }

    public function update_pending_send($pn_txn_id, $pn_send) {
        $sql = "
            UPDATE paypal_note
            SET    pn_send       = ?
            WHERE  pn_txn_id     = ? AND pn_payment_status='pending'
        ";
        return $this->HT->query($sql, array($pn_send, $pn_txn_id));
    }

    //设置订单号
    public function set_invoice($pn_txn_id, $pn_invoice) {
        $sql = "
            UPDATE paypal_note
            SET    pn_invoice       = ?
            WHERE  pn_txn_id     = ?
        ";
        return $this->HT->query($sql, array($pn_invoice, $pn_txn_id));
    }

    public function date_range($from, $to, $currency=NULL, $pn_sn=NULL, $includeWH=true)
    {
        $this->init();
        $search_sql = " AND pn_payment_status in ('Completed','Refunded') ";
        $search_sql .= " AND pn.pn_datetime BETWEEN '$from 00:00:00' AND '$to 23:59:59' ";
        if ( ! empty($currency)) {
            $search_sql .= " AND pn_mc_currency = '$currency' ";
        }
        if ( ! empty($pn_sn)) {
            $search_sql .= " AND pn_sn >= $pn_sn ";
        }
        if (true !== $includeWH) {
            $search_sql .= " AND isnull(pn_payer,'')<>'' and ISNULL(pn_payer_email,'')<>'' ";
        }
        $this->search  = $search_sql;
        $this->orderby = " order by pn.pn_sn asc";
        $filter_list = [];
        $txn_list = [];
        $query_list = $this->get_list();
    	 foreach ($query_list as $key => $row) {
    		if (!in_array($row->pn_txn_id, $txn_list)) {
    			$txn_list[] = $row->pn_txn_id;
    			$filter_list[] = $row;
    		}
    	 }
        return $filter_list;
    }
    public function top_list($top, $currency=NULL, $pn_sn=NULL, $includeWH=true)
    {
        $this->init();
        $this->topnum = $top;
        $search_sql = " AND pn_payment_status in ('Completed','Refunded') ";
        if ( ! empty($currency)) {
            $search_sql .= " AND pn_mc_currency = '$currency' ";
        }
        if ( ! empty($pn_sn)) {
            $search_sql .= " AND pn_sn >= $pn_sn ";
        }
        if (true !== $includeWH) {
            $search_sql .= " AND isnull(pn_payer,'')<>'' and ISNULL(pn_payer_email,'')<>'' ";
        }
        $this->search  = $search_sql;
        $this->orderby = " order by pn.pn_sn asc";

        $filter_list = [];
        $txn_list = [];
        $query_list = $this->get_list();
    	 foreach ($query_list as $key => $row) {
    		if (!in_array($row->pn_txn_id, $txn_list)) {
    			$txn_list[] = $row->pn_txn_id;
    			$filter_list[] = $row;
    		}
    	 }
        return $filter_list;
    }


    /**
     * export note
     */
    public function export_record($db)
    {
        $this->info = $this->load->database('INFO', TRUE);
        $this->info->insert('Transaction_Export_Log', $db);
    }

    public function list_export_record($sn=0, $currency=null)
    {
        $this->info = $this->load->database('INFO', TRUE);
        $search_sql = $sn===0 ? "" : " AND TEL_SN=$sn ";
        $search_sql .= $currency===null ? "" : " AND TEL_transactionCurrency='" . $currency . "'";
        $sql = "SELECT TOP 20 *
                  FROM [InfoManager].[dbo].[Transaction_Export_Log]
                  WHERE 1=1
                  $search_sql
                  order by TEL_SN desc";
        return $this->info->query($sql)->result();
    }

}
