<?php 
error_reporting(E_ALL);
session_start();
require 'functions.php';

// cek cookie
if (isset($_COOKIE['id']) && isset($_COOKIE['key'])) {
	$id = $_COOKIE['id'];
	$key = $_COOKIE['key'];

	$result = mysqli_query($conn, "SELECT username FROM user WHERE id = $id");
	$row = mysqli_fetch_assoc($result);

	if ($key === hash('sha256', $row['username'])) {
		$_SESSION['login'] = true;
	}
}

if (isset($_SESSION["login"])) {
	header("Location: index.php");
	exit;
}

if (isset($_POST["login"])) {
	$username = $_POST["username"];
	$password = $_POST["password"];

	$result = mysqli_query($conn, "SELECT * FROM user WHERE username = '$username'");

	if (mysqli_num_rows($result) === 1) {
		$row = mysqli_fetch_assoc($result);
		if (password_verify($password, $row["password"])) {
			$_SESSION["logkanwil"] = $row['kanwil'];
			$_SESSION["username"] = $row['username'];
			$_SESSION["login"] = true;
			header("Location: index.php");
			exit;
		}
	}
	$error = true;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Login</title>
	<link rel="shortcut icon" href="siswa.png">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
	<style>
		body {
			font-family: Arial, sans-serif;
			padding: 20px;
			background: #f4f4f4;
		}
		.container {
			max-width: 360px;
			margin: auto;
			background: white;
			padding: 20px;
			border-radius: 10px;
			box-shadow: 0 0 10px rgba(0,0,0,0.1);
		}
		h1 {
			text-align: center;
			font-size: 22px;
		}
		label {
			font-size: 14px;
		}
		input {
			width: 100%;
			padding: 8px;
			margin: 6px 0 12px;
			font-size: 14px;
		}
		button {
			width: 100%;
			font-size: 14px;
			padding: 10px;
		}
		@media screen and (max-width: 400px) {
			h1 {
				font-size: 18px;
			}
			input, button {
				font-size: 12px;
				padding: 8px;
			}
		}
	</style>
</head>
<body>

<div class="container">
	<h1>Login First</h1>

	<?php if (isset($error)) : ?>
		<div class="alert alert-danger" role="alert" style="font-size: 14px;">
			Username / password salah
		</div>
	<?php endif; ?>

	<form action="" method="post">
		<div class="form-group">
			<label for="username">Username:</label>
			<input type="text" name="username" id="username" autocomplete="off" onkeyup="this.value = this.value.toUpperCase()" required autofocus>
		</div>
		<div class="form-group">
			<label for="password">Password:</label>
			<input type="password" name="password" id="password" onkeyup="this.value = this.value.toUpperCase()" required>
		</div>
		<button type="submit" class="btn btn-danger" name="login">Login</button>
	</form>
</div>

</body>
</html>
