<?php
/**
 * Created by PhpStorm.
 * User: freuddebian
 * Date: 09/10/18
 * Time: 12:21
 */
require_once 'database/DataBaseConnector.php';
$params=$_POST["param"];
if(isset($params)){
    switch ($params){
        case "UpdateInformations":
            generateHyperVisor();
            break;
        case "listnetwork":
            listnetwork();
            break;
        case "insertnetwork":
            insertNetwork();
            break;
        case "listagentnetwork":
            listagentNetwork();
            break;
        case "listcountry":
            listcountry();
            break;
        case "listcodegenerer":
            listcode();
            break;
        case "listusers":
            listUsers();
            break;
        case "listoldnetworks":
            listOldNetwork();
            break;
        case "listnumero":
            listPhonenum();
            break;
        case "generateh":
            superCreator();
            break;
        case "readagent":
            readAgent();
            break;
        case "readsupervisornetwor":
            readSupervisorNetwork();
            break;
        case "deleteagentbynum":
            deleteAgent();
            break;

    }

}else{
    echo "no param";
}
function deleteAgent(){
    $con = mysqli_connect(DB_HOST, DB_USER
        , DB_PASSWORD, DB_DATABASE);
    $phone=$_POST["phone"];
    if(isset($phone)) {
        $deleted=[];
        $cod = mysqli_query($con, "SELECT ag.id as agentId,na.id as agentId2,cg.id as cgId  from agents ag INNER JOIN networks_agents na ON ag.id=na.agent_id INNER JOIN codeGenerer cg ON na.codegenerer_id=cg.id WHERE na.transactionNumber='$phone'");
        if ($cod) {
            while ($row = mysqli_fetch_array($cod, MYSQLI_ASSOC)) {
                $ag = $row['agentId'];
                $a = $row["agentId2"];
                $c = $row["cgId"];
                $deleted[]=$row;
                mysqli_query($con, "delete from agents WHERE id=$ag");
                mysqli_query($con, "delete from networks_agents WHERE id=$a");
                mysqli_query($con, "delete from codegenerer WHERE id=$c");
            }
        }else{
            $deleted["error"]=mysqli_error($con);
        }
        echo json_encode($deleted);

    }
}
function readSupervisorNetwork(){
    $phone=$_POST["code"];
    $isTest=$_POST["test"];
    $con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
    $cod=mysqli_query($con,"SELECT * from agents ag INNER JOIN networks_agents na ON ag.id=na.agent_id INNER JOIN  codeGenerer cg ON cg.id=na.codegenerer_id WHERE  cg.code_membre='$phone'");

    if($cod) {
        $me = mysqli_fetch_assoc($cod);
        $cod=mysqli_query($con,"SELECT * from agents ag INNER JOIN networks_agents na ON ag.id=na.agent_id INNER JOIN  codeGenerer cg ON cg.id=na.codegenerer_id WHERE  cg.code_parrain='$phone'");
        while($item=mysqli_fetch_assoc($cod)){
            $rows[]=$item;
        }

        echo json_encode(['agent'=>$me,'total'=>count($rows),'geo'=>$rows]);
    }else{
        echo mysqli_error($con);
    }
}
function readAgent(){
    $phone=$_POST["phone"];
    $con = mysqli_connect(DB_HOST, DB_USER
        , DB_PASSWORD, DB_DATABASE);
    $cod=mysqli_query($con,"SELECT * from agents ag INNER JOIN networks_agents na ON ag.id=na.agent_id INNER JOIN  codeGenerer cg ON cg.id=na.codegenerer_id WHERE na.transactionNumber='$phone' || na.phone='$phone'");
    if($cod) {
        while ($me = mysqli_fetch_assoc($cod)) {
            $rows[] = $me;
        }

        echo json_encode($rows);
    }else{
        echo mysqli_error($con);
    }
}
function superCreator(){
    $con = mysqli_connect(DB_HOST, DB_USER
        , DB_PASSWORD, DB_DATABASE);
    $cod=mysqli_query($con,"SELECT * from codeGenerer WHERE etat=0 AND category='hyper'");
    if($cod){
        $codes=[];
        $networks=[];
        $towns=[];
        $net=mysqli_query($con,"select * from networks WHERE country_id=78");
         while($row=mysqli_fetch_array($net, MYSQLI_ASSOC )) {
                $networks[] = $row;
            }
        $tow=mysqli_query($con,"select * from towns WHERE country_id=78");
        while($row=mysqli_fetch_array($tow, MYSQLI_ASSOC )) {
            $towns[] = $row;
        }
        $i=0;
        while($code=mysqli_fetch_array($cod, MYSQLI_ASSOC )) {
            if($i<count($networks)) {
                $network = $networks[$i];
                $town=$towns[0];
//The url you wish to send the POST request to
                $url = 'https://ilink-app.com/mobilebackend/interacted/MembersAction.php';
//The data you want to send via POST
                $fields = [
                    'tag'=>"member",
                    'type'=>'create_supervisor',
                    'address'      => "Libreville",
                    'lastname' => $network["name"],
                    'email'=>$network["name"].'@ilink-app.com',
                    'phone'=>"0100000$i",
                    'network'=>$network,
                    'phone_transaction'=>"0100000$i",
                    'town'=>$town,
                    'password'=>'1234',
                    'latitude'=>-1,
                    'lang'=>'fr',
                    'test'=>false,
                    'longitude'=>-1,
                    'member'=>$code['code_membre'],
                    'category'=>"hyper",
                ];
//url-ify the data for the POST
                $fields_string = json_encode($fields);
//open connection
                $ch = curl_init();
//set the url, number of POST vars, POST data
                curl_setopt($ch,CURLOPT_URL, $url);
                curl_setopt($ch,CURLOPT_POST, count($fields));
                curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//So that curl_exec returns the contents of the cURL; rather than echoing it
                curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
//execute post
                $result = curl_exec($ch);
                echo $result;
            }

            $i++;
        }
        echo json_encode($codes);
    }else {
        echo mysqli_error($con);
    }
};
function deleteRedon(){
    $con = mysqli_connect(DB_HOST, DB_USER
        , DB_PASSWORD, DB_DATABASE);
    $cod=mysqli_query($con,"SELECT ag.id as agentId,na.id as agentId2,cg.id as cgId  from agents ag INNER JOIN networks_agents na ON ag.id=na.agent_id INNER JOIN codeGenerer cg ON na.codegenerer_id=cg.id WHERE etat=0 AND ag.id=7984 AND ag.id=7987");
    if($cod){
        while ($row=mysqli_fetch_array($cod,MYSQLI_ASSOC)){
           $ag= $row['agentId'];
           $a =$row["agentId2"];
           $c=$row["cgId"];
            mysqli_query($con,"delete from agents WHERE id=$ag");
            mysqli_query($con,"delete from networks_agents WHERE id=$a");
            mysqli_query($con,"delete from codegenerer WHERE id=$c");

        }
    }
}
function listPhonenum(){
    try {
        $con = mysqli_connect(DB_HOST, DB_USER
            , DB_PASSWORD, DB_DATABASE);
        if($con){
            $net=mysqli_query($con,"select * from networks");
            if($net){
                while($row=mysqli_fetch_array($net, MYSQLI_ASSOC )) {

                    $rows[] = $row;

                }
                echo json_encode($rows);
            }else{
                echo json_encode(mysqli_error($con));
            }
        }else{
            var_dump(mysqli_connect_error());
        }

    }catch (Exception $e){
        echo 'error';
        echo $e->getMessage();
    }
}
function listOldNetwork(){
    $con = mysqli_connect(DB_HOST, DB_USER
        , DB_PASSWORD, "ilink");
    if($con){
        $net=mysqli_query($con,"select * from network WHERE reseau='KENYA'");
        if($net){
            $rows=[];
            while ($row=mysqli_fetch_array($net,MYSQLI_ASSOC)){

                $filt=[];
                foreach($row as $key => $value) {
                   if(strlen($value)>0){
                       $filt[$key]=$value;
                   }
                }
                $rows[]=$filt;
            }
            $connexion = mysqli_connect(DB_HOST, DB_USER
                , DB_PASSWORD, DB_DATABASE);
            if($connexion) {
                foreach ($rows as $row) {
                    foreach ($row as $key=>$value)
                        if(strtoupper($key)!='RESEAU')
                            mysqli_query($connexion,"INSERT INTO networks(country_id,name) VALUES('114','$value')");
                }
            }
            listnetwork();
        }else{
            echo json_encode(mysqli_error($con));
        }
    }else{
        var_dump(mysqli_connect_error());
    }
}
function listUsers(){
    $con = mysqli_connect(DB_HOST, DB_USER
        , DB_PASSWORD, DB_DATABASE);
    if($con){
        $net=mysqli_query($con,"select * from users");
        if($net){
            $rows=[];
            while ($row=mysqli_fetch_array($net,MYSQLI_ASSOC)){
                $rows[]=$row;
            }

            echo json_encode($rows);
        }else{
            echo json_encode(mysqli_error($con));
        }
    }else{
        var_dump(mysqli_connect_error());
    }
}
function listagentNetwork(){
    try {
        $con = mysqli_connect(DB_HOST, DB_USER
            , DB_PASSWORD, DB_DATABASE);
        if($con){
            $net=mysqli_query($con,"select * from networks_agents na INNER JOIN codeGenerer cg ON na.codeGenerer_id=cg.id");
            if($net){
                while ($row=mysqli_fetch_array($net,MYSQLI_ASSOC)){
                    $rows[]=$row;
                }

                echo json_encode($rows);
            }else{
                echo json_encode(mysqli_error($con));
            }
        }else{
            var_dump(mysqli_connect_error());
        }

    }catch (Exception $e){
        echo 'error';
        echo $e->getMessage();
    }
}
function insertNetwork(){
    $country=$_POST['country'];
    $name=$_POST['network'];
    try {
        $con = mysqli_connect(DB_HOST, DB_USER
            , DB_PASSWORD, DB_DATABASE);
        if($con){
            $net=mysqli_query($con,"INSERT INTO networks(country_id,name) VALUES('$country','$name')");
            if($net){
                echo json_encode('success');
            }else{
                echo json_encode(mysqli_error($con));
            }
        }else{
            var_dump(mysqli_connect_error());
        }

    }catch (Exception $e){
        echo 'error';
        echo $e->getMessage();
    }

}
function listcountry(){
    try {
        $con = mysqli_connect(DB_HOST, DB_USER
            , DB_PASSWORD, DB_DATABASE);
        if($con){
            $net=mysqli_query($con,"select * from countries");
            if($net){
                echo json_encode(mysqli_fetch_all($net));
            }else{
                echo json_encode(mysqli_error($con));
            }
        }else{
            var_dump(mysqli_connect_error());
        }

    }catch (Exception $e){
        echo 'error';
        echo $e->getMessage();
    }

}
function listcode(){
    try {
        $con = mysqli_connect(DB_HOST, DB_USER
            , DB_PASSWORD, DB_DATABASE);
        if($con){
            $net=mysqli_query($con,"select * from codeGenerer");
            if($net){
                while($row=mysqli_fetch_array($net,MYSQLI_ASSOC)){
                    $rows[]=$row;
                }
                echo json_encode($rows);
            }else{
                echo json_encode(mysqli_error($con));
            }
        }else{
            var_dump(mysqli_connect_error());
        }

    }catch (Exception $e){
        echo 'error';
        echo $e->getMessage();
    }

}
function listnetwork(){
        try {
            $con = mysqli_connect(DB_HOST, DB_USER
                , DB_PASSWORD, DB_DATABASE);
            if($con){
                $net=mysqli_query($con,"select * from networks WHERE country_id=78");
                if($net){
                    while($row=mysqli_fetch_array($net, MYSQLI_ASSOC )) {

                        $rows[] = $row;

                    }
                    echo json_encode($rows);
                }else{
                    echo json_encode(mysqli_error($con));
                }
            }else{
                var_dump(mysqli_connect_error());
            }

        }catch (Exception $e){
            echo 'error';
            echo $e->getMessage();
        }
    };
function generateHyperVisor(){
   $random= generateRandomString();
    $con = mysqli_connect(DB_HOST, DB_USER
        , DB_PASSWORD, DB_DATABASE);
    $insert=mysqli_query($con,"insert INTO codeGenerer (code_parrain,code_membre,category) VALUES ('$random','$random','hyper')");
    if($insert){
        var_dump($insert);
    }else {
        echo mysqli_error($con);
    }
}
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}