<?php
/**
 * User: Khalid.Alaraj
 * Date: 9-August-2016
 * Time: 2:36 PM
 */
session_start();
define('SERV_ID',2);
define('INTRO_NO','056');

require '../../../helpers/helpers.php';
require '../../../classes/conn.php';
$messages = require '../../../config/messages.php';
unset($_SESSION['Error']);
$db = new DBConnection();

if(!isset($_SESSION['service_id']) || !isset($_SESSION['api_key'])){
    $attributes =array('service_id','api_key');
    $constraints = array('where id ='.SERV_ID);
    $result = $db->select('service',$attributes,$constraints,true);
    $_SESSION['service_id'] = isset($result[0]['service_id']) ? $result[0]['service_id'] : null;
    $_SESSION['api_key'] = isset($result[0]['api_key']) ? $result[0]['api_key'] : null;
}
$PlatForm = null;
if(!empty($_SESSION['PF'])){
    $PlatForm = '?pf=d';
}

if(isset($_POST['mobile'])){
    $validate = validate_number($_POST['mobile']);
    if($validate['status'] == 'Success'){
        $_SESSION['mobile_number'] = INTRO_NO.$_POST['mobile'];
        $check_subscribe = check_for_subscribe($_SESSION['mobile_number'],SERV_ID);
        if($check_subscribe['status'] == 'Error'){
            $_SESSION['Error'] = $check_subscribe['msg'];
            header('location: index.php'.$PlatForm);exit;
        }

        $attributes = array(
            'number'=>$_SESSION['mobile_number'],
            'verification_code'=> generate_code(),
            'service_id'=> SERV_ID,
            'ip_address'=> get_client_ip(),
            'status'=> 'Pending'
        );
        if($db->insert('number',$attributes)){
            $msg = 'Activation Code: '.$attributes['verification_code'];
            if(send_sms($_SESSION['mobile_number'] ,$msg)){
                $_SESSION['verify_code'] = $attributes['verification_code'];
                insert_log('Sent sms verify code successfully');
                header('location: verify.php');
            }
        }
    }else{
        $_SESSION['Error'] = $validate['msg'];
        header('location: index.php'.$PlatForm);
    }

}elseif(isset($_POST['verify_code'])){

    if($_SESSION['verify_code'] == $_POST['verify_code']){
        insert_log('Entered valid code');
        $attributes = array(
            "ip_address" => get_client_ip(),
            "status" => 'Verified',
            "verify_date" => date('Y-m-d H:m:s')
        );
        $constraints = array(
            "number = ".$_SESSION['mobile_number'],
            "verification_code = '". $_SESSION['verify_code']."'",
            "service_id = ".SERV_ID
        );

        if(subscribe_service($_SESSION['mobile_number'])){
            //$msg = $messages['success_activate'];
            if($db->update('number',$attributes,$constraints)){
                insert_log('Success Subscribe');
                insert_log('sent success subscribe sms');
                /*if(send_sms($_SESSION['mobile_number'] ,$msg)){
                    insert_log('sent success subscribe sms');
                }*/
                unset($_SESSION['service_id']);
                unset($_SESSION['mobile_number']);
                unset($_SESSION['api_key']);
                header('location: done.php');
            }

        }else{
            insert_log('unable to subscribe ...');
            $_SESSION['Error'] = $messages['unable_to_subscribe'];
            header('location: verify.php');
        }
    }else{
        insert_log('Entered invalid code');
        $_SESSION['Error'] = $messages['invalid_code'];
        header('location: verify.php');
    }

}else{
    if(isset($_GET['resend'])){
        unset($_SESSION['mobile_number']);
    }
    header('location: index.php'.$PlatForm);
}


function validate_number($number){
    global $messages;
    $validate = array();
    if(empty($number)){
        $validate['msg'] = $messages['enter_number'];
    }elseif (strlen($_POST['mobile']) != 7){
        $validate['msg'] = $messages['wrong_number'];

    }

    if(!empty($validate)){
        $validate['status'] = 'Error';
    }else{
        $validate['status'] = 'Success';
    }

    return $validate;
}

/*function subscribe_service($mobile_number){
    require_once('./lib/soap/nusoap.php');
    $proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
    $proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
    $proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
    $proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
    $client = new nusoap_client('http://217.21.1.82:6363/SubscriptionService.asmx?wsdl', 'wsdl',
        $proxyhost, $proxyport, $proxyusername, $proxypassword);
    $client->soap_defencoding = 'UTF-8';
    $err = $client->getError();
    $client->decode_utf8 = false;
    $api_key = 'aBKF6L9Ili8Az24y0gdW0Ez8119005a80vn7Kx2F567x7h2h0tM9nw7vN6V';
    $param = array('apikey'=>$api_key,'sid' => 100100,'msisdn'=>$mobile_number);

    $result = $client->call('SubToService', array('parameters' => $param), '', '', false, true);
    //Check for a fault
    //print_r($result);exit;
    if ($client->fault) {
//        echo '<h2>Fault</h2><pre>';
//        print_r($result);
//        echo '</pre>';
    } else {
        // Check for errors
        $err = $client->getError();
        if ($err) {
            // Display the error
            //	echo '<h2>Error</h2><pre>' . $err . '</pre>';
        } else {
            // Display the result
            //	echo '<h2>Result</h2><pre>';
            //	print_r($result);
            //	echo '</pre>';
        }
    }


}*/
function subscribe_service($mobile_number){
    $api_key = $_SESSION['api_key'];
    $service_id = $_SESSION['service_id'];
    $mobile__no = substr($mobile_number , 1 , 10);
    $doc = new DOMDocument;
    $status = file_get_contents("http://217.21.1.82:6363/SubscriptionService.asmx/SubToService?apikey=$api_key&sid=$service_id&msisdn=$mobile__no") or die("Cant Connect To subscribe server ");
    $doc->loadXML($status);

    $string = $doc->getElementsByTagName('string');
    $value = $string->item(0)->textContent;
    if($value == '-1' || $value == '0'){
        return true;
    }
    return false;
}

function insert_log($status){
    $attributes = array(
        'number'=> $_SESSION['mobile_number'],
        'inserted_code'=> isset($_POST['verify_code']) ? $_POST['verify_code'] : null,
        'status'=> $status

    );
    $db = new DBConnection();
    $db->insert('log',$attributes);
}

function check_for_subscribe($mobile_number,$service_id){
    global $messages;
    $validate = array();
    $db = new DBConnection();
    $attributes = array('number','service_id','status');
    $constraints = array("where",
        " number = $mobile_number",
        " and service_id = $service_id"
    );
    $result = $db->select('number',$attributes,$constraints,true);
    // set the resulting array to associative
    if(!empty($result)){
        if($result[0]['status'] == 'verified'){
            $validate['msg'] = $messages['duplicate_subscribe'];
        }
    }
    if(!empty($validate)){
        $validate['status'] = 'Error';
    }else{
        $validate['status'] = 'Success';
    }
    return $validate;

}