<?php
session_start();
require_once 'config.php';

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
	header('location: login.php');
	exit;
}

$user_id = $_SESSION['id'];
$username = $_SESSION['username'];
$today = date('Y-m-d');
$entry_err = $shubank = $points = '';

// Handle add entry
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_entry'])) {
	$shubank = trim($_POST['shubank']);
	$points = trim($_POST['points']);
	if (!ctype_digit($shubank) || $shubank < 1 || $shubank > 100) {
		$entry_err = 'Shubank must be an integer between 1 and 100.';
	} elseif (!ctype_digit($points) || $points < 10 || $points > 1000) {
		$entry_err = 'Points must be an integer between 10 and 1000.';
	} else {
		$sql = 'INSERT INTO entries (username, shubank, points, entry_date) VALUES (?, ?, ?, ?)';
		if ($stmt = mysqli_prepare($link, $sql)) {
			mysqli_stmt_bind_param($stmt, 'siis', $username, $shubank, $points, $today);
			mysqli_stmt_execute($stmt);
			mysqli_stmt_close($stmt);
		}
	}
}

// Handle update entry
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_entry'])) {
	$entry_id = intval($_POST['entry_id']);
	$shubank = trim($_POST['shubank']);
	$points = trim($_POST['points']);
	if (!ctype_digit($shubank) || $shubank < 1 || $shubank > 100) {
		$entry_err = 'Shubank must be an integer between 1 and 100.';
	} elseif (!ctype_digit($points) || $points < 10 || $points > 1000) {
		$entry_err = 'Points must be an integer between 10 and 1000.';
	} else {
		   $sql = 'UPDATE entries SET shubank=?, points=? WHERE id=? AND username=? AND entry_date=?';
		   if ($stmt = mysqli_prepare($link, $sql)) {
			   mysqli_stmt_bind_param($stmt, 'iiiis', $shubank, $points, $entry_id, $username, $today);
			   mysqli_stmt_execute($stmt);
			   mysqli_stmt_close($stmt);
		   }
	}
}

// Fetch today's entries
$entries = [];
$sql = 'SELECT id, username, shubank, points FROM entries WHERE username=? AND entry_date=?';
if ($stmt = mysqli_prepare($link, $sql)) {
	mysqli_stmt_bind_param($stmt, 'ss', $username, $today);
	mysqli_stmt_execute($stmt);
	$result = mysqli_stmt_get_result($stmt);
	while ($row = mysqli_fetch_assoc($result)) {
		$entries[] = $row;
	}
	mysqli_stmt_close($stmt);
}

// Calculate sum of points for today
$points_sum = 0;
foreach ($entries as $entry) {
	$points_sum += $entry['points'];
}
$_SESSION['points_sum'] = $points_sum;

// Handle confirm entries
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm_entries'])) {
	$sql = 'INSERT INTO payment (username, totalpoints, pay_date) VALUES (?, ?, ?)';
	if ($stmt = mysqli_prepare($link, $sql)) {
		mysqli_stmt_bind_param($stmt, 'sis', $username, $points_sum, $today);
		mysqli_stmt_execute($stmt);
		mysqli_stmt_close($stmt);
		header('location: thankyou.php');
		exit;
	}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Welcome</title>
	<style>
		body{ font: 14px sans-serif; }
		.wrapper{ width: 600px; padding: 20px; margin: auto; }
		.error{ color: red; }
		table { width: 100%; border-collapse: collapse; margin-top: 20px; }
		th, td { border: 1px solid #ccc; padding: 8px; text-align: center; }
		th { background: #eee; }
		.top-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
	</style>
</head>
<body>
	<div class="wrapper">
		<div class="top-bar">
			<div><b><?php echo htmlspecialchars($username); ?></b> | Total Points: <b><?php echo $points_sum; ?></b></div>
			<div><a href="logout.php">Logout</a></div>
		</div>
		<h2>Add Entry</h2>
		<?php if(!empty($entry_err)) echo '<div class="error">'.$entry_err.'</div>'; ?>
		<form method="post">
			<input type="number" name="shubank" min="1" max="100" placeholder="Shubank (1-100)" required>
			<input type="number" name="points" min="10" max="1000" placeholder="Points (10-1000)" required>
			<input type="submit" name="add_entry" value="Add Entry">
		</form>

		<h3>Today's Entries</h3>
		<table>
			<tr><th>Shubank</th><th>Points</th><th>Action</th></tr>
			<?php foreach ($entries as $entry): ?>
				<tr>
					<form method="post">
						<td><input type="number" name="shubank" min="1" max="100" value="<?php echo $entry['shubank']; ?>" required></td>
						<td><input type="number" name="points" min="10" max="1000" value="<?php echo $entry['points']; ?>" required></td>
						<td>
							<input type="hidden" name="entry_id" value="<?php echo $entry['id']; ?>">
							<input type="submit" name="update_entry" value="Update">
						</td>
					</form>
				</tr>
			<?php endforeach; ?>
		</table>

		<form method="post" style="margin-top:20px;">
			<input type="submit" name="confirm_entries" value="Confirm Entries">
		</form>
	</div>
</body>
</html>
