<?php
header("Access-Control-Allow-Origin: *");
include 'conexion.php';
$table = 'users';

$getJson = file_get_contents('php://input');
$json = json_decode($getJson);
$phone = $json->phone;
$password = $json->password;
$fcmToken = $json->fcmToken;
// Cek apakah username dan password sesuai
$sql = $connect->query("SELECT * FROM " . $table . " WHERE phone='" . $phone . "' and password=md5('" . $password . "')");

$ceklogin = $sql->num_rows;

$hasil = array();

while ($fetchSql = $sql->fetch_assoc()) {
	$hasil[] = $fetchSql;
	$sql = $connect->query("SELECT * FROM userd WHERE username='" . $hasil[0]['username'] . "'");
	while ($fetchSql = $sql->fetch_assoc()) {
		$hasil[] = $fetchSql;
	}
}

if ($ceklogin > 0) {
	$sqlChecking = $connect->query("SELECT * FROM user_tokens WHERE username = '" . $hasil[0]['username'] . "' and token = '$fcmToken'");
	if ($sqlChecking->num_rows == 0) {
		$updateTokenQuery = "UPDATE user_tokens SET is_active = 0 WHERE username = '" . $hasil[0]['username'] . "'";
		$connect->query($updateTokenQuery);

		// Insert token FCM baru atau update jika token tersebut sudah ada
		$insertTokenQuery = "INSERT INTO user_tokens (username, token, is_active) 
                        VALUES ('" . $hasil[0]['username'] . "', '" . $fcmToken . "', 1)";

		$connect->query($insertTokenQuery);
	}
	if ($hasil[0]['default_address'] == "1" or $hasil[0]['default_address'] == null) {
		$hasil[0]['default_address'] = null;
	}


	// Response untuk login berhasil
	$response = array(
		'error' => false,
		'message' => null,
		'data' => $hasil
	);
} else {
	// Response untuk login gagal
	$response = array(
		'error' => true,
		'message' => 'Nomor Telephone/Password Salah',
		'data' => null
	);
}

header('Content-Type: application/json');
echo json_encode($response);