<?php
// Include database connection
include('db_connection.php');

// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Initialize variables from the form
    $teacher_id = $_POST['teacher_id'];
    $attendance_date = $_POST['attendance_date'];
    $status = $_POST['status'];
    $notes = isset($_POST['notes']) ? $_POST['notes'] : '';

    // Prepare SQL statement to insert attendance record
    $query = "INSERT INTO attendance (teacher_id, attendance_date, status, notes) VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($query);

    // Check for prepared statement errors
    if ($stmt === false) {
        die('Error in preparing statement: ' . $conn->error);
    }

    // Bind parameters and execute statement
    $stmt->bind_param("isss", $teacher_id, $attendance_date, $status, $notes);
    $stmt->execute();

    // Check for execution success
    if ($stmt->affected_rows > 0) {
        // Successful insertion
        $success_message = "Attendance record added successfully!";
    } else {
        // Error in execution
        $error_message = "Error: " . $stmt->error;
    }

    // Close statement
    $stmt->close();
}

// Fetch teachers for dropdown
$query = "SELECT teacher_id, name FROM teachers ORDER BY name";
$teachers_result = $conn->query($query);

// Fetch attendance records for display
$records_query = "SELECT t.name AS teacher_name, a.attendance_date, a.status, a.notes 
                  FROM attendance a 
                  INNER JOIN teachers t ON a.teacher_id = t.teacher_id
                  ORDER BY a.attendance_date DESC";
$records_result = $conn->query($records_query);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Attendance Management - School Management System</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #3a57e8;
            --secondary: #6c757d;
            --success: #1cbb8c;
            --info: #17a2b8;
            --warning: #f5b759;
            --danger: #fc5b69;
            --light: #f8f9fa;
            --dark: #343a40;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background-color: #f5f7ff;
            color: #333;
        }
        
        .card {
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            margin-bottom: 20px;
            border: none;
        }
        
        .card-header {
            background: linear-gradient(135deg, var(--primary) 0%, #2039c5 100%);
            color: white;
            border-radius: 10px 10px 0 0 !important;
            font-weight: 600;
        }
        
        .btn-primary {
            background: var(--primary);
            border: none;
        }
        
        .btn-primary:hover {
            background: #2039c5;
        }
        
        .table th {
            background-color: var(--primary);
            color: white;
        }
        
        .status-badge {
            padding: 0.5em 1em;
            border-radius: 20px;
            font-weight: 600;
        }
        
        .status-present {
            background-color: rgba(28, 187, 140, 0.2);
            color: var(--success);
        }
        
        .status-absent {
            background-color: rgba(252, 91, 105, 0.2);
            color: var(--danger);
        }
        
        .status-leave {
            background-color: rgba(245, 183, 89, 0.2);
            color: var(--warning);
        }
        
        .stats-card {
            text-align: center;
            padding: 20px;
            border-radius: 10px;
            background: white;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            margin-bottom: 20px;
        }
        
        .stats-number {
            font-size: 24px;
            font-weight: 700;
            color: var(--primary);
        }
        
        .stats-label {
            font-size: 14px;
            color: var(--secondary);
        }
        
        .attendance-form {
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
        }
        
        .section-title {
            border-left: 4px solid var(--primary);
            padding-left: 15px;
            margin-bottom: 25px;
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <div class="row mb-4">
            <div class="col-md-8">
                <h2 class="mb-0"><i class="fas fa-calendar-check me-2"></i>Attendance Management</h2>
                <p class="text-muted">Record and view teacher attendance records</p>
            </div>
            <div class="col-md-4 text-md-end">
                <a href="dashboard.php" class="btn btn-outline-primary"><i class="fas fa-arrow-left me-1"></i> Back to Dashboard</a>
            </div>
        </div>

        <!-- Display messages -->
        <?php if (isset($success_message)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle me-2"></i> <?php echo $success_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        
        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i> <?php echo $error_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <!-- Statistics Cards -->
        <div class="row mb-4">
            <div class="col-md-4">
                <div class="stats-card">
                    <div class="stats-number">
                        <?php
                        $today = date('Y-m-d');
                        $today_query = "SELECT COUNT(*) as count FROM attendance WHERE attendance_date = '$today'";
                        $today_result = $conn->query($today_query);
                        $today_count = $today_result->fetch_assoc()['count'];
                        echo $today_count;
                        ?>
                    </div>
                    <div class="stats-label">Today's Records</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stats-card">
                    <div class="stats-number">
                        <?php
                        $present_query = "SELECT COUNT(*) as count FROM attendance WHERE status = 'Present' AND attendance_date = '$today'";
                        $present_result = $conn->query($present_query);
                        $present_count = $present_result->fetch_assoc()['count'];
                        echo $present_count;
                        ?>
                    </div>
                    <div class="stats-label">Present Today</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stats-card">
                    <div class="stats-number">
                        <?php
                        $teachers_query = "SELECT COUNT(*) as count FROM teachers";
                        $teachers_count_result = $conn->query($teachers_query);
                        $teachers_count = $teachers_count_result->fetch_assoc()['count'];
                        echo $teachers_count;
                        ?>
                    </div>
                    <div class="stats-label">Total Teachers</div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-5">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-plus-circle me-2"></i>Record Attendance</h5>
                    </div>
                    <div class="card-body">
                        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
                            <div class="mb-3">
                                <label for="teacher_id" class="form-label">Teacher Name</label>
                                <select class="form-select" id="teacher_id" name="teacher_id" required>
                                    <option value="">Select Teacher</option>
                                    <?php
                                    if ($teachers_result->num_rows > 0) {
                                        while ($row = $teachers_result->fetch_assoc()) {
                                            echo "<option value='" . $row['teacher_id'] . "'>" . $row['name'] . "</option>";
                                        }
                                    } else {
                                        echo "<option value=''>No teachers found</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label for="attendance_date" class="form-label">Attendance Date</label>
                                <input type="date" class="form-control" id="attendance_date" name="attendance_date" 
                                       value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="status" class="form-label">Attendance Status</label>
                                <select class="form-select" id="status" name="status" required>
                                    <option value="Present">Present</option>
                                    <option value="Absent">Absent</option>
                                    <option value="Leave">Leave</option>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label for="notes" class="form-label">Notes (Optional)</label>
                                <textarea class="form-control" id="notes" name="notes" rows="3"></textarea>
                            </div>
                            
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="fas fa-save me-1"></i> Record Attendance
                            </button>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-md-7">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="fas fa-history me-2"></i>Attendance Records</h5>
                        <span class="badge bg-primary"><?php echo $records_result->num_rows; ?> Records</span>
                    </div>
                    <div class="card-body">
                        <?php if ($records_result->num_rows > 0): ?>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>Teacher Name</th>
                                            <th>Date</th>
                                            <th>Status</th>
                                            <th>Notes</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php while ($row = $records_result->fetch_assoc()): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($row['teacher_name']); ?></td>
                                            <td><?php echo date('M j, Y', strtotime($row['attendance_date'])); ?></td>
                                            <td>
                                                <?php 
                                                $status_class = '';
                                                if ($row['status'] == 'Present') $status_class = 'status-present';
                                                elseif ($row['status'] == 'Absent') $status_class = 'status-absent';
                                                elseif ($row['status'] == 'Leave') $status_class = 'status-leave';
                                                ?>
                                                <span class="status-badge <?php echo $status_class; ?>">
                                                    <?php echo $row['status']; ?>
                                                </span>
                                            </td>
                                            <td><?php echo !empty($row['notes']) ? htmlspecialchars($row['notes']) : '—'; ?></td>
                                        </tr>
                                        <?php endwhile; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-5">
                                <i class="fas fa-calendar-times fa-3x text-muted mb-3"></i>
                                <p class="text-muted">No attendance records found.</p>
                                <p>Record attendance to see data here.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Set today's date as default if not already set
        document.addEventListener('DOMContentLoaded', function() {
            const attendanceDate = document.getElementById('attendance_date');
            if (!attendanceDate.value) {
                attendanceDate.value = new Date().toISOString().substring(0, 10);
            }
            
            // Add animation to table rows
            const tableRows = document.querySelectorAll('tbody tr');
            tableRows.forEach((row, index) => {
                row.style.opacity = '0';
                row.style.transform = 'translateX(-20px)';
                setTimeout(() => {
                    row.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
                    row.style.opacity = '1';
                    row.style.transform = 'translateX(0)';
                }, index * 100);
            });
        });
    </script>
</body>
</html>

<?php
// Close database connection
$conn->close();
?>