<?php    
  session_start();
  header('Content-Type: text/html; charset=utf-8');
  //echo chr(239).chr(187).chr(191);;
  $role = $_SESSION['role'];
  $id_user = $_SESSION['id'];
  
  $instance_id = $_SESSION['client_id'];
  
  $dbset = json_decode($_SESSION['settingsApp'],true);
  $db = new mysqli ($dbset['DB']['DB_HOST'],$dbset['DB']['DB_USER'],$dbset['DB']['DB_PASS'],$dbset['DB']['DB_NAME']);

  //$db = new mysqli ($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME);
  $db->query("SET CHARSET SET utf8");
  $db->query("SET NAMES 'utf8'");
  if (mysqli_connect_errno()) {
    echo "Error connecting to DB";
    exit;
  }
  //-------------------------------------show--------------------------------------------------		

  if ($_GET['func']=='show')
  {
    $i=0;
    
	$start = isset($_REQUEST['start']) ? $_REQUEST['start'] : 0;
	$limit = isset($_REQUEST['limit']) ? $_REQUEST['limit'] : 50;
	
	
	$query = "SELECT COUNT(tp.id) FROM ms_trade_point tp LEFT JOIN ms_region r ON tp.id_region = r.id LEFT JOIN ms_network n ON tp.id_network = n.id LEFT JOIN ms_city c ON tp.id_city = c.id WHERE tp.instance_id = ".$instance_id.";";
		//echo $query;
		if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($total);
			$stmt->fetch();
			 $stmt->close();
		}
	
	
	$query = "SELECT tp.id,tp.name,r.name,n.name,c.name,tp.address FROM ms_trade_point tp LEFT JOIN ms_region r ON tp.id_region = r.id LEFT JOIN ms_network n ON tp.id_network = n.id LEFT JOIN ms_city c ON tp.id_city = c.id WHERE tp.instance_id = ".$instance_id." LIMIT " . $start . "," . $limit ." ;"; //WHERE tp.id > 0 AND tp.id <501 "; // WHERE tp.id >= ".$_GET['start']." LIMIT ". $_GET['limit'];
    //echo $query;
   $stmt = $db->prepare($query);
      $stmt->execute();
      $stmt->bind_result($id, $name, $region, $network, $city, $address);
      while ($stmt->fetch()) {
        $Model[$i] = 
        array(
               'id'=>$id,
               'name'=>$name,
               'region'=>$region,
               'network'=>$network,
               'city'=>$city,
               'address'=>$address
        );
        $i++;
      } 
      $stmt->close();
      $db->close();
    
    echo'{totalCount:'.$total.',rows:'.json_encode($Model).'}'; 
  }


  //---------------------------- delete ----------------------------------------

  $i=0;
  if ($_POST['func']=='delete')
  {
    $id = $_POST['id'];

    $query = "DELETE FROM ms_trade_point WHERE id=".$id;
    echo $query;
    $stmt = $db->prepare($query);
    $stmt->execute();

    $stmt->close();
    $db->close();
  }


  //---------------- show to update-------------------------------
  if ($_POST['func']=='edit')
  {
    $idClient = $_POST['id'];

    $query = "SELECT id, name, id_city, address,number,id_region,id_network FROM ms_trade_point WHERE id=".$idClient;
    if ($stmt = $db->prepare($query)){
      $stmt->execute();
      $stmt->bind_result($id,$name,$id_city,$address,$number,$id_region,$id_network);
      while ($stmt->fetch()){
        $data_edit = $id.'/t'.$name.'/t'.$id_city.'/t'.$address.'/t'.$number.'/t'.$id_region.'/t'.$id_network.'/t';
      } 
      //$data_edit = substr($data_edit,0,strlen($data_edit)-2);
      $stmt->close();
      $db->close();
    }
    echo $data_edit;
  }


  //---------------- update------------------------------------------------------------------

  if ($_POST['func']=='update')
  {
    $id = $_POST['id'];
    $name = $_POST['name'];
    //$phone = $_POST['phone'];
    $id_city = $_POST['id_city'];
    $address = $_POST['address'];
	$number = $_POST['number'];
    $region = $_POST['region'];
	$network = $_POST['network'];

    
    if ($id == NaN)                             // add new rows
    {
      $query ="SELECT MAX(id) FROM ms_client";
      $stmt = $db->prepare($query);                   
      $stmt->execute();
      $stmt->bind_result($id);
      while ($stmt->fetch()) 
      {
        $number_id=$id;
      }
      $number_id++;
      //$query = "INSERT INTO ms_trade_point (id, name, id_city, address, number, id_region, id_network) VALUES (".$number_id.", '".$name."', '".$id_city."', '".$address."', ".$number.", ".$region.", ".$network.")";
	  $query = "INSERT INTO ms_trade_point (name, id_city, address, number, id_region, id_network, instance_id) VALUES ('".$name."', '".$id_city."', '".$address."', ".$number.", ".$region.", ".$network.", ".$instance_id.")";
     //echo $query; exit;
	  $stmt = $db->prepare($query);
      $stmt->execute();    
    }
    else                                        // update rows
    {
      $query = "UPDATE ms_trade_point SET name='".$name."', id_city='".$id_city."', address='".$address."', number=".$number.", region=".$region.", network=".$network." WHERE id=".$id;
      $stmt = $db->prepare($query);
      $stmt->execute();
    }
    
    $stmt->close();
    $db->close();		   
  }	

  
  
   if ($_GET['func']=='showCity')
  {
    $i=0;
    $query = "SELECT id,name FROM ms_city";
    if ($stmt = $db->prepare($query))
    {
      $stmt->execute();
      $stmt->bind_result($id,$name);
      while ($stmt->fetch())
      {
        $store[$i]= 
        array('id'=>$id,
              'name'=>$name,
        );
        $i++;
      } 
      $stmt->close();
      $db->close();
    }
    echo'{rows:'.json_encode($store).'}';
  }
    if ($_GET['func']=='showRegion')
  {
    $i=0;
    $query = "SELECT id,name FROM ms_region";
    if ($stmt = $db->prepare($query))
    {
      $stmt->execute();
      $stmt->bind_result($id,$name);
      while ($stmt->fetch())
      {
        $store[$i]= 
        array('id'=>$id,
              'name'=>$name,
        );
        $i++;
      } 
      $stmt->close();
      $db->close();
    }
    echo'{rows:'.json_encode($store).'}';
  }
    if ($_GET['func']=='showNetwork')
  {
    $i=0;
    $query = "SELECT id,name FROM ms_network WHERE instance_id=".$instance_id.";";
    if ($stmt = $db->prepare($query))
    {
      $stmt->execute();
      $stmt->bind_result($id,$name);
      while ($stmt->fetch())
      {
        $store[$i]= 
        array('id'=>$id,
              'name'=>$name,
        );
        $i++;
      } 
      $stmt->close();
      $db->close();
    }
    echo'{rows:'.json_encode($store).'}';
  }
?>