<?php
// Database configuration
include "config.php";

try {
    // Connect to the database
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Fetch unique available dates from the database
    $dateQuery = "
        SELECT DISTINCT 
            CONCAT(year, '-', LPAD(month, 2, '0'), '-', LPAD(day, 2, '0')) AS full_date 
        FROM att_table 
        ORDER BY full_date DESC";
    $dateStmt = $pdo->prepare($dateQuery);
    $dateStmt->execute();
    $dates = $dateStmt->fetchAll(PDO::FETCH_COLUMN);

} catch (PDOException $e) {
    echo "<p>Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Attendance Logs</title>
    <style>
		.logo {
			height: 40px; /* Adjust the height of the logo */
			margin-right: auto; /* Add space between the logo and text */
		}
		html, body {
		  height: 100%;
		  margin: 0;
		  display: flex;
		  flex-direction: column;
		}
        h1 {
            color: #333;
            font-size: 20px;
            margin-bottom: 5px;
        }
		body {
		  font-family: Arial, sans-serif;
		  background-color: #f2f2f2;
		  padding: 1px;
		  text-align: center;
		}

		#date-selector {
		  margin: 2px;
		  width: 160px;
		  padding: 5px;
		  font-size: 15px;
		  border: 1px solid #4CAF50; /* Green border */
		  border-radius: 5px;
		  background-color: white;
		  color: black;
		  cursor: pointer;
		}

		#log-display {
		  margin-top: 2px;
		  text-align: center;
		}

		.table-container {
		  flex: 1;
		  overflow-y: auto;
		  max-height: calc(100vh - 140px); /* Adjusts remaining height */
		  border: 1px solid #ccc;
		}

		#log-table {
		  width: 100%;
		  border-collapse: collapse;
		  font-size: 12px;
		}

		#log-table thead {
		  position: sticky;
		  top: 0;
		  background-color: white;
		  z-index: 100;
		  
		}

		#log-table th, #log-table td {
		  padding: 5px;
		  border: 1px solid #ddd;
		  text-align: left;
		}

		#log-table tbody tr:nth-child(odd) {
		  background-color: #f9f9f9;
		}

		#log-table tbody tr:nth-child(even) {
		  background-color: #ffffff;
		}
		/* Set max widths for all columns */
		#log-table th:nth-child(1), #log-table td:nth-child(1) { max-width: 150px; } /* Designation */
		#log-table th:nth-child(2), #log-table td:nth-child(2) { max-width: 150px; } /* Attendance ID */
        footer {
            text-align: center;
            margin-top: 2px;
            font-size: 12px;
            color: #666;
        }
		button {
            margin: 1px;
			margin-bottom: 1px;
            padding: 5px;
			width: 200px;
            font-size: 14px;
            cursor: pointer;
			border-radius: 5px;
			border: 1px solid #4CAF50; /* Green border */
			background-color: #007bff; /* Blue color */
			font-weight: bold;
			color: white;
        }
		.button-container {
			display: flex;
			justify-content: center;
			margin-top: 2px; /* Adjust spacing if needed */
		}
    </style>
    <script>
		function fetchLogsByDate() {
			const selectedDate = document.getElementById('date-selector').value;
			const logTableBody = document.getElementById('log-table').querySelector('tbody');

			// Show loading message
			logTableBody.innerHTML = `<tr><td colspan="5">Loading logs...</td></tr>`;

			fetch(`fetch_logs_by_date.php?date=${selectedDate}`)
				.then(response => response.json())
				.then(logs => {
					logTableBody.innerHTML = ''; // Clear previous logs

					if (logs.length > 0) {
						logs.forEach(log => {
							const row = document.createElement('tr');
							row.innerHTML = `
								<td>${log.logDate}</td>
								<td>${log.Designation || 'N/A'}</td>
								<td>${log.Name || log.attendanceID}</td>
								<td>${log.logType}</td>
								<td>${log.timeString}</td>
							`;
							logTableBody.appendChild(row);
						});
					} else {
						logTableBody.innerHTML = `<tr><td colspan="5">No records found for this date.</td></tr>`;
					}
				})
				.catch(error => {
					console.error('Error fetching logs:', error);
					logTableBody.innerHTML = `<tr><td colspan="5">Error loading logs. Please try again.</td></tr>`;
				});
		}

		document.addEventListener('DOMContentLoaded', () => {
			fetchLogsByDate(); // Fetch logs when the page loads
		});
    </script>
</head>
<body>

    <div id="log-display">
		<div>
			<h1><img src="logo.png" alt="Logo" class="logo">CNSAT Attendance Logs</h1>
			<label for="date-selector"><strong>Select Date:</strong></label>
			<select id="date-selector" onchange="fetchLogsByDate()">
				<option value="all">All Dates</option> <!-- All Dates option -->
				<?php
				$currentDate = date('Y-m-d'); // Get today's date
				foreach ($dates as $date):
					if (strtotime($date) >= strtotime('2025-02-20')): // Filter dates
						$selected = ($date === $currentDate) ? 'selected' : ''; // Default to today
				?>
					<option value="<?= $date ?>" <?= $selected ?>><?= $date ?></option>
				<?php endif;
				endforeach; ?>
			</select>
		</div>
		<div class="table-container">
			<table id="log-table">
				<thead>
					<tr>
						<th>Date</th>
						<th>Section</th>
						<th>Name / ID</th>
						<th>Log Type</th>
						<th>Time</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<td colspan="5">Select a date to load logs.</td>
					</tr>
				</tbody>
			</table>

		</div>
    </div>
	
    <footer>
			<button id="download-csv" onclick="window.location.href='download_csv.php'">Download Raw Logs in CSV</button> &copy; 2025 Sir Manny
    </footer>
</body>
</html>
