<?php
   
    //error_reporting(-1);
    //ini_set('display_errors', 'On');
    
    include_once '../account/session.php';
    include_once '../../scripts/bd.php';
    
   
    
    
   if(isset($_GET['action']))
    {
        $action=$_GET['action'];
        if($action=='show')show();
        if($action=='get_sponsors')get_sponsors();
        if($action=='get_servers')get_servers();
        if($action=='get_offers')get_offers();
        if($action=='get_image')get_image();
        if($action=='delete_image')delete_image();
   }
   
    function add($filename,$p_ip_main_server,$id_server)
    {
        include('../../scripts/bdd.php');
        $id_sponsor  =   $_POST["sponsor"];
        $id_offer    =   $_POST["offer"];
        $id_mailer   =   $_SESSION['id-mailer'];
        $link        =   'http://'.$p_ip_main_server.'/app/image/'.$filename;
        $date_upload =   date('Y-m-d h:i:s');
       
        $sqlInsertCreative  =   
        '
            INSERT INTO image(id_server,id_sponsor,id_offer,link,date_upload) VALUES (?,?,?,?,?);
        ';
        $cmdInsertCreative  =   $bdd->prepare($sqlInsertCreative);
        $rep                =   $cmdInsertCreative->execute(array($id_server, $id_sponsor, $id_offer, $link, $date_upload));
        
        if($rep)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
   
   function show(){ 
      $list=array();
      
      $id_server=$_GET["id_server"];
      $id_sponsor=$_GET["id_sponsor"];
      $id_offer=$_GET["id_offer"];
      $id_mailer=$_SESSION['id-mailer'];
      
      $request="SELECT id,link FROM image WHERE id_server = '".$id_server."'";
      
      if($id_server!='0'){
          $request.=" && id_server='$id_server'";
      }
      
      if($id_sponsor!='0'){
          $request.=" && id_sponsor='$id_sponsor'";
      }
      
      if($id_offer!='0'){
          $request.=" && id_offer='$id_offer'";
      }
      $data= bd::query($request);
      
      while ($row = mysql_fetch_object($data)) {
          $list[]=$row;
      }
      echo json_encode($list);
   }
   
   function get_servers(){
      $data=array();
      $query = bd::query("SELECT id,name FROM server WHERE active='1'");
      while ($row = mysql_fetch_object($query)) {
          $data[]=$row;
      }
      echo json_encode($data);
   }
   
   function get_sponsors(){
      $data=array();
      $query = bd::query("SELECT id,name FROM sponsor WHERE active='1'");
      while ($row = mysql_fetch_object($query)) {
          $data[]=$row;
      }
      echo json_encode($data);
   }
   
   function get_offers(){
      $data=array();
      $query = bd::query("SELECT id,name FROM offer WHERE id_sponsor='{$_GET["sponsor"]}' &&  active='1'");
      while ($row = mysql_fetch_object($query)) {
          $data[]=$row;
      }
      echo json_encode($data);
   }
   
   function get_server_ip($id){
       $res=bd::query("SELECT main_ip FROM server WHERE id='$id'");
       $row= mysql_fetch_array($res);
       return $row['main_ip'];
    }
    
    function get_image(){
      $data=array();
      $query = bd::query("SELECT image.id,image.link as link,server.name as server_name,sponsor.name as sponsor_name,offer.name as offer_name FROM image,server,sponsor,offer WHERE image.id='{$_GET["image"]}' && server.id=image.id_server && sponsor.id=image.id_sponsor && offer.id=image.id_offer");
      while ($row = mysql_fetch_object($query)) {
          $data[]=$row;
      }
      echo json_encode($data);
    }

    function delete_image()
    {
      if(isset($_GET['id']) AND !empty($_GET['id'])) {
        $query = bd::query("SELECT id FROM image WHERE id = '".$_GET['id']."'");
        if(mysql_num_rows($query)) {
          bd::query("DELETE FROM image WHERE id = '".$_GET['id']."'");
          header("Location: show.php");
        }
      }
    }
   
    function upload_image1()
    {
        if(!empty($_FILES["image1"]["tmp_name"]) && !empty($_POST['sponsor']) && !empty($_POST['offer']))
        {
            $target_dir = "../../image/";
            $uniqid = uniqid();
            $target_file = $target_dir . $uniqid.basename($_FILES["image1"]["name"]);
            $uploadOk = 1;
            $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
            if(isset($_POST["submit"])) 
            {
                $check = getimagesize($_FILES["image1"]["tmp_name"]);
                if($check !== false) 
                {
                    $uploadOk = 1;
                }
                else 
                {
                    echo "Error: File is not an image.\n";
                    $uploadOk = 0;
                }
            }
            if (file_exists($target_file)) 
            {
                echo "Error: File already exists.\n";
                $uploadOk = 0;
            }
            
            if ($uploadOk == 0) 
            {
                echo "Error: File was not uploaded.\n";
            } 
            else 
            {

                if (move_uploaded_file($_FILES["image1"]["tmp_name"], $target_file)) 
                {
                    //Get the offer creative image filename :
                    $offer_creative_image_filename   =   $uniqid.basename($_FILES["image1"]["name"]);
                    
                     
                    //Boucler sur chaque Serveur et Uploader l'images dans le dossier '../../image/' :
                    include('../../scripts/bdd.php');

                    $sqlGetServers  =   'SELECT S.id,S.name,S.main_ip,S.login,S.password FROM server S WHERE S.active = ? AND S.id > 1';
                    
                    $cmdGetServers  =   $bdd->prepare($sqlGetServers);
                    $cmdGetServers->execute(array(1));

                    while($server   =   $cmdGetServers->fetch())
                    {
                        $main_ip    =   $server['main_ip'];
                        $login      =   $server['login'];
                        $password   =   $server['password'];
                        $connection = ssh2_connect($main_ip, 22);
                        ssh2_auth_password($connection, $login, $password);
                        ssh2_scp_send($connection, '/var/www/app/image/'.$offer_creative_image_filename, '/var/www/app/image/'.$offer_creative_image_filename, 0777);
                        add($offer_creative_image_filename,$main_ip,$server['id']);
                    } 
                    
                    echo $offer_creative_image_filename. " has been uploaded.\n";
                } 
                else 
                {
                    echo "Error: There was an error uploading your file.\n";
                }
            }
        }
    }
    
    function upload_image2()
    {
        if(!empty($_FILES["image2"]["tmp_name"]) && !empty($_POST['sponsor']) && !empty($_POST['offer']))
        {
            $target_dir = "../../image/";
            $target_file = $target_dir . basename($_FILES["image2"]["name"]);
            $uploadOk = 1;
            $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
            if(isset($_POST["submit"])) {
                $check = getimagesize($_FILES["image2"]["tmp_name"]);
                if($check !== false) {
                    $uploadOk = 1;
                } else {
                    echo "Error: File is not an image.\n";
                    $uploadOk = 0;
                }
            }
            if (file_exists($target_file)) {
                echo "Error: File already exists.\n";
                $uploadOk = 0;
            }
            if ($uploadOk == 0) 
            {
                echo "Error: File was not uploaded.\n";
            } 
            else 
            {
                if (move_uploaded_file($_FILES["image2"]["tmp_name"], $target_file)) 
                {
                    //Get the offer creative image filename :
                    $offer_creative_unsub_image_filename   =   basename($_FILES["image2"]["name"]);
                    
                    
                    //Boucler sur chaque Serveur et Uploader l'images dans le dossier '../../image/' :
                    include('../../scripts/bdd.php');
                    $sqlGetServers  =   'SELECT S.id,S.name,S.main_ip,S.login,S.password FROM server S WHERE S.active = ? AND S.id > 1';
                    
                    $cmdGetServers  =   $bdd->prepare($sqlGetServers);
                    $cmdGetServers->execute(array(1));
                    while($server   =   $cmdGetServers->fetch())
                    {
                        $main_ip    =   $server['main_ip'];
                        $login      =   $server['login'];
                        $password   =   $server['password'];
                        $connection = ssh2_connect($main_ip, 22);
                        ssh2_auth_password($connection, $login, $password);
                        ssh2_scp_send($connection, '/var/www/app/image/'.$offer_creative_unsub_image_filename, '/var/www/app/image/'.$offer_creative_unsub_image_filename, 0777);
                        
                        //Insert the new uploaded image into the database :
                        add($offer_creative_unsub_image_filename,$main_ip,$server['id']);
                    }
                    echo $offer_creative_unsub_image_filename. " has been uploaded.\n";
                }
                else 
                {
                    echo "Error: There was an error uploading your file.\n";
                }
            }
        }
    }

    function RandomPrefix($length){
        $random= "";
        srand((double)microtime()*1000000);
        $data="0123456789abcdefghijklmnopqrstuvwxyz";
        for($i = 0; $i < $length; $i++){
            $random .= substr($data, (rand()%(strlen($data))), 1);
        }
        return $random;
    }