<?php 

// Include main file
include_once('../libs/main.php');
// Check admin Login
include_once('checkLogin.php');
// Logical section of page
$redeemedObj =  new  redeemed();


// $adminlogObj = new admin_log();
// $modulepagesObj = new module_pages();

// $filename=basename($_SERVER['SCRIPT_FILENAME']);
// if($filename == 'redeemedadd.php')
// {
//     $module_id = $adminlogObj->getModuleId($filename);
//     $page_id = $adminlogObj->getPageId($filename);
//     $allpages = $modulepagesObj->fromId($page_id);
//     $pagename = $allpages->page;

// }

if(isset($_REQUEST['act']) && $_REQUEST['act']=='send_form' && isset($_REQUEST['redeemed_id'])){
    $redeemedDetail  = $redeemedObj->fromId($_REQUEST['redeemed_id']);
    $dependantObj = new dependant();
    $dependantDetails =$dependantObj->fromId($redeemedDetail->dependant_id);
    $tokenResponse =w::fetchTangoToken();

    $tokenResponse =json_decode($tokenResponse,1);
    if(isset($tokenResponse['access_token'])){
      $access_token=$tokenResponse['access_token'];
      
        $curl = curl_init();
        curl_setopt_array($curl, array(
          CURLOPT_URL => 'https://integration-api.tangocard.com/raas/v2/accounts',
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'GET',
          CURLOPT_HTTPHEADER => array(
            'Authorization: Bearer '.$access_token
          ),
        ));

        $allAccounts = curl_exec($curl);
        $allAccounts =json_decode($allAccounts,1);
        
        curl_close($curl);
        
        $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => 'https://integration-api.tangocard.com/raas/v2/emailTemplates',
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'GET',
          CURLOPT_HTTPHEADER => array(
            'Authorization: Bearer '.$access_token
          ),
        ));

        $allETemplates = curl_exec($curl);
        $allETemplates = json_decode($allETemplates,1);
        $allETemplates = $allETemplates['emailTemplates'];
        curl_close($curl);
        
    }
}

if(isset($_REQUEST['act']) && $_REQUEST['act']=='send_order' && isset($_REQUEST['account_id']) && $_REQUEST['account_id'] != "" && $_REQUEST['template_id'] != "" && $_REQUEST['hdnId'] != ""){
    $redeemedDetail  = $redeemedObj->fromId($_REQUEST['hdnId']);
    $dependantObj = new dependant();
    $dependantDetails =$dependantObj->fromId($redeemedDetail->dependant_id);
    if($dependantDetails->dependant_member_email=="" || is_null($dependantDetails->dependant_member_email)){
        echo json_encode(array('error'=>true,'msg'=>'User membership email is blank.'));
        exit;
    }
    $tokenResponse =w::fetchTangoToken();

    $tokenResponse =json_decode($tokenResponse,1);
    if(isset($tokenResponse['access_token'])){
        $access_token=$tokenResponse['access_token'];
        $customerIdentifier="";
        if($dependantDetails->dependant_tangoId!=""){
            $customerIdentifier  = $dependantDetails->dependant_tangoId;
        }else{
            $displayName =w::d($dependantDetails->dependant_fname)." ".w::d($dependantDetails->dependant_lname);
            $curl = curl_init();
            $postFields =array(
                "customerIdentifier"=>w::getReferenceUniqueId(15),
                "displayName"=>$displayName."(".$dependantDetails->dependant_member_id.")"
            );
            curl_setopt_array($curl, array(
              CURLOPT_URL => 'https://integration-api.tangocard.com/raas/v2/customers',
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => '',
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 0,
              CURLOPT_FOLLOWLOCATION => true,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => 'POST',
              CURLOPT_POSTFIELDS =>json_encode($postFields),
              CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Authorization: Bearer '.$access_token
              ),
            ));

            $response = curl_exec($curl);
            $response =json_decode($response,1);
            
            if(isset($response['customerIdentifier']) && $response['customerIdentifier']!=""){
                $dependantData =array(
                    "dependant_tangoId"=>$response['customerIdentifier']
                );
                $dependantObj->updateRecords($dependantData,$dependantDetails->dependant_id);
                $customerIdentifier =$dependantDetails->dependant_id;
            }
            curl_close($curl);
        }
        if($customerIdentifier!=""){
            $qty =$redeemedDetail->quantity;
            for ($i=1; $i<=intval($qty); $i++) { 
                $curl = curl_init();

                curl_setopt_array($curl, [
                  CURLOPT_URL => "https://integration-api.tangocard.com/raas/v2/orders",
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_ENCODING => "",
                  CURLOPT_MAXREDIRS => 10,
                  CURLOPT_TIMEOUT => 30,
                  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                  CURLOPT_CUSTOMREQUEST => "POST",
                  CURLOPT_POSTFIELDS => json_encode([
                    'sender' => [
                        'firstName' => $_SESSION['admin_fname'],
                        'lastName' => $_SESSION['admin_lname'],
                        'email' => $_SESSION['admin_email_address']
                    ],
                    'recipient' => [
                        'firstName' => w::d($dependantDetails->dependant_fname),
                        'lastName' => w::d($dependantDetails->dependant_lname),
                        'email' => w::d($dependantDetails->dependant_email_address)
                    ],
                    'sendEmail' => true,
                    'externalRefID' => $redeemedDetail->externalRefID."_".$i,
                    'customerIdentifier' => $customerIdentifier,
                    'accountIdentifier' => $_REQUEST['account_id'],
                    'utid' => $redeemedDetail->utid,
                    'amount' => $redeemedDetail->faceValue,
                    'etid' => $_REQUEST['template_id'],
                    'purchaseOrderNumber' => w::getReferenceId(12,3)
                  ]),
                  CURLOPT_HTTPHEADER => [
                    "accept: application/json",
                    "content-type: application/json",
                    'Authorization: Bearer '.$access_token
                  ],
                ]);

                $response = curl_exec($curl);
                $response =json_decode($response,1);
                curl_close($curl);
                if(!isset($response['errors'])){
                    $tango_orderObj = new tango_order();
                    $tango_orderData =array(
                        "referenceOrderID"=>$response['referenceOrderID'],
                        "externalRefID"=>$response['externalRefID'],
                        "redeemed_id"=>$_REQUEST['hdnId'],
                        "amount"=>$response['denomination']['value'],
                        "purchaseOrderNumber"=>$response['purchaseOrderNumber'],
                        "status"=>$response['status'],
                        "response"=>json_encode($response),
                        "created_at"=>date("Y-m-d H:i:s")
                    );
                    $rs =$tango_orderObj->addRecords($tango_orderData);
                }else{
                    echo json_encode(array('error'=>true,'msg'=>$response['errors']));
                    exit;    
                }        
            }
            if($rs){
                $redeemedData =array(
                    "status"=>$response['status'],
                    "delivered_by"=>$_SESSION['admin_id'],
                    "delivered_at"=>date("Y-m-d H:i:s")
                );
                $redeemedObj->updateRecords($redeemedData,$_REQUEST['hdnId']);
                $loyalty_actionObj = new loyalty_action();
                $loyalty_actionData =array(
                    "loyalty_action_action"=>"Delivered"
                );
                $loyalty_actionObj->updateRecords($loyalty_actionData,$redeemedDetail->action_id);
                echo json_encode(array('error'=>false,'msg'=>'Success.'));
                exit;        
            }else{
                echo json_encode(array('error'=>true,'msg'=>'Facing some error,Please verify on tango portal before submit same order.'));
                exit;        
            }
        }else{
            echo json_encode(array('error'=>true,'msg'=>'Customer creation error.'));
            exit;
        }
    }else{
        echo json_encode(array('error'=>true,'msg'=>'Tango Token error.'));
        exit;
    }
}

// Include Template 
include_once('../libs/routs.php')

?>