<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}

require_once 'connectiondb.php';

$errors = [];
$success_message = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// Fetch batches for selection
$stmt = $pdo->query("SELECT * FROM batches ORDER BY batch_name");
$batches = $stmt->fetchAll(PDO::FETCH_ASSOC);

$selected_batch_id = $_POST['batch_id'] ?? ($_GET['batch_id'] ?? '');
$attendance_date = $_POST['attendance_date'] ?? ($_GET['attendance_date'] ?? date('Y-m-d'));
$students = [];
$attendance_records = [];

// Always load attendance data if batch and date are set
if (!empty($selected_batch_id) && !empty($attendance_date)) {
    // Fetch students enrolled in the batch
    $stmtStudents = $pdo->prepare("
        SELECT s.id, s.student_id, s.name
        FROM batch_enrollments be
        JOIN students s ON be.student_id = s.id
        WHERE be.batch_id = ?
        ORDER BY s.name
    ");
    $stmtStudents->execute([$selected_batch_id]);
    $students = $stmtStudents->fetchAll(PDO::FETCH_ASSOC);

    // Fetch attendance records for the date and batch
    $stmtAttendance = $pdo->prepare("
        SELECT * FROM attendance
        WHERE batch_id = ? AND attendance_date = ?
    ");
    $stmtAttendance->execute([$selected_batch_id, $attendance_date]);
    $attendance_records_raw = $stmtAttendance->fetchAll(PDO::FETCH_ASSOC);

    // Map attendance by student_id
    foreach ($attendance_records_raw as $record) {
        $attendance_records[$record['student_id']] = $record;
    }
}

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_attendance'])) {
        $selected_batch_id = $_POST['batch_id'] ?? '';
        $attendance_date = $_POST['attendance_date'] ?? '';
        $statuses = $_POST['status'] ?? [];
        $student_ids = $_POST['student_id'] ?? [];

        if (empty($selected_batch_id) || empty($attendance_date)) {
            $errors[] = "Batch and attendance date are required.";
        } else {
            try {
                $pdo->beginTransaction();

                foreach ($student_ids as $student_id) {
                    $status = $statuses[$student_id] ?? 'present';

                    // Check if attendance record exists
                    $stmtCheck = $pdo->prepare("SELECT id FROM attendance WHERE student_id = ? AND batch_id = ? AND attendance_date = ?");
                    $stmtCheck->execute([$student_id, $selected_batch_id, $attendance_date]);
                    $existing = $stmtCheck->fetch(PDO::FETCH_ASSOC);

                    if ($existing) {
                        // Update existing record
                        $stmtUpdate = $pdo->prepare("UPDATE attendance SET status = ?, updated_at = NOW() WHERE id = ?");
                        $stmtUpdate->execute([$status, $existing['id']]);
                    } else {
                        // Insert new record
                        $stmtInsert = $pdo->prepare("INSERT INTO attendance (student_id, batch_id, attendance_date, status) VALUES (?, ?, ?, ?)");
                        $stmtInsert->execute([$student_id, $selected_batch_id, $attendance_date, $status]);
                    }
                }

                $pdo->commit();
                $success_message = "Attendance updated successfully.";

                // Reload attendance data
                header("Location: admin_attendance.php?batch_id=" . urlencode($selected_batch_id) . "&attendance_date=" . urlencode($attendance_date));
                exit;

            } catch (PDOException $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                $errors[] = "Error updating attendance: " . $e->getMessage();
            }
        }
    }

$month = $_POST['month'] ?? $_GET['month'] ?? date('Y-m');
$month_start = $month . '-01';
$month_end = date('Y-m-t', strtotime($month_start));
$monthly_attendance = [];

if (!empty($selected_batch_id)) {
    // Fetch students enrolled in the selected batch
    $stmtStudentsBatch = $pdo->prepare("
        SELECT s.id, s.student_id, s.name
        FROM batch_enrollments be
        JOIN students s ON be.student_id = s.id
        WHERE be.batch_id = ?
        ORDER BY s.name
    ");
    $stmtStudentsBatch->execute([$selected_batch_id]);
    $batch_students = $stmtStudentsBatch->fetchAll(PDO::FETCH_ASSOC);

    // Fetch attendance records for the month and batch
    $stmtMonthlyAttendance = $pdo->prepare("
        SELECT student_id, attendance_date, status
        FROM attendance
        WHERE attendance_date BETWEEN ? AND ? AND batch_id = ?
        ORDER BY attendance_date, student_id
    ");
    $stmtMonthlyAttendance->execute([$month_start, $month_end, $selected_batch_id]);
    $attendance_data = $stmtMonthlyAttendance->fetchAll(PDO::FETCH_ASSOC);

    // Organize attendance data by student and date
    foreach ($batch_students as $student) {
        $monthly_attendance[$student['id']] = [
            'student_id' => $student['student_id'],
            'name' => $student['name'],
            'attendance' => []
        ];
    }
    foreach ($attendance_data as $record) {
        if (isset($monthly_attendance[$record['student_id']])) {
            $monthly_attendance[$record['student_id']]['attendance'][$record['attendance_date']] = $record['status'];
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Admin - Attendance</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container my-4">
    <h2>Manage Attendance</h2>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <ul>
                <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if ($success_message): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($success_message); ?></div>
    <?php endif; ?>

    <form method="POST" action="admin_attendance.php" class="mb-4">
        <div class="row g-3 align-items-center">
            <div class="col-auto">
                <label for="batch_id" class="col-form-label">Batch</label>
            </div>
            <div class="col-auto">
                <select name="batch_id" id="batch_id" class="form-select" required>
                    <option value="">Select Batch</option>
                    <?php foreach ($batches as $batch): ?>
                        <option value="<?php echo htmlspecialchars($batch['id']); ?>" <?php echo ($batch['id'] == $selected_batch_id) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($batch['batch_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-auto">
                <label for="attendance_date" class="col-form-label">Date</label>
            </div>
            <div class="col-auto">
                <input type="date" name="attendance_date" id="attendance_date" class="form-control" value="<?php echo htmlspecialchars($attendance_date); ?>" required />
            </div>
            <div class="col-auto">
                <button type="submit" name="load_attendance" class="btn btn-primary">Load</button>
            </div>
        </div>
    </form>

    <?php if (!empty($students)): ?>
        <form method="POST" action="admin_attendance.php">
            <input type="hidden" name="batch_id" value="<?php echo htmlspecialchars($selected_batch_id); ?>" />
            <input type="hidden" name="attendance_date" value="<?php echo htmlspecialchars($attendance_date); ?>" />
            <table class="table table-bordered table-striped">
                <thead>
                    <tr>
                <th>Student ID</th>
                <th>Name</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $is_sunday = (date('w', strtotime($attendance_date)) == 0);
            if ($is_sunday) {
                // If Sunday, show holiday for all students
                foreach ($students as $student): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($student['student_id']); ?></td>
                        <td><?php echo htmlspecialchars($student['name']); ?></td>
                        <td colspan="1" class="text-center text-primary">Holiday</td>
                    </tr>
                <?php endforeach;
            } else {
                foreach ($students as $student): 
                    $att = $attendance_records[$student['id']] ?? null;
                    $status = $att['status'] ?? 'present';
            ?>
            <tr>
                <td><?php echo htmlspecialchars($student['student_id']); ?></td>
                <td><?php echo htmlspecialchars($student['name']); ?></td>
                <td>
                    <input type="hidden" name="student_id[]" value="<?php echo htmlspecialchars($student['id']); ?>" />
                    <input type="radio" name="status[<?php echo $student['id']; ?>]" value="present" id="present_<?php echo $student['id']; ?>" <?php echo ($status == 'present') ? 'checked' : ''; ?> />
                    <label for="present_<?php echo $student['id']; ?>">Present</label>
                    <input type="radio" name="status[<?php echo $student['id']; ?>]" value="absent" id="absent_<?php echo $student['id']; ?>" <?php echo ($status == 'absent') ? 'checked' : ''; ?> />
                    <label for="absent_<?php echo $student['id']; ?>">Absent</label>
                    <input type="radio" name="status[<?php echo $student['id']; ?>]" value="holiday" id="holiday_<?php echo $student['id']; ?>" <?php echo ($status == 'holiday') ? 'checked' : ''; ?> />
                    <label for="holiday_<?php echo $student['id']; ?>">Holiday</label>
                </td>
            </tr>
            <?php endforeach; 
            } ?>
        </tbody>
    </table>
            <button type="submit" name="submit_attendance" class="btn btn-success">Update Attendance</button>
        </form>
    <?php endif; ?>

    <hr />

    <h3>Monthly Attendance Overview</h3>
    <form method="POST" action="admin_attendance.php" class="mb-4">
        <div class="row g-3 align-items-center">
            <div class="col-auto">
                <label for="batch_id_monthly" class="col-form-label">Select Batch</label>
            </div>
            <div class="col-auto">
                <select name="batch_id" id="batch_id_monthly" class="form-select" required>
                    <option value="">Select Batch</option>
                    <?php foreach ($batches as $batch): ?>
                        <option value="<?php echo htmlspecialchars($batch['id']); ?>" <?php echo ($batch['id'] == $selected_batch_id) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($batch['batch_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-auto">
                <label for="month" class="col-form-label">Select Month</label>
            </div>
            <div class="col-auto">
                <input type="month" name="month" id="month" class="form-control" value="<?php echo htmlspecialchars($month); ?>" required />
            </div>
            <div class="col-auto">
                <button type="submit" name="load_monthly_attendance" class="btn btn-primary">Load Monthly Attendance</button>
            </div>
        </div>
    </form>

    <?php if (!empty($monthly_attendance)): ?>
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>Student ID</th>
                    <th>Name</th>
                    <?php
                    $period = new DatePeriod(
                        new DateTime($month_start),
                        new DateInterval('P1D'),
                        new DateTime($month_end . ' +1 day')
                    );
                    foreach ($period as $date) {
                        echo '<th>' . $date->format('d') . '</th>';
                    }
                    ?>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($monthly_attendance as $student): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($student['student_id']); ?></td>
                        <td><?php echo htmlspecialchars($student['name']); ?></td>
                        <?php
                        foreach ($period as $date) {
                            $date_str = $date->format('Y-m-d');
                            $status = $student['attendance'][$date_str] ?? '';
                            $color = '';
                            $display = '';
                            if ($status === 'present') {
                                $display = 'P';
                                $color = 'green';
                            } elseif ($status === 'absent') {
                                $display = 'A';
                                $color = 'red';
                            } elseif ($status === 'holiday') {
                                $display = 'H';
                                $color = 'blue';
                            } else {
                                $display = '';
                                $color = '';
                            }
                            echo '<td class="text-center" style="color:' . $color . ';">' . $display . '</td>';
                        }
                        ?>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
