<?php
global $hooks;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$hooks->add_action('silex_action', 'the_company');

function mycompany_title() {
    echo "My company";
}

function editcompany_title() {
    echo "Edit company";
}

function editcompany_js() {
    ?>
    <script src="/assets/global/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script>
    <script src="/assets/modul-js/common/company/editcompany.min.js"></script>
<?php }

function editwarehouse_js() {
    ?>
	<script src="/assets/global/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/select2/js/select2.full.min.js" type="text/javascript"></script>
    <script src="/assets/global/plugins/datatables/datatables.min.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
	<script src="/assets/modul-js/common/company/editwarehouse.min.js"></script>
<?php }

function editbranch_js() {
    ?>
	<script src="/assets/global/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script>
    <script src="/assets/global/plugins/datatables/datatables.min.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
	<script src="/assets/modul-js/common/company/editbranch.min.js"></script>
<?php }

function editstaff_js() {
    ?>
	<script src="/assets/global/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/select2/js/select2.full.min.js" type="text/javascript"></script>
    <script src="/assets/global/plugins/datatables/datatables.min.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
    <script src="/assets/modul-js/common/company/editstaff.min.js"></script>
<?php }

function editcompany_css() {
    ?>
	<link href="/assets/global/plugins/dropzone/dropzone.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/dropzone/basic.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/bootstrap-fileinput/bootstrap-fileinput.css" rel="stylesheet" type="text/css" />
	<link href="/assets/modul-css/profile/profile.min.css" rel="stylesheet" type="text/css" />

<?php }

function editstaff_css() {
    ?>
	<link href="/assets/global/plugins/dropzone/dropzone.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/dropzone/basic.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/select2/css/select2.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/select2/css/select2-bootstrap.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/bootstrap-fileinput/bootstrap-fileinput.css" rel="stylesheet" type="text/css" />
	<link href="/assets/modul-css/profile/profile.min.css" rel="stylesheet" type="text/css" />
<?php }

function editwarehouse_css() {
    ?>
	<link href="/assets/global/plugins/dropzone/dropzone.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/dropzone/basic.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/select2/css/select2.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/select2/css/select2-bootstrap.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/bootstrap-fileinput/bootstrap-fileinput.css" rel="stylesheet" type="text/css" />
	<link href="/assets/modul-css/profile/profile.min.css" rel="stylesheet" type="text/css" />
<?php }

function editbranch_css() {
    ?>
	<link href="/assets/global/plugins/dropzone/dropzone.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/dropzone/basic.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/bootstrap-fileinput/bootstrap-fileinput.css" rel="stylesheet" type="text/css" />
	<link href="/assets/modul-css/profile/profile.min.css" rel="stylesheet" type="text/css" />
<?php }

function mycompany_js() {
    ?>
	<script src="/assets/global/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script>    
<?php }

function the_company() {
    global $app;
	
	//WAREHOUSE CODE
	$app->get('/company/warehouse', function() {
        global $hooks;
		$hooks->add_action('global_css', 'editwarehouse_css');
        $hooks->add_action('global_js', 'editwarehouse_js');
        $hooks->add_action('the_title', "editcompany_title");
        the_head();
        include 'editwarehouse.tpl.php';
        the_footer();
        return "";
    });
    $app->post('/company/warehouse/list', function(Request $request)  {
        $curpage = $request->get('page');
        include 'editwarehouse.list.php';
        return '';
    });
	$app->post('/company/warehouse/add', function(Request $request) {
        global $db;
        $name = $request->get('name');
        $address = $request->get('address');
        $city = $request->get('city');
        $zip = $request->get('zip');
        $state = $request->get('state');
        $country = $request->get('country');
        $contact_person = $request->get('contact_person');
        $contact_person_no = $request->get('contact_person_no');
        $branch = $request->get('branch');
		$company_id = getCompany($_SESSION['user_id']);
        // CONDITIONAL FOR MAKE SURE BANK EXISTS
            // PREPARE
		$db->bind("name", $name);
		$db->bind("address", $address);
		$db->bind("city", $city);
		$db->bind("zip", $zip);
		$db->bind("state", $state);
		$db->bind("country", $country);
		$db->bind("contact_person", $contact_person);
		$db->bind("contact_person_no", $contact_person_no);
		$db->bind("branch", $branch);
		$db->bind("company_id", $company_id);
		// EXECUTE
		$row = $db->query("INSERT INTO warehouses(name,address,city,zip,state,country,contact_person,contact_person_no,branch_id,company_id) VALUES (:name,:address,:city,:zip,:state,:country,:contact_person,:contact_person_no,:branch,:company_id)");
		if ($row) {
			action_log($_SESSION['user_id'], "Create Warehouse", "SUCCESS");
			return new Response('SUCCESS', 200);
		}else{
			action_log($_SESSION['user_id'], "Create Warehouse", "FAILED");
			return new Response('Failed', 201);
		}
       
    });
	$app->post('/company/warehouse/delete', function(Request $request) {
        global $db;
        $warehouse_id = $request->get('id');
		$name = get_warehouse($warehouse_id , "name");
		$db->bind("warehouse_id", $warehouse_id);
		// EXECUTE
		$row = $db->query("DELETE FROM warehouses WHERE warehouse_id = :warehouse_id");
		if ($row) {
			action_log($_SESSION['user_id'], "Delete Warehouse : ID - " . $warehouse_id . " | Name - " .$name , "SUCCESS");
			return new Response('SUCCESS', 200);
		}else{
			action_log($_SESSION['user_id'], "Delete Warehouse : ID - " . $warehouse_id . " | Name - " .$name , "FAILED");
			return new Response('Failed', 201);
		}
       
    });
	$app->post('/company/warehouse/edit', function(Request $request) {
        global $db;
		
        $warehouse_id = $request->get('id');
        $name = $request->get('name');
        $address = $request->get('address');
        $city = $request->get('city');
        $zip = $request->get('zip');
        $state = $request->get('state');
        $country = $request->get('country');
        $notice = $request->get('notice');
        $contact_person = $request->get('contact_person');
        $contact_person_no = $request->get('contact_person_no');
        $branch = $request->get('branch');
        
            // PREPARE
		$db->bind("warehouse_id", $warehouse_id);
		$db->bind("name", $name);
		$db->bind("address", $address);
		$db->bind("city", $city);
		$db->bind("zip", $zip);
		$db->bind("state", $state);
		$db->bind("country", $country);
		$db->bind("notice", $notice);
		$db->bind("contact_person", $contact_person);
		$db->bind("contact_person_no", $contact_person_no);
		$db->bind("branch", $branch);
		$row = $db->query("UPDATE warehouses SET 
						name               = :name,
						address            = :address,
						city               = :city,
						zip 	           = :zip,
						state              = :state,
						country            = :country,
						contact_person     = :contact_person,
						contact_person_no  = :contact_person_no,
						branch_id  		   = :branch,
						notice   		   = :notice
						WHERE warehouse_id = :warehouse_id");
		if ($row) {
			action_log($_SESSION['user_id'], "Edit Warehouse : ID - " . $warehouse_id , "SUCCESS");
			return new Response('SUCCESS', 200);
		}else{
			action_log($_SESSION['user_id'], "Edit Warehouse : ID - " . $warehouse_id , "FAILED");
			return new Response('Failed', 201);
		}
    });
    $app->post('/company/warehouse/status-edit', function (Request $request) {
        global $db;
        $warehouse_id = $request->get('id');
        $state = $request->get('state');
		if($state == "true"){
			$status = "1";
		}else{
			$status = "0";
		}
        // Bind the data
        $db->bind("warehouse_id", $warehouse_id);
        $db->bind("status", $status);
        $companyupdate = $db->query("UPDATE warehouses SET  
									 status= :status 
									 WHERE warehouse_id = :warehouse_id");
        if ($status) {
			action_log($_SESSION['user_id'], "Edit Warehouse Status : ID - " . $warehouse_id , "SUCCESS");
            return new Response('Success', 200);
        } else {
			action_log($_SESSION['user_id'], "Edit Warehouse Status : ID - " . $warehouse_id , "FAILED");
            return new Response('Failed', 201);
        }
    });
    $app->post('/company/warehouse/get-data', function (Request $request) {
        global $db;
        $warehouse_id = $request->get('id');
        // Bind the data
        $html = getModalWarehouse($warehouse_id);
		
		return $html;
    });
    
	
	//BRANCH CODE
	$app->get('/company/branch', function() {
        global $hooks;
		$hooks->add_action('global_css', 'editbranch_css');
        $hooks->add_action('global_js', 'editbranch_js');
        $hooks->add_action('the_title', "editcompany_title");
        the_head();
        include 'editbranch.tpl.php';
        the_footer();
        return "";
    });
    $app->post('/company/branch/list', function(Request $request)  {
        $curpage = $request->get('page');
        include 'editbranch.list.php';
        return '';
    });
	$app->post('/company/branch/add', function(Request $request) {
        global $db;
        $name = $request->get('name');
        $address = $request->get('address');
        $city = $request->get('city');
        $zip = $request->get('zip');
        $state = $request->get('state');
        $contact_person = $request->get('contact_person');
        $contact_person_no = $request->get('contact_person_no');
        $state = $request->get('state');
        $country = $request->get('country');
		$company_id = getCompany($_SESSION['user_id']);
        // CONDITIONAL FOR MAKE SURE BANK EXISTS
            // PREPARE
		$db->bind("branch_name", $name);
		$db->bind("branch_address", $address);
		$db->bind("branch_city", $city);
		$db->bind("branch_zip", $zip);
		$db->bind("branch_state", $state);
		$db->bind("contact_person", $contact_person);
		$db->bind("contact_person_no", $contact_person_no);
		$db->bind("branch_country", $country);
		$db->bind("company_id", $company_id);
		// EXECUTE
		$row = $db->query("INSERT INTO branches(branch_name,branch_address,branch_city,branch_zip,branch_state,contact_person,contact_person_no,branch_country,company_id) VALUES (:branch_name,:branch_address,:branch_city,:branch_zip,:branch_state,:contact_person,:contact_person_no,:branch_country,:company_id)");
		if ($row) {
			action_log($_SESSION['user_id'], "Create Branch", "SUCCESS");
			return new Response('SUCCESS', 200);
		}else{
			action_log($_SESSION['user_id'], "Create Branch", "FAILED");
			return new Response('Failed', 201);
		}
       
    });
	$app->post('/company/branch/delete', function(Request $request) {
        global $db;
        $branch_id = $request->get('id');
		$name = get_branch($branch_id , "branch_name");
		
		$db->bind("branch_id", $branch_id);
		$row = $db->query("DELETE FROM branches WHERE branch_id = :branch_id");
		if ($row) {
			action_log($_SESSION['user_id'], "Delete Branch : ID - " . $branch_id . " | Name - " .$name , "SUCCESS");
			return new Response('SUCCESS', 200);
		}else{
			action_log($_SESSION['user_id'], "Delete Branch : ID - " . $branch_id . " | Name - " .$name , "FAILED");
			return new Response('Failed', 201);
		}
       
    });
	$app->post('/company/branch/edit', function(Request $request) {
        global $db;
		
        $branch_id = $request->get('id');
        $branch_name = $request->get('name');
        $branch_address = $request->get('address');
        $branch_city = $request->get('city');
        $branch_zip = $request->get('zip');
        $branch_state = $request->get('state');
        $contact_person = $request->get('contact_person');
        $contact_person_no = $request->get('contact_person_no');
        $branch_country = $request->get('country');
        
            // PREPARE
		$db->bind("branch_id", $branch_id);
		$db->bind("branch_name", $branch_name);
		$db->bind("branch_address", $branch_address);
		$db->bind("branch_city", $branch_city);
		$db->bind("branch_zip", $branch_zip);
		$db->bind("branch_state", $branch_state);
		$db->bind("contact_person", $contact_person);
		$db->bind("contact_person_no", $contact_person_no);
		$db->bind("branch_country", $branch_country);
		// EXECUTE
		$row = $db->query("UPDATE branches SET 
						branch_name        = :branch_name,
						branch_address     = :branch_address,
						branch_city        = :branch_city,
						branch_zip 	       = :branch_zip,
						branch_state       = :branch_state,
						contact_person     = :contact_person,
						contact_person_no  = :contact_person_no,
						branch_country     = :branch_country
						WHERE branch_id    = :branch_id");
		if ($row) {
			action_log($_SESSION['user_id'], "Edit Branch : ID - " . $branch_id , "SUCCESS");
			return new Response('SUCCESS', 200);
		}else{
			action_log($_SESSION['user_id'], "Edit Branch : ID - " . $branch_id , "FAILED");
			return new Response('Failed', 201);
		}
    });
    $app->post('/company/branch/get-data', function (Request $request) {
        global $db;
        $branch_id = $request->get('id');
        // Bind the data
        $html = getModalBranch($branch_id);
		
		return $html;
    });
	
	//COMPANY CODE 
	$app->post('/company/edit/update', function (Request $request) {
        global $db;
		
		
		//CHECK IF USER HAVE COMPANY
		$result = getCompany($_SESSION['user_id']);
		
		if($result == 0){
			//CHECK IF USER HAVE NO COMPANY
			//WE CREATE AUTOMATICALLY
			$create_companies = $db->query("INSERT INTO companies(company_id) VALUES (NULL);");
			
			
			$company_id = $db->lastInsertId();
			
			if($create_companies && $company_id){
				action_log($_SESSION['user_id'], "Create Company : ID - " . $company_id , "SUCCESS");
				//CHECK COMPANY CREATED
				//WE ASSIGN ROLE AS ADMIN
				
				//COMPANY WAS CREATED
				//UPDATE BASED ON WHAT USER SUBMIT
				//TAKE USER SUBMITTED DATA
				$name              = $request->get('name');
				$tax_no            = $request->get('tax_no');
				$company_no        = $request->get('company_no');
				$company_fax       = $request->get('company_fax');
				$address           = $request->get('address');
				$city              = $request->get('city');
				$zip               = $request->get('zip');
				$state             = $request->get('state');
				$country           = $request->get('country');
				$reg_no            = $request->get('reg_no');
				$contact_person    = $request->get('contact_person');
				$contact_person_no = $request->get('contact_person_no');
				
				// BIND THE DATA
				$db->bind("name",$name);
				$db->bind("tax_no",$tax_no);
				$db->bind("company_no",$company_no);
				$db->bind("company_fax",$company_fax);
				$db->bind("address",$address);
				$db->bind("city",$city);
				$db->bind("zip",$zip);
				$db->bind("state",$state);
				$db->bind("country",$country);
				$db->bind("reg_no",$reg_no);
				$db->bind("contact_person",$contact_person);
				$db->bind("contact_person_no",$contact_person_no);
				$db->bind("company_id", $company_id);
				
				//UPDATE THE DATA
				$companyupdate = $db->query("UPDATE companies SET 
											 name               = :name,
											 tax_no             = :tax_no,
											 company_no         = :company_no,
											 company_fax        = :company_fax,
											 address            = :address,
											 city               = :city,
											 zip                = :zip,
											 state              = :state,
											 country            = :country,
											 reg_no             = :reg_no,
											 contact_person     = :contact_person,
											 contact_person_no  = :contact_person_no
											 WHERE company_id   = :company_id");
											 
				$db->bind("company_id", $company_id);
				$db->bind("branch_name", "HQ");
				$db->bind("branch_address",$address);
				$db->bind("branch_city",$city);
				$db->bind("branch_zip",$zip);
				$db->bind("branch_state",$state);
				$db->bind("branch_country",$country);
				
				$create_branch = $db->query("INSERT INTO branches(company_id, branch_name, branch_address, branch_city, branch_zip, branch_state, branch_country) VALUES (:company_id, :branch_name, :branch_address, :branch_city, :branch_zip, :branch_state, :branch_country);");
				$branch_id = $db->lastInsertId();
				
				$db->bind("company_id", $company_id);
				$db->bind("branch_id", $branch_id);
				$db->bind("user_id", $_SESSION['user_id']);
				$db->bind("position", "1");
				$enter_company = $db->query("INSERT INTO user_company(company_id, branch_id, user_id,position) VALUES (:company_id, :branch_id, :user_id, :position);");	
				
				if ($companyupdate && $create_branch) {
					$_SESSION["company_id"] = getCompany($_SESSION['user_id']);
					$_SESSION["branch_id"] = getBranch($_SESSION['user_id']);
					return new Response('Success', 200);
				} else {
					$_SESSION["company_id"] = getCompany($_SESSION['user_id']);
					$_SESSION["branch_id"] = getBranch($_SESSION['user_id']);
					return new Response('Failed', 201);
				}
			}else{
				action_log($_SESSION['user_id'], "Create Company : ID - " . $company_id , "FAILED");
				return new Response('Failed', 201);
			}
		}else{
			//CHECK USER ROLE IN COMPANY
			$company_role = getCompanyPosition($_SESSION['user_id']);
			if($company_role == 1 ){
				$company_id        = $result;
				$name              = $request->get('name');
				$tax_no            = $request->get('tax_no');
				$company_no        = $request->get('company_no');
				$company_fax       = $request->get('company_fax');
				$address           = $request->get('address');
				$city              = $request->get('city');
				$zip               = $request->get('zip');
				$state             = $request->get('state');
				$country           = $request->get('country');
				$reg_no            = $request->get('reg_no');
				$contact_person    = $request->get('contact_person');
				$contact_person_no = $request->get('contact_person_no');
				
				// BIND THE DATA
				$db->bind("name",$name);
				$db->bind("tax_no",$tax_no);
				$db->bind("company_no",$company_no);
				$db->bind("company_fax",$company_fax);
				$db->bind("address",$address);
				$db->bind("city",$city);
				$db->bind("zip",$zip);
				$db->bind("state",$state);
				$db->bind("country",$country);
				$db->bind("reg_no",$reg_no);
				$db->bind("contact_person",$contact_person);
				$db->bind("contact_person_no",$contact_person_no);
				$db->bind("company_id", $company_id);
				//UPDATE THE DATA
					$companyupdate = $db->query("UPDATE companies SET 
												 name               = :name,
												 tax_no             = :tax_no,
												 company_no         = :company_no,
												 company_fax        = :company_fax,
												 address            = :address,
												 city               = :city,
												 zip                = :zip,
												 state              = :state,
												 country            = :country,
												 reg_no             = :reg_no,
												 contact_person     = :contact_person,
												 contact_person_no  = :contact_person_no
												 WHERE company_id   = :company_id");
					
					$db->bind("company_id",$company_id);
					$db->bind("branch_address",$address);
					$db->bind("branch_city",$city);
					$db->bind("branch_zip",$zip);
					$db->bind("branch_state",$state);
					$db->bind("branch_country",$country);
					$db->bind("branch_name","HQ");
					
					$update_branch = $db->query("UPDATE branches SET
												 branch_address     =  :branch_address, 
												 branch_city        =  :branch_city, 
												 branch_zip         =  :branch_zip, 
												 branch_state       =  :branch_state, 
												 branch_country     =  :branch_country
												 WHERE company_id   =  :company_id 
												   and branch_name  =  :branch_name");
			
				if ($companyupdate) {
					$_SESSION["company_id"] = getCompany($_SESSION['user_id']);
					$_SESSION["branch_id"] = getBranch($_SESSION['user_id']);
					action_log($_SESSION['user_id'], "Edit Company : ID - " . $company_id , "SUCCESS");
					return new Response('Success', 200);
				} else {
					$_SESSION["company_id"] = getCompany($_SESSION['user_id']);
					$_SESSION["branch_id"] = getBranch($_SESSION['user_id']);
					action_log($_SESSION['user_id'], "Edit Company : ID - " . $company_id , "FAILED");
					return new Response('Failed', 201);
				}
			}else{
				$_SESSION["company_id"] = getCompany($_SESSION['user_id']);
				$_SESSION["branch_id"] = getBranch($_SESSION['user_id']);
				action_log($_SESSION['user_id'], "Edit Company : ID - " . $company_id , "FAILED");
				return new Response('Failed', 201);
			}
		}
    });
    $app->post('/company/edit/updatepic', function (Request $request) {
        global $db;
        global $app;
		//CHECK IF USER HAVE COMPANY
		$result = getCompany($_SESSION['user_id']);
		
		if($result == 0){
			//CHECK IF USER HAVE NO COMPANY
			//WE CREATE AUTOMATICALLY
			$create_companies = $db->query("INSERT INTO companies(company_id) VALUES (NULL);");
			
			
			$company_id = $db->lastInsertId();
			
			if($create_companies && $company_id){
				// BIND THE DATA
				$db->bind("company_id", $company_id);
				
				$create_branch = $db->query("INSERT INTO branches(company_id, branch_name) VALUES (:company_id, 'HQ');");
				$branch_id = $db->lastInsertId();
				
				$db->bind("company_id", $company_id);
				$db->bind("branch_id", $branch_id);
				$db->bind("user_id", $_SESSION['user_id']);
				$db->bind("position", "1");
				$enter_company = $db->query("INSERT INTO user_company(company_id, branch_id, user_id,position) VALUES (:company_id, :branch_id, :user_id, :position);");	
				
				if ($companyupdate && $create_branch) {
					$_SESSION["company_id"] = getCompany($_SESSION['user_id']);
					$_SESSION["branch_id"] = getBranch($_SESSION['user_id']);				
				}else{
					$_SESSION["company_id"] = getCompany($_SESSION['user_id']);
					$_SESSION["branch_id"] = getBranch($_SESSION['user_id']);	
				}
			}
		}
		$referer = $_SERVER["HTTP_REFERER"];
		if (!file_exists( __DIR__ . '/../../../uploads/company/'.$_SESSION['user_id'])) {
			mkdir( __DIR__ . '/../../../uploads/company/'.$_SESSION['user_id'], 0777, true);
		}
        $uploaddir =  __DIR__ . '/../../../uploads/company/'.$_SESSION['user_id'];
		$verifyimg = getimagesize($_FILES['image']['tmp_name']);
		$pattern = "#^(image/)[^\s\n<]+$#i";
		if(!preg_match($pattern, $verifyimg['mime'])){
			return new Response('Failed', 201);
		}
		
		$uploadfile = tempnam_sfx($uploaddir, ".tmp");
		
		if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
			$path =  'http://' . $_SERVER['HTTP_HOST'].'/uploads/company/'.$_SESSION['user_id']."/".basename($uploadfile);
			$uploaded_img = $_FILES['image']['tmp_name'];
			$data = file_get_contents($path);

			$logo = 'data:' . $_FILES['image']['type'] . ';base64,' . base64_encode($data);
			$logo_mime = $_FILES['image']['type'];
			$company_id = getCompany($_SESSION['user_id']);
			$db->bind("logo", $logo);
			$db->bind("logo_mime", $logo_mime);
			$db->bind("company_id", $company_id);
			
			return $logo;
			$imageupdate = $db->query("UPDATE companies SET logo = :logo, logo_mime= :logo_mime WHERE company_id = :company_id");
		}
		
		if ($imageupdate) {
			action_log($_SESSION['user_id'], "Edit Logo : ID - " . $company_id , "SUCCESS");
			delete_directory(__DIR__ ."/../../../uploads/");
			
			
		} else {
			action_log($_SESSION['user_id'], "Edit Logo : ID - " . $company_id , "FAILED");
			delete_directory(__DIR__ ."/../../../uploads/");
			
			//return $app->redirect($referer.'?failed');
		}
    });
	
    $app->post('/company/edit/updatebizreg', function (Request $request) {
        global $db;
        global $app;
		
		//CHECK IF USER HAVE COMPANY
		$result = getCompany($_SESSION['user_id']);
		
		if($result == 0){
			//CHECK IF USER HAVE NO COMPANY
			//WE CREATE AUTOMATICALLY
			$create_companies = $db->query("INSERT INTO companies(company_id) VALUES (NULL);");
			
			
			$company_id = $db->lastInsertId();
			
			if($create_companies && $company_id){
				// BIND THE DATA
				$db->bind("company_id", $company_id);
				
				$create_branch = $db->query("INSERT INTO branches(company_id, branch_name) VALUES (:company_id, 'HQ');");
				$branch_id = $db->lastInsertId();
				
				$db->bind("company_id", $company_id);
				$db->bind("branch_id", $branch_id);
				$db->bind("user_id", $_SESSION['user_id']);
				$db->bind("position", "1");
				$enter_company = $db->query("INSERT INTO user_company(company_id, branch_id, user_id,position) VALUES (:company_id, :branch_id, :user_id, :position);");	
				
				if ($companyupdate && $create_branch) {
					$_SESSION["company_id"] = getCompany($_SESSION['user_id']);
					$_SESSION["branch_id"] = getBranch($_SESSION['user_id']);				
				}else{
					$_SESSION["company_id"] = getCompany($_SESSION['user_id']);
					$_SESSION["branch_id"] = getBranch($_SESSION['user_id']);	
				}
			}
		}
		$referer = $_SERVER["HTTP_REFERER"];
		if (!file_exists( __DIR__ . '/../../../uploads/company/'.$_SESSION['user_id'])) {
			mkdir( __DIR__ . '/../../../uploads/company/'.$_SESSION['user_id'], 0777, true);
		}
        $uploaddir =  __DIR__ . '/../../../uploads/company/'.$_SESSION['user_id'];
		$verifyimg = getimagesize($_FILES['image2']['tmp_name']);
		$pattern = "#^(image/)[^\s\n<]+$#i";
		if(!preg_match($pattern, $verifyimg['mime'])){
			return new Response('Failed', 201);
		}
		
		$uploadfile = tempnam_sfx($uploaddir, ".tmp");
		
		if (move_uploaded_file($_FILES['image2']['tmp_name'], $uploadfile)) {
			$path =  'http://' . $_SERVER['HTTP_HOST'].'/uploads/company/'.$_SESSION['user_id']."/".basename($uploadfile);
			$data = file_get_contents($path);
			$reg_cert = 'data:' . $_FILES['image2']['type'] . ';base64,' . base64_encode($data);
			$reg_cert_mime = $_FILES['image2']['type'];
			$company_id = getCompany($_SESSION['user_id']);
			$db->bind("reg_cert", $reg_cert);
			$db->bind("reg_cert_mime", $reg_cert_mime);
			$db->bind("company_id", $company_id);
			
			$imageupdate2 = $db->query("UPDATE companies SET reg_cert = :reg_cert, reg_cert_mime= :reg_cert_mime WHERE company_id = :company_id");
		}
		
		if ($imageupdate2) {
			action_log($_SESSION['user_id'], "Edit Business Registration Certificate : ID - " . $company_id , "SUCCESS");
			delete_directory(__DIR__ ."/../../../uploads/");
			return $app->redirect($referer.'?success');
		} else {
			action_log($_SESSION['user_id'], "Edit Business Registration Certificate : ID - " . $company_id , "FAILED");
			delete_directory(__DIR__ ."/../../../uploads/");
			return $app->redirect($referer.'?failed');
		}
    });
	
    $app->get('/company/edit', function() {
        global $hooks;
		$hooks->add_action('global_css', 'editcompany_css');
        $hooks->add_action('global_js', 'editcompany_js');
        $hooks->add_action('the_title', "editcompany_title");
        the_head();
        include 'editcompany.tpl.php';
        the_footer();
        return "";
    });
    $app->get('/company', function() {
        global $hooks;
        $hooks->add_action('global_css', 'editcompany_css');
        $hooks->add_action('global_js', 'mycompany_js');
        $hooks->add_action('the_title', "mycompany_title");
        the_head();
        include 'mycompany.tpl.php';
        the_footer();
        return "";
    });	
	
	//STAFF CODE
	$app->get('/company/staff', function() {
        global $hooks;
		$hooks->add_action('global_css', 'editstaff_css');
        $hooks->add_action('global_js', 'editstaff_js');
        $hooks->add_action('the_title', "editcompany_title");
        the_head();
        include 'editstaff.tpl.php';
        the_footer();
        return "";
    });
	$app->post('/company/staff/list', function(Request $request)  {
        $curpage = $request->get('page');
        include 'editstaff.list.php';
        return '';
    });
	$app->post('/company/staff/add', function(Request $request) {
        global $db;
        $user_id = $request->get('user_id');
        $position = $request->get('position');
        $branch = $request->get('branch');
        $company_id = getCompany($_SESSION['user_id']);
        // CONDITIONAL FOR MAKE SURE BANK EXISTS
            // PREPARE
		$db->bind("user_id", $user_id);
		$db->bind("position", $position);
		$db->bind("branch", $branch);
		$db->bind("company_id", $company_id);
		// EXECUTE
		$row = $db->query("INSERT INTO user_company(user_id,company_id,branch_id,position) VALUES (:user_id,:company_id,:branch,:position)");
		if ($row) {
			$id = $db->lastInsertId();
			action_log($_SESSION['user_id'], "Add Staff : ID - " . $id , "SUCCESS");
			return new Response('SUCCESS', 200);
		}else{
			action_log($_SESSION['user_id'], "Add Staff : ID - " . $id , "FAILED");
			return new Response('Failed', 201);
		}
       
    });
	$app->post('/company/staff/delete', function(Request $request) {
        global $db;
        $id = $request->get('id');
		
		// PREPARE
		$db->bind("id", $id);
		// EXECUTE
		$row = $db->query("DELETE FROM user_company WHERE id = :id");
		if ($row) {
			action_log($_SESSION['user_id'], "Delete Staff : ID - " . $id , "SUCCESS");
			return new Response('SUCCESS', 200);
		}else{
			action_log($_SESSION['user_id'], "Delete Staff : ID - " . $id , "FAILED");
			return new Response('Failed', 201);
		}
       
    });
	$app->post('/company/staff/get-data', function (Request $request) {
        global $db;
        $id = $request->get('id');
        // Bind the data
        $html = getModalStaff($id);
		
		return $html;
    });
	$app->post('/company/staff/edit', function(Request $request) {
        global $db;
        $id = $request->get('id');
        $position = $request->get('position');
        $branch = $request->get('branch');
		
		// PREPARE
		$db->bind("id", $id);
		$db->bind("position", $position);
		$db->bind("branch", $branch);
		echo $id;
		// EXECUTE
		$row = $db->query("UPDATE user_company SET branch_id = :branch, position = :position WHERE id = :id");
		if ($row) {
			action_log($_SESSION['user_id'], "Edit Staff : ID - " . $id , "SUCCESS");
			return new Response('SUCCESS', 200);
		}else{
			action_log($_SESSION['user_id'], "Edit Staff : ID - " . $id , "FAILED");
			return new Response('Failed', 201);
		}
       
    });
    
}
