<?php
    include_once '../account/session.php';
    include_once '../../scripts/bd.php';
    
    if($_SESSION["type"] == 'it') {
      die("404 not found: <a href='/app/manager/offer/show.php'>Go back</a>");
    }
    if(isset($_GET['action'])){
        $action=$_GET['action'];
        if($action=='add')add();
        if($action=='show')show();
        if($action=='get')get();
        if($action=='set')set();
   }
   
   function verify_username($id,$username){
       $query = bd::query("SELECT * FROM account_mailer where username like '$username' && id!='$id'");
       if(mysql_num_rows($query)>0){
           return true;
       }
       return false;
   }
   
   function add(){
        $first_name=$_POST["first_name"];
        $last_name=$_POST["last_name"];
        $username=$_POST["username"];
        $password=$_POST["password"];
        $address_email=$_POST["address_email"];
        $im_id=$_POST["im_id"];
        $status="Under Review";
        $date_add=date('Y-m-d h:i:s');
        $date_set=date('Y-m-d h:i:s');
        $ok=0;
        if(!verify_username('0',$username)){
            $rep=bd::query("INSERT INTO account_mailer VALUES (NULL, '$first_name', '$last_name', '$address_email', '$im_id', '$username', '$password', '$status', '$date_add', '$date_set');");
            if(!$rep){
               $ok=2; 
            }
        }else{
            $ok=1; 
        }
        echo $ok;
   }
   
   function show(){ 
      $list=array();
      $data= bd::query("SELECT id,first_name,last_name,username,status FROM account_mailer where id!=100 and id!=24");
      while ($row = mysql_fetch_object($data)) {
          $list[]=$row;
      }
      echo json_encode($list);
   }
   
   function get(){ 
      $data = bd::query("SELECT * FROM account_mailer WHERE id='{$_GET["id_mailer"]}'");
      $row = mysql_fetch_array($data);
      return $row;
   }
   
   function set(){ 
       $first_name=$_POST["first_name"];
       $last_name=$_POST["last_name"];
       $username=$_POST["username"];
       $password=$_POST["password"];
       $address_email=$_POST["address_email"];
       $im_id=$_POST["im_id"];
       $status=$_POST["status"];
       $date_set=date('Y-m-d h:i:s');
       $ok=0;
        if(!verify_username($_POST["id"],$username)){
            $rep=bd::query("UPDATE account_mailer SET first_name='$first_name', last_name='$last_name', address_email='$address_email', im_id='$im_id', username='$username', password='$password', status='$status', date_set='$date_set' WHERE id='{$_POST["id"]}'");
            if(!$rep){
               $ok=2; 
            }
        }else{
            $ok=1; 
        }
        echo $ok;
   }