<?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();
        if($action=='delete')delete($_GET['id_it']);
   }
   

   function delete($id)
   {
      if(!empty($id) AND is_numeric($id)) {
        $sql = bd::query("SELECT id FROM account_manager WHERE id = '".$id."' AND type = 'it'");
        if(mysql_num_rows($sql)>0) {
          bd::query("DELETE FROM account_manager WHERE id = '".$id."'");
          echo "<script>alert('Deleted !');</script>";
          header("Location: show.php#success");
        } else {
          echo "404 not found ! <a href='show.php'>Go back</a>";
        }
      } else {
        header("Location: show.php#error");
      }
   }

   function verify_username($id,$username){
       $query = bd::query("SELECT id FROM account_manager WHERE username = '".$username."' AND type = 'it' AND id!='".$id."'");
       if(mysql_num_rows($query)>0){
           return true;
       }
       return false;
   }
   
   function add(){
        $username=$_POST["username"];
        $password=$_POST["password"];
        $status="Under Review";
        $ok=0;
        if(!verify_username('0',$username)){
            $rep=bd::query("INSERT INTO account_manager(username,password,type,status) VALUES ('$username', '$password', 'it', '$status')");
            if(!$rep){
               $ok=2; 
            }
        }else{
            $ok=1; 
        }
        echo $ok;
   }
   
   function show(){ 
      $list=array();
      $data= bd::query("SELECT id,username,status FROM account_manager where type = 'it'");
      while ($row = mysql_fetch_object($data)) {
          $list[]=$row;
      }
      echo json_encode($list);
   }
   
   function get(){ 
      $data = bd::query("SELECT * FROM account_manager WHERE id='{$_GET["id_it"]}' and type = 'it'");
      $row = mysql_fetch_array($data);
      return $row;
   }
   
   function set(){ 
       $username=$_POST["username"];
       $password=$_POST["password"];
       $status=$_POST["status"];
       $ok=0;
        if(!verify_username($_POST["id"],$username)){
            $rep=bd::query("UPDATE account_manager SET username='$username', password='$password', status='$status' WHERE id='{$_POST["id"]}'");
            if(!$rep){
               $ok=2; 
            }
        }else{
            $ok=1; 
        }
        echo $ok;
   }