	<?php
	/**
	* Created by PhpStorm.
	* User: ahmad
	* Date: 20/08/2019
	* Time: 11:48 AM
	* Location profil -> daftar
	*/

	require_once("../connection.php");
	$tanggal	= gmdate("Y-m-d H:i:s", time()+60*60*7);
			
			$sift=mysqli_real_escape_string($connect, $_POST['sift']);
			$cash_awal=mysqli_real_escape_string($connect, $_POST['modal_awal']);
			$key = mysqli_real_escape_string($connect, $_POST["key"]);
			
			
	$getusers	= mysqli_query($connect,"SELECT * FROM users WHERE id_session='$key'");
	$u	   		= mysqli_fetch_array($getusers);
	$amount   	= mysqli_num_rows($getusers);
	
	$masterakun = mysqli_query($connect,"SELECT * FROM users WHERE phone_number='$u[master]'");
	$m=mysqli_fetch_array($masterakun);
	
	if ($amount > 0){
		
		
	$today		= gmdate("Y-m-d 00:00:00", time()+60*60*7);
	$endtoday	= gmdate("Y-m-d 23:59:00", time()+60*60*7);
	$query = "SELECT * FROM intial WHERE cashier_id='$u[phone_number]' AND create_at>='$today' AND shift='$sift' AND create_at<='$endtoday'";
	$hasil = mysqli_query($connect,$query);
	if(mysqli_num_rows($hasil) > 0 ){		
	
 $json = array(
    'status' 	=> 'true',
    'errCode' 	=> '02',
	'msg' 		=> 'You have closed the shift today, please enter with the next shift or log in tomorrow'
   );

    echo json_encode($json);	

	
	
	}else{
	
	
 $nama = $u['full_name'];
	$arr = explode(' ', $nama);
	$singkatan = "";
	foreach($arr as $kata)
	{
	$singkatan .= substr($kata, 0, 1);
	}
		$kode= strtoupper($singkatan);
	
	
	function create_random($length)
{
    $data = 'ABCDEFGHIJKLMNOPQRSTU1234567890';
    $string = '';
    for($i = 0; $i < $length; $i++) {
        $pos = rand(0, strlen($data)-1);
        $string .= $data{$pos};
    }
    return $string;
}

$kodekey=create_random(5);
$code = "$kode-$kodekey";


	mysqli_query($connect,"INSERT INTO intial(flag,
								  user,
								  id_store,
								  code,
								  shift,
								  initial_date,
								  cashier_id,
								  cash_awal,
								  create_at) 
                    VALUES('I',
						   '$m[phone_number]',
						   '$u[id_store]',
						   '$code',
						   '$sift',
						   '$tanggal',
						   '$u[phone_number]',
						   '$cash_awal',
						   '$tanggal')");
						   
	mysqli_query($connect,"UPDATE users SET initial = 'I',
											shift   = '$code'
										WHERE phone_number = '$u[phone_number]'");

	
	$json = array(
    'status' 	=> 'true',
    'errCode' 	=> '01',
	'msg' 		=> 'Sukses, silahkan transaksi'
	);
	
    echo json_encode($json);	
	}


	}else{
	
	$json = array(
    'status' 	=> 'true',
    'errCode' 	=> '00',
	'msg' 		=> 'User Not Found'
	);

    echo json_encode($json);	
	}
	?>