<?php
/**
 * Created by PhpStorm.
 * User: Kavand
 * Date: 3/6/2019
 * Time: 1:36 AM
 */
// header('Access-Control-Allow-Origin: http://gokashan.ir');
// header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
// header('Access-Control-Max-Age: 1000');
// header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');


if (isset($_SERVER['HTTP_ORIGIN'])) {
    // should do a check here to match $_SERVER['HTTP_ORIGIN'] to a
    // whitelist of safe domains
    if ($_SERVER['HTTP_ORIGIN'] === 'http://kashantc.ir' Or $_SERVER['HTTP_ORIGIN'] === 'http://gokashan.ir') {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 120');    // cache for 2 min
    }
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

}





$User = array("User" => "romouzi", "Pass" => "zmr_13111363rmz", 'GroupCode' => 3131);
if (!isset($request)) {
    define("HOME", '../resource/php/page/');
    define("FUNCTION_SYSTEM", '../resource/php/function/');
    require_once '../../../../core/DAL/DAL.php';
    require_once '../../../../core/DAL/DAL2.php';
    require_once '../../../../core/WebServiceSystem.php';
    require_once '../../../../core/DAL/public-function.php';
    require_once '../../../../core/DAL/sms/SendMessage.php';

    $request = $_REQUEST;
    $DLA = $DAL = new DAL("constant.php");
    $WS = new WebServiceSystem();
}
$data = $request['object'];
switch ($request['data-header']) {
    case 'NoCodeCustomerServiceNafisKashanTC':
        //profile
        $select = $DLA->Select("SELECT `ID` FROM `app_acceptor_profile` WHERE `pNC`='{$data['NationalCode']}' AND `pNumber` IN ('0{$data['Mobile']}', '{$data['Mobile']}')");
        if (!$select) {
            $mobile = (strlen($data['Mobile']) === 11 ? $data['Mobile'] : '0' . $data['Mobile']);
            $ID = $DLA->DoCommandID("INSERT INTO `app_acceptor_profile` (fName, lName, pNumber, pNC) VALUE ('{$data['FirstName']}', '{$data['LastName']}', '{$mobile}', '{$data['NationalCode']}')");
        } else $ID = $select[0]['ID'];
        // addd

        $data['CardPan'] = str_replace(' ', '', $data['CardPan']);
        $data['CardPan'] = str_replace('-', '', $data['CardPan']);
        if (strlen($data['CardPan']) == 16 and is_numeric($data['CardPan'])) {
            $DLA->DoCommand("INSERT INTO `app_client_credit_card` (card_number, client_id, reg_from) VALUE ('{$data['CardPan']}','{$ID}','{$data['RegFrom']}')");
            echo $WS->BusApi()->json('NoCodeCustomerServiceNafis', array_merge($User, GetParam($data)));
        } else {
            echo json_encode(array(array("error" => 1, "message" => "اطلاعات به درستی وارد نشده است.")), JSON_UNESCAPED_UNICODE);
        }
        break;
    case "NoCodeCustomerServiceNafis-json":
        $payload = base64_decode(str_pad(strtr($request['json'], '-_', '+/'), strlen($request['json']) % 4, '=', STR_PAD_RIGHT));
        $payload = json_decode($payload, true);
        $data = $payload['object'];
    case "NoCodeCustomerServiceNafis-app":
        if (isset($data) && is_numeric($data['RegFrom']) && !is_null($data['RegFrom'])) {
            foreach ($data as $key => $value) $data [$key] = convert($value, true);
            $select = $DLA->Select("SELECT `ID` FROM `app_acceptor_profile` WHERE `pNC`='{$data['NationalCode']}' AND `pNumber` IN ('0{$data['Mobile']}', '{$data['Mobile']}')");
            if (!$select) {
                $mobile = (strlen($data['Mobile']) === 11 ? $data['Mobile'] : '0' . $data['Mobile']);
                $ID = $DLA->DoCommandID("INSERT INTO `app_acceptor_profile` (fName, lName, pNumber, pNC) VALUE ('{$data['FirstName']}', '{$data['LastName']}', '{$mobile}', '{$data['NationalCode']}')");
            } else $ID = $select[0]['ID'];

            $data['CardPan'] = str_replace(' ', '', $data['CardPan']);
            $data['CardPan'] = str_replace('-', '', $data['CardPan']);
            if (strlen($data['CardPan']) == 16 and is_numeric($data['CardPan'])) {
                $DLA->DoCommand("INSERT INTO `app_client_credit_card` (card_number, client_id, reg_from) VALUE ('{$data['CardPan']}','{$ID}','{$data['RegFrom']}')");
                echo $WS->BusApi()->json(str_replace('-app', '', str_replace('-json', '', $request['data-header'])), array_merge($User, GetParam($data)));
            } else {
                echo json_encode(array(array("error" => 1, "message" => "اطلاعات به درستی وارد نشده است.")), JSON_UNESCAPED_UNICODE);
            }
        } else {
            echo '[]';
        }
        break;
    case 'TransReportNafis-json':
        $payload = base64_decode(str_pad(strtr($request['json'], '-_', '+/'), strlen($request['json']) % 4, '=', STR_PAD_RIGHT));
        $payload = json_decode($payload, true);
        $data = $payload['object'];
    case 'TransReportNafis':
//        echo $WS->BusApi()->json($request['data-header'], array_merge($User, GetParam($data)));
        echo $WS->BusApi()->json(str_replace('-app', '', str_replace('-json', '', $request['data-header'])), array_merge($User, GetParam($data)));
        break;
    case 'BonServiceNafis':
        echo $WS->BusApi()->json($request['data-header'], array_merge($User, GetParam($data)));
        break;
    case 'CustBonServiceNafis':
        echo $WS->BusApi()->json($request['data-header'], array_merge($User, GetParam($data)));
        break;
    case 'RefNoServiceNafis':
        echo $WS->BusApi()->json($request['data-header'], array_merge($User, GetParam($data)));
        break;
//    case "NoCodeCustomerServiceNafis":
//        $select = $DLA->Select("SELECT `RegFrom`, `BankCardNumber` FROM `app_client_register` WHERE (`Mobile`='0" . $data['Mobile'] . "')");
//        if ($select) {
//            $select = $select[0];
//            if (is_numeric($select['RegFrom']) && !is_null($select['RegFrom']) && ($select['RegFrom'] === $data['RegFrom'] OR $data['RegFrom'] == -10)) {
//                $data['CardPan'] = str_replace(' ', '', $data['CardPan']);
//                $data['CardPan'] = str_replace('-', '', $data['CardPan']);
//                if (strlen($data['CardPan']) == 16 and is_numeric($data['CardPan'])) {
//                    ($DLA->DoCommand("UPDATE `app_client_register` SET `BankCardNumber`='{$data['CardPan']}'"));
//                    echo $WS->BusApi()->json($request['data-header'], array_merge($User, GetParam($data)));
//                } else {
//                    echo json_encode(array(array("error" => 1, "message" => "اطلاعات به درستی وارد نشده است.")), JSON_UNESCAPED_UNICODE);
//                }
//            } else {
//                echo json_encode(array(array("error" => 1, "message" => "این کاربرد توسط فرد دیگری در سیستم ثبت شده است.")), JSON_UNESCAPED_UNICODE);
//            }
//        } else {
//            $DLA->DoCommand("INSERT INTO `app_client_register` (`FirstName`, `LastName`, `NationalCode`, `NationalSecurityCode`, `BankCardNumber`, `Mobile`, `Mode`, `RegFrom`, `ATime`) VALUES ('{$request["FirstName"]}','{$request["LastName"]}','{$request["NationalCode"]}','{$request["bnCode"]}','{$request["CardPan"]}','{$request["Mobile"]}','1','{$request["RegFrom"]}',CURRENT_TIMESTAMP)");
//            echo $WS->BusApi()->json($request['data-header'], array_merge($User, GetParam($data)));
//        }
//        break;
//    /*add from application*/

//    case 'MobileCustomerService':
//        $input_log = json_encode($_REQUEST, JSON_UNESCAPED_UNICODE);
//        $result_log = null;
//        $visitor = $DLA->Select("SELECT `FirstName` as `FN`, `LastName` as `LN` FROM `app_client_register` WHERE  `ID`='{$data['RegFrom']}'");
//        if ($visitor) {
//            $visitor = $visitor[0];
//            $ID = $DLA->DoCommandID("INSERT INTO `app_visitor_log` (`visitor_id`, `input_add_log`, `v_first_name`, `v_last_name`) VALUES ('{$data['RegFrom']}','{$input_log}','{$visitor['FN']}','{$visitor['LN']}')");
//
//            $out = $WS->BusApi()->json($request['data-header'], array_merge($User, GetParam($data)));
//
//            $DLA->DoCommand("UPDATE `app_visitor_log` SET `output_add_log`='{$out}' WHERE `ID`='{$ID}'");
//
//            $out = json_decode($out, true);
//
//            if (count($out) == 1) {
//                $out = $out[0];
//                if ($out['error'] === 'no error') {
//                    $result_log = json_encode(array(array("error" => 0, "message" => $out['response'])), JSON_UNESCAPED_UNICODE);
//                    $result_log = json_encode(array(array("error" => 0, "message" => $out['response'])), JSON_UNESCAPED_UNICODE);
//                    $Text = "\n" . "شما در شبکه تخفیفی نفیس عضو شدید" . "\n";
//                    $Text .= 'جهت اطلاعات بیشتر:' . "\n";
//                    $Text .= 'Http://t.me/nafiskashancart_bot';
//                    $SMS->SendOneMessage("0" . $data['Mobile'], $Text);
//                } else {
//                    $result_log = json_encode(array(array("error" => 1, "message" => $out['error'])), JSON_UNESCAPED_UNICODE);
//                }
//            } else {
//                $result_log = json_encode(array(array("error" => 1, "message" => "نتیجه ای دریافت نشد.")), JSON_UNESCAPED_UNICODE);
//            }
//        } else {
//            $result_log = json_encode(array(array("error" => 1, "message" => "مشخصات کاربری یافت نشد.")), JSON_UNESCAPED_UNICODE);
//        }
//        $DLA->DoCommand("UPDATE `app_visitor_log` SET `result_add_log`='{$result_log}', `EndDate`=current_timestamp WHERE `ID`='{$ID}'");
//        echo $result_log;
//        break;
//    case
//    'agent-report':
//        //code visitor
//        $array = array();
//        $index = 0;
//        $select = $DAL->Select("SELECT `ID`,concat(`FirstName`, ' ', `LastName`) as `full-name` FROM `app_client_register` WHERE (`Mode`='2')");
//        if ($select) {
//            foreach ($select as $record) {
//                $acceptor = $DAL->Select("SELECT `IsActive`, concat(`fName`, ' ', `lName`) as `full-name` FROM `app_acceptor_list` WHERE `visitor_id`='{$record['ID']}'");
//                $client = $DAL->Select("Select concat(`FirstName`, ' ', `LastName`) as `full-name` FROM `app_client_register` WHERE `RegFrom`='{$record['ID']}'");
//
//                $ch = '';
//                if ($client) {
//                    $ch = '<div class="">';
//                    $ch .= '    <div class="btn-group-vertical full_width" role="group" aria-label="Vertical button group">';
//                    $ch .= '        <button type="button" class="btn bg-pink waves-effect">';
//                    $ch .= '            <span class="material-icons">assignment_ind</span>';
//                    $ch .= '            <br>';
//                    $ch .= '            <span>' . count($client) . '</span>';
//                    $ch .= '        </button>';
//                    $ch .= '        <button class="btn bg-cyan waves-effect m-b-15" type="button" data-toggle="collapse" data-target="#collapse-c-' . $record['ID'] . '" aria-expanded="false" aria-controls="collapse-c-' . $record['ID'] . '">ریز ثبت</button>';
//                    $ch .= '        <div class="collapse" id="collapse-c-' . $record['ID'] . '">';
//                    $ch .= '            <div class="well">';
//                    foreach ($client as $c) {
//                        $ch .= '<div class="btn table-bordered">' . $c['full-name'] . '</div>';
//                    }
//                    $ch .= '            </div>';
//                    $ch .= '        </div>';
//                    $ch .= '    </div>';
//                    $ch .= '</div>';
//                } else {
//                    $ch = '<div class="btn table-bordered">ندارد</div>';
//                }
//
//                $ah = '';
//                if ($acceptor) {
//                    $ah = '<div class="">';
//                    $ah .= '    <div class="btn-group-vertical full_width" role="group" aria-label="Vertical button group">';
//                    $ah .= '        <button type="button" class="btn btn-block bg-pink waves-effect">';
//                    $ah .= '            <span class="material-icons">store</span>';
//                    $ah .= '            <br>';
//                    $ah .= '            <span>' . count($acceptor) . '</span>';
//                    $ah .= '        </button>';
//                    $ah .= '        <button class="btn bg-cyan btn-block waves-effect m-b-15" type="button" data-toggle="collapse" data-target="#collapse-a-' . $record['ID'] . '" aria-expanded="false" aria-controls="collapse-a-' . $record['ID'] . '">ریز ثبت</button>';
//                    $ah .= '        <div class="collapse" id="collapse-a-' . $record['ID'] . '">';
//                    $ah .= '            <div class="well">';
//                    foreach ($acceptor as $a) {
//                        $ah .= '<div class="btn table-bordered ' . ($a['IsActive'] === '1' ? 'text-success' : 'text-danger') . ' ">' . $a['full-name'] . '</div>';
//                    }
//                    $ah .= '            </div>';
//                    $ah .= '        </div>';
//                    $ah .= '    </div>';
//                    $ah .= '</div>';
//                } else {
//                    $ah = '<div class="btn table-bordered">ندارد</div>';
//                }
//                $array[] = array(
//                    'index' => (++$index),
//                    'ID' => $record['ID'],
//                    'full-name' => $record['full-name'],
//                    'client' => $ch,
//                    'acceptor' => $ah
//                );
//            }
//        }
//        echo json_encode($array, JSON_UNESCAPED_UNICODE);
//        break;
    default:
        echo "[]";
        break;

}