<?php
	$servername = "localhost"; $ip_address = $_SERVER['REMOTE_ADDR'];
	if($ip_address == "::1" || $ip_address == "192.168.0.189" || $ip_address == "192.168.0.119"){
		$username = "root"; $password = ""; $database = "wdfc2023";

		//test mode switcher
		$testMode = true; $inputRequire = "";
	}else{
		$username = "msdeafor_wdfc2023_admin"; $password = "Wdfc2023"; $database = "msdeafor_wdfc2023";
		
		//test mode switcher
		$testMode = false; $inputRequire = "REQUIRED";
	}

	// Create connection
	$conn = new mysqli($servername, $username, $password, $database);

	// Check connection
	if ($conn->connect_error) {	
		die("Connection failed: " . $conn->connect_error);
	}

	session_start();
	ob_start();	

	$roundList = array(
		1 => 'A',
		2 => 'B',
		3 => 'C',
		4 => 'D',
		5 => 'E'
	);

	$roles = array(
        1 => 'STRIKER',
        2 => 'MIDFIELDER',
        3 => 'DEFENDER',
        4 => 'GOALKEEPER'
    );

	// Get the current requested URL
	$currentURL = $_SERVER['REQUEST_URI'];

	// Check if the current URL is equal to the URL you want to redirect from
	if ($currentURL === "/admin/v2/index.php"){
		// Define the URL you want to redirect to
		$redirectURL = "https://wdfc2023.msdeaf.org.my/admin/v2/index.php?page=news";
		
		// Perform the redirect
		header("Location: $redirectURL");
		exit; // Ensure that no more code is executed after the redirect
	}

if(basename($_SERVER['PHP_SELF']) != "login.php"){
		if($_SESSION['admin'] == NULL){
			header("Location: login.php");}}

function generateRandomString($length) {
    $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

function cleanizeContact($number){
	return str_replace("+","",str_replace(" ","",str_replace("-","",$number)));
}

function generateRandomNumber($length) {
    $characters = '0123456789';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

//IP ADDRESS
$ipAddress = $_SERVER['REMOTE_ADDR'];

//TELEGRAM


function sendMessage($messaggio,$chatID) {
	$token = "100033216:AAFpUx-vJZFa_8cFuw6RBmxGjqcN1spf3bU";
	if(!$chatID){$chatID = "-469914267";}
	
	echo "sending message to " . $chatID . "\n";

	$url = "https://api.telegram.org/bot" . $token . "/sendMessage?chat_id=" . $chatID;
	$url = $url . "&text=" . urlencode($messaggio);
	$ch = curl_init();
	$optArray = array(
			CURLOPT_URL => $url,
			CURLOPT_RETURNTRANSFER => true
	);
	curl_setopt_array($ch, $optArray);
	$result = curl_exec($ch);
	curl_close($ch);
	return $result;
}

function sendPhoto($chatID, $photoUrl, $token) {
	echo "sending message to " . $chatID . "\n";

	$url = "https://api.telegram.org/bot" . $token . "/sendPhoto?chat_id=" . $chatID;
	$url = $url . "&photo=" . $photoUrl;
	$ch = curl_init();
	$optArray = array(
			CURLOPT_URL => $url,
			CURLOPT_RETURNTRANSFER => true
	);
	curl_setopt_array($ch, $optArray);
	$result = curl_exec($ch);
	curl_close($ch);
	return $result;
}

function getDetailFromTable($tableName,$rowID){
		global $conn;
		
		$result = mysqli_query($conn, "SHOW COLUMNS FROM $tableName");
		while($row = mysqli_fetch_assoc($result)){
			$column[] = $row['Field'];
		} 
		
		$result = mysqli_query($conn, "SELECT * FROM $tableName WHERE $column[0]=$rowID");
		$array = mysqli_fetch_array($result);
		
		return $array;
	}
	
function selectDropmenu($fromTable, $fromValue){
		if($fromTable == $fromValue){ return "SELECTED"; }
	}

function getCustomerDetails($id){
		global $conn;
		$result = mysqli_query($conn, "SELECT * FROM customers WHERE cu_id=$id");
		$row = mysqli_fetch_assoc($result);
	
		return array($row['cu_id'],$row['cu_name'],$row['cu_contact'],$row['cu_email'],$row['a_id'],$row['timestamp']);
	}

function getItemDetails($id){
		global $conn;
		$result = mysqli_query($conn, "SELECT * FROM items WHERE it_id=$id");
		$row = mysqli_fetch_assoc($result);
	
		return array($row['it_id'],$row['it_title'],$row['it_code'],$row['it_wholesale_price'],$row['it_selling_price'],$row['it_qty'],$row['it_details'],$row['a_id'],$row['timestamp']);
	}

function getPlatformDetails($id){
		global $conn;
		$result = mysqli_query($conn, "SELECT * FROM platform WHERE pf_id=$id");
		$row = mysqli_fetch_assoc($result);
	
		return array($row['pf_id'],$row['pf_title'],$row['pf_link'],$row['a_id'],$row['timestamp']);
	}

function totalItemsPriceInCart($id){
		global $conn; $total=0;
		$result = mysqli_query($conn, "SELECT * FROM cart WHERE or_id=$id");
		while($row = mysqli_fetch_assoc($result)){
			$amount = $row['ct_price']*$row['ct_qty']; $total = $total + $amount;
		}
	
		return $total;
	}

function hide($level,$expectedLevel){
		if($level>$expectedLevel){$title="hidden";}else{$title="";} return $title;
	}

function statusInTitle($level,$expectedLevel){
		if($level>=$expectedLevel){$title="Approved";}else{$title="Pending";} return $title;
	}

function disable($level,$expectedLevel){
		if($level<$expectedLevel){$title="disabled";}else{$title="";} return $title;
	}
	//affected page : guests.php guest_standard.php guest_deluxe.php gest_penthouse.php guest_villa.php payments.php

function totalSold(){
	global $conn; $total = 0;
	$result = mysqli_query($conn, "SELECT * FROM cart");
	while($row = mysqli_fetch_assoc($result)){
		$total = $total + ($row['ct_qty'] * $row['ct_price']);
	}

	return $total;
}

function totalSoldToday(){
	global $conn; $total = 0;
	$result = mysqli_query($conn, "SELECT * FROM cart WHERE DATE(timestamp) = CURDATE()");
	while($row = mysqli_fetch_assoc($result)){
		$total = $total + ($row['ct_qty'] * $row['ct_price']);
	}

	return $total;
}

function totalOrder(){
	global $conn; $total = 0;
	$result = mysqli_query($conn, "SELECT COUNT(or_id) AS totalOrder FROM orders");
	$row = mysqli_fetch_assoc($result);
	
	return $row['totalOrder'];
}

function totalOrderToday(){
	global $conn; $total = 0;
	$result = mysqli_query($conn, "SELECT COUNT(or_id) AS totalOrder FROM orders WHERE or_date=CURRENT_DATE");
	$row = mysqli_fetch_assoc($result);
	
	return $row['totalOrder'];
}

function totalDeliveryPrice(){
	global $conn; $total = 0;
	$result = mysqli_query($conn, "SELECT SUM(DP.dp_price) as totalDeliveryPrice FROM order_delivery AS OD LEFT JOIN delivery_price AS DP ON OD.dp_id=DP.dp_id");
	$row = mysqli_fetch_assoc($result);
	
	return $row['totalDeliveryPrice'];
}

function totalDeliveryPriceToday(){
	global $conn; $total = 0;
	$result = mysqli_query($conn, "SELECT SUM(DP.dp_price) as totalDeliveryPrice FROM order_delivery AS OD LEFT JOIN delivery_price AS DP ON OD.dp_id=DP.dp_id WHERE DATE(OD.timestamp) = CURDATE()");
	$row = mysqli_fetch_assoc($result);
	
	return $row['totalDeliveryPrice'];
}

function totalExpenses(){
	global $conn; $total = 0;
	$result = mysqli_query($conn,"SELECT SUM(ex_price) AS totalExpenses FROM expenses");
	$row = mysqli_fetch_assoc($result);
	
	return $row['totalExpenses'];
}

function totalExpensesToday(){
	global $conn; $total = 0;
	$result = mysqli_query($conn,"SELECT SUM(ex_price) AS totalExpenses FROM expenses WHERE DATE(timestamp) = CURDATE()");
	$row = mysqli_fetch_assoc($result);
	
	return $row['totalExpenses'];
}

function totalSpent($adminID){
	global $conn;
	$result = mysqli_query($conn,"SELECT SUM(ex_price) AS totalAmount FROM expenses WHERE ex_a_id=$adminID");
	$row = mysqli_fetch_assoc($result);
	if(!$row['totalAmount']){return 0.00;}else{return $row['totalAmount'];}
}

function totalSoldByDate($date){
	global $conn;
	$result = mysqli_query($conn,"SELECT SUM(ct_qty*ct_price) AS sumTotal FROM cart AS CT LEFT JOIN orders AS OD ON CT.or_id=OD.or_id WHERE OD.or_date='$date'");
	$row = mysqli_fetch_assoc($result);
	
	return $row['sumTotal'];
}

function totalDeliveryCost($date){
	global $conn;
	$result = mysqli_query($conn,"SELECT SUM(dp_price) AS sumTotal FROM order_delivery AS OD LEFT JOIN delivery_price AS DP ON OD.dp_id=DP.dp_id WHERE OD.timestamp like '$date%'");
	$row = mysqli_fetch_assoc($result);
	
	return $row['sumTotal'];
}

function itemAvailability($id){
	global $conn;
	$result = mysqli_query($conn,"SELECT * FROM items WHERE it_id=$id");
	$row = mysqli_fetch_assoc($result);
	
	return $row['it_qty'];
}
?>

<script>
	function confirmBtn(e){if(confirm(e)){yourformelement.submit();}else{return false;}}
</script>