<?php  
  session_start();
    header('Content-Type: text/html; charset=utf-8');
	$instance_id = $_SESSION['client_id'];
        //require "log.php";
        //include "../settings.php";
		include "writedblog.php";
		
		$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;
        }

        $data = array();

    if ($_GET['func'] == 'show') {
        $query = "SELECT o.`id_outlet`,o.`client_id`,o.`name`,o.`region`,o.`city`,o.`address`,o.`contact_name`,o.`id_code_PSD`,
        		o.`contract_number`,o.`note`,o.`type_TT`,o.`sales_contact_number`,c.`name_TT`,o.`geoX`,o.`geoY`,o.`model`,  
        		(SELECT GROUP_CONCAT(`equipment_id` SEPARATOR ',') FROM `toir_outlet_equipment` WHERE `outlet_id` = o.`id_outlet` ) AS  `equipment_id`, 
                c.client,
                (SELECT GROUP_CONCAT(e.`model` SEPARATOR ', ') FROM `toir_outlet_equipment` oe LEFT JOIN `equipment` e ON oe.`equipment_id`=e.`id_equipment` WHERE oe.`outlet_id` = o.`id_outlet` ) AS  `model`,
                o.`arrival`
                FROM `toir_outlets` `o` 
					INNER JOIN `client` c ON c.`id_client` = o.`client_id`  AND c.`instance_id` = $instance_id";
        $stmt = $db->prepare($query);
        $stmt->execute();
        $stmt->bind_result($id_outlet, $client_id, $name, $region, $city, $address, $contact_name, $id_code_PSD, 
            $contract_number,
        $note, $type_TT, $sales_contact_number, $name_TT, $geoX, $geoY, $model, $equipment_id, $client_name, $model_equipment, $arrival);
        while ($stmt->fetch()) {

            $query = 
            $data[] = array(
                'id_outlet' => $id_outlet,
                'client_id' => $client_id,            		
                'name' => $name,
                'region' => $region,
                'city' => $city,
                'address' => $address,
                'contact_name' => $contact_name,
                'id_code_PSD' => $id_code_PSD,
                'contract_number' => $contract_number,
                'note' => $note,
                'type_TT' => $type_TT,
                'sales_contact_number' => $sales_contact_number,
                'name_TT' => $name_TT,
                'geoX' => $geoX,
                'geoY' => $geoY,
                'model' => $model,
            	'equipment_id' => $equipment_id,
            	'client_name' => $client_name,
                'model_equipment' => $model_equipment,       
            	'arrival' => $arrival		 
            		
                );
        }

        $stmt->close(); 
        // print_r($data);
        // exit;
        echo'{rows:'.json_encode($data).'}';
}

if ($_REQUEST['func'] == 'getOutletsData') {
    $id = $_REQUEST['id'];
    $query = "SELECT      
          `region`,
          `city`,
          `address`,
          `contact_number`,
          `contact_name`,
          `id_code_PSD`,
          `contract_number`,
          `note`,
          `type_TT`,
          `sales_contact_number`
    FROM `toir_outlets` WHERE `id_outlet`= $id";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $stmt->bind_result($region, $city, $address, $contact_phone, $contact_man, $ID_PSD, $client_number, $description, 
            $outlet_type, $sales_man);
    while ($stmt->fetch()) {
        // echo $city;
        $data = array(
                'region' => $region,
                'city' => $city,
                'address' => $address,
                'contact_phone' => $contact_phone,
                'contact_man' => $contact_man,
                'ID_PSD' => $ID_PSD,
                'client_number' => $client_number,
                'description' => $description,
                'outlet_type' => $outlet_type,
                'sales_man' => $sales_man           
        );
    }
    $stmt->close();
    echo json_encode($data);    
}
if ($_REQUEST['func'] == 'showEquipment') {
    $clientID = $_REQUEST['clientID'];
    $query = "SELECT `equipment`.`id_equipment`,`equipment`.`model`, `equipment`.`inventory_number`
                FROM `toir_client_equipment` 
                LEFT JOIN `equipment` ON `toir_client_equipment`.`id_equipment` = `equipment`.`id_equipment`
                WHERE `toir_client_equipment`.`client_id` = '".$clientID."'";
    
    
    // echo $query;
    // exit;
    $stmt = $db->prepare($query);
    $stmt->execute();
    $stmt->bind_result($id, $name, $inventory_number);
    while ($stmt->fetch()) {
        $data[] = array(
            'id' => $id,
            'name' => $inventory_number.'  '.$name
        );
    }
    $stmt->close();
    echo'{rows:'.json_encode($data).'}';
}
if ($_REQUEST['func'] == 'showOutlets') {
    $clientID = $_REQUEST['clientID'];
    // echo $clientID;
    // exit;
    $query = "SELECT `id_outlet`, `name` FROM `toir_outlets` WHERE client_id = $clientID";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $stmt->bind_result($id, $name);
    while ($stmt->fetch()) {
        $data[] = array(
            'id' => $id,
            'name' => $name
        );
    }
    $stmt->close();
    echo'{rows:'.json_encode($data).'}';
}
if ($_REQUEST['func'] == 'showClients') {
    $query = "SELECT `id_client`, `client` FROM `client` WHERE `instance_id`=$instance_id";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $stmt->bind_result($id, $name);
    while ($stmt->fetch()) {
        $data[] = array(
            'id' => $id,
            'name' => $name
        );
    }
    $stmt->close();
    echo'{rows:'.json_encode($data).'}';
}
if ($_GET['func'] == 'selectCity') {
    $region = $_GET['region'];
    $city = $_GET['inpCity'];
    $query = "SELECT DISTINCT `city` FROM `toir_outlets` WHERE `region` = '".$region."' AND city LIKE '$city%'";
    // echo $query;
    $stmt = $db->prepare($query);
    $stmt->execute();
    $stmt->bind_result($city);
    while ($stmt->fetch()) {
        $data[] = array(
            'city' => $city
        );
    }
    echo json_encode($data);
}
if ($_GET['func'] == 'selectRegion') {
    $region = $_GET['inpRegion'];
    $query = "SELECT DISTINCT `region` FROM `toir_outlets` WHERE `region` LIKE '$region%'";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $stmt->bind_result($region);
    while ($stmt->fetch()) {
        $data[] = array(
            'region' => $region
        );
    }
    echo json_encode($data); 
}
if ($_REQUEST['func'] == 'addedit') {
    
	//print_r($_REQUEST); exit;
	$func = $_GET['f'];
    $id = $_POST['request_id_outlet'];
    $name = $_POST['request_name'];
    $client_id = $_POST['client'];
    $region = $_POST['request_region'];
    $city = $_POST['request_city'];
    $contact_phone = $_POST['request_contact_phone'];
    $address = $_POST['request_address'];
    $contact_name = $_POST['request_contact_name'];
    $contract_number = $_POST['request_contract_number'];
    $type_TT = $_POST['request_type_TT'];
    $sales_contact_number = $_POST['request_sales_contact_number'];
    $geox = $_POST['request_geox'];
    $geoy = $_POST['request_geoy'];
    $equipment_id = explode(',', $_POST['request_equipment']);
    $arrival = $_POST['request_arrival'];

    //print_r($_REQUEST); exit;
// echo $client_id

    // if (is_int($client_id)) {
        // echo $client_id;
        /* $query = "SELECT `id_client` FROM `client` WHERE `client` = '$client_id'";
        // echo $query;
        $stmt = $db->prepare($query);
        $stmt->execute();
        $stmt->bind_result($id_client);
        while ($stmt->fetch()) {
        }
        // echo $id_client;
        // exit;
        $stmt->close(); */
    // }

    // foreach ($_POST as $key => $value)
    // {           
    //     $data[$key] = $value;       
    // }
    // echo $func;

    
        if ($func == 'add') {
        $query = "INSERT INTO `toir_outlets` (`client_id`,`name`,`region`,`city`,`address`,`contact_number`,`contact_name`,`contract_number`,`type_TT`,`sales_contact_number`,`geoX`,`geoY`,`arrival`)  
        VALUES ('".$client_id."', '".$name."','".$region."','".$city."','".$address."','".$contact_phone."','".$contact_name."',
            '".$contract_number."','".$type_TT."','".$sales_contact_number."','".$geox."','".$geoy."','".$arrival."')";
        } else {
            $query = "UPDATE `toir_outlets` 
            SET  `client_id` = '".$client_id."',
            `name` = '".$name."',
            `region` = '".$region."',
            `city` = '".$city."',
            `address` = '".$address."',
            `contact_number` = '".$contact_phone."',
            `contact_name` = '".$contact_name."',
            `contract_number` = '".$contract_number."',
            `type_TT` = '".$type_TT."',
            `sales_contact_number` = '".$sales_contact_number."',
            `geoX` = '".$geox."',
            `geoY` = '".$geoy."',
            `arrival` = '".$arrival."' 
            WHERE id_outlet = '$id'";
        }
    
    //print_r($query);
    //exit;
// 
    
    $stmt = $db->prepare($query);
    $stmt->execute();
    if ($func == 'add') {
    $outlet_id = $stmt->insert_id;
}
    $stmt->close(); 
 
 for($i=0;$i<count($equipment_id);$i++)
{
    if ($func == 'add') {

        $query = "INSERT INTO `toir_outlet_equipment` (`outlet_id`,`equipment_id`) VALUES ('".$outlet_id."','".$equipment_id[$i]."')";    
    } else {
        if ($equipment_id) {
            if($i == 0)
            {
                $query2 = "DELETE FROM `toir_outlet_equipment` WHERE `outlet_id` = $id";
                $stmt2 = $db->prepare($query2);
                $stmt2->execute();
                $stmt2->close();
            }
           $query = "INSERT INTO  `toir_outlet_equipment` (`equipment_id`, `outlet_id`)  VALUES (".$equipment_id[$i].", $id)";
        }  
    }
    /* echo $query;
    exit; */
    if ($equipment_id) {
        $stmt = $db->prepare($query);
        $stmt->execute();
        $stmt->close();
    }
}   

     




}
if ($_REQUEST['func'] == 'del') {
    $id = $_REQUEST['id'];  
    $query = "DELETE FROM `toir_outlets` WHERE `id_outlet`=$id LIMIT 1";
    // echo $query;
    $stmt = $db->prepare($query);
    $stmt->execute();
    $stmt->close();
    
    $query = "DELETE FROM `toir_outlet_equipment` WHERE `outlet_id` = $id";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $stmt->close();
}