<?php
session_start();

// Include access control functions
require_once '../includes/access_control.php';
require_once '../config/database.php';

// Check if user is logged in and is a teacher
require_teacher();

$user_role = $_SESSION['user_role'];
$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'] ?? $_SESSION['username'] ?? 'শিক্ষক';

// Only teachers can access this page
if ($user_role !== 'teacher') {
    header('Location: ../index.php');
    exit();
}

// Get teacher ID
$teacher_id = null;
$stmt = $pdo->prepare("SELECT id FROM teachers WHERE user_id = ?");
$stmt->execute([$user_id]);
$teacher = $stmt->fetch();
if ($teacher) {
    $teacher_id = $teacher['id'];
} else {
    // Redirect if not a valid teacher
    header('Location: dashboard.php');
    exit();
}

$success_message = '';
$error_message = '';

// Get teacher's assigned classes
$assigned_classes = [];
$assigned_class_ids = [];
if ($teacher_id) {
    $assigned_class_ids = get_teacher_assigned_classes($teacher_id);

    // Get detailed class information
    if (!empty($assigned_class_ids)) {
        $placeholders = str_repeat('?,', count($assigned_class_ids) - 1) . '?';
        $stmt = $pdo->prepare("
            SELECT DISTINCT c.id, c.name, c.section
            FROM classes c
            WHERE c.id IN ($placeholders) AND c.status = 'active'
            ORDER BY c.name, c.section
        ");
        $stmt->execute($assigned_class_ids);
        $assigned_classes = $stmt->fetchAll();
    }
}

$students = [];
$attendance_date = date('Y-m-d');
$selected_class_id = 0;

// Handle attendance submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_attendance'])) {
    $class_id = (int)$_POST['class_id'];
    $attendance_date = $_POST['attendance_date'];
    $subject_id = isset($_POST['subject_id']) ? (int)$_POST['subject_id'] : null;
    
    // Validate that teacher has access to this class
    if (!teacher_has_class_access($teacher_id, $class_id)) {
        $error_message = "আপনি এই ক্লাসের জন্য উপস্থিতি নিতে পারবেন না।";
    } else {
        try {
            $pdo->beginTransaction();
            
            // Process each student's attendance
            if (isset($_POST['attendance']) && is_array($_POST['attendance'])) {
                foreach ($_POST['attendance'] as $student_id => $status) {
                    // Check if attendance already exists for this student/date
                    $stmt = $pdo->prepare("
                        SELECT id FROM attendance 
                        WHERE student_id = ? AND date = ? AND class_id = ?
                    ");
                    $stmt->execute([$student_id, $attendance_date, $class_id]);
                    $existing_attendance = $stmt->fetch();
                    
                    if ($existing_attendance) {
                        // Update existing attendance
                        $stmt = $pdo->prepare("
                            UPDATE attendance SET 
                                status = ?, subject_id = ?, remarks = ?, updated_at = NOW()
                            WHERE id = ?
                        ");
                        $stmt->execute([
                            $status, 
                            $subject_id, 
                            $_POST['remarks'][$student_id] ?? '', 
                            $existing_attendance['id']
                        ]);
                    } else {
                        // Insert new attendance
                        $stmt = $pdo->prepare("
                            INSERT INTO attendance 
                            (student_id, class_id, date, status, subject_id, remarks, created_at, updated_at)
                            VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())
                        ");
                        $stmt->execute([
                            $student_id, 
                            $class_id, 
                            $attendance_date, 
                            $status, 
                            $subject_id, 
                            $_POST['remarks'][$student_id] ?? ''
                        ]);
                    }
                }
            }
            
            $pdo->commit();
            $success_message = "উপস্থিতি সফলভাবে সেভ করা হয়েছে!";
            
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = "উপস্থিতি সেভ করতে সমস্যা হয়েছে: " . $e->getMessage();
        }
    }
}

// Handle search for students
if (isset($_GET['search']) && $_GET['search'] == '1') {
    $selected_class_id = (int)$_GET['class_id'];
    $attendance_date = $_GET['date'] ?? date('Y-m-d');
    
    // Validate that teacher has access to this class
    if (!teacher_has_class_access($teacher_id, $selected_class_id)) {
        $error_message = "আপনি এই ক্লাসের জন্য উপস্থিতি নিতে পারবেন না।";
    } else {
        // Get students for this class
        $stmt = $pdo->prepare("
            SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number,
                   a.status as existing_status, a.remarks as existing_remarks
            FROM students s
            LEFT JOIN attendance a ON s.id = a.student_id AND a.date = ? AND a.class_id = ?
            WHERE s.class_id = ? AND s.status = 'active'
            ORDER BY s.roll_number, s.first_name
        ");
        $stmt->execute([$attendance_date, $selected_class_id, $selected_class_id]);
        $students = $stmt->fetchAll();
    }
}

// Get subjects taught by this teacher in the selected class
$subjects = [];
if ($selected_class_id > 0) {
    $stmt = $pdo->prepare("
        SELECT DISTINCT s.id, s.name, s.code
        FROM subjects s
        JOIN class_subjects cs ON s.id = cs.subject_id
        WHERE cs.teacher_id = ? AND cs.class_id = ? AND s.status = 'active'
        ORDER BY s.name
    ");
    $stmt->execute([$teacher_id, $selected_class_id]);
    $subjects = $stmt->fetchAll();
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>আমার উপস্থিতি - স্কুল ম্যানেজমেন্ট সিস্টেম</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/jessoreboard-theme.css" rel="stylesheet">
    <style>
        .attendance-card {
            background: #fff;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .present {
            background-color: #d4edda;
        }
        .absent {
            background-color: #f8d7da;
        }
        .late {
            background-color: #fff3cd;
        }
        #select-all-present, #select-all-absent, #select-all-late {
            margin-right: 10px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-12">
                <h2><i class="fas fa-calendar-check"></i> আমার উপস্থিতি</h2>
                <p class="text-muted">আপনার নির্ধারিত ক্লাসের জন্য উপস্থিতি নিন</p>
            </div>
        </div>

        <!-- Messages -->
        <?php if ($success_message): ?>
            <div class="row">
                <div class="col-12">
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                </div>
            </div>
        <?php endif; ?>
        
        <?php if ($error_message): ?>
            <div class="row">
                <div class="col-12">
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <!-- Search Form -->
        <div class="row">
            <div class="col-12">
                <div class="attendance-card">
                    <form method="GET" class="row g-3">
                        <input type="hidden" name="search" value="1">
                        
                        <div class="col-md-4">
                            <label for="class_id" class="form-label">ক্লাস <span class="text-danger">*</span></label>
                            <select class="form-select" id="class_id" name="class_id" required>
                                <option value="">ক্লাস নির্বাচন করুন</option>
                                <?php foreach ($assigned_classes as $class): ?>
                                    <option value="<?php echo $class['id']; ?>" 
                                            <?php echo (isset($_GET['class_id']) && $_GET['class_id'] == $class['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($class['name'] . ' - ' . $class['section']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-4">
                            <label for="date" class="form-label">তারিখ <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" id="date" name="date" 
                                   value="<?php echo isset($_GET['date']) ? $_GET['date'] : date('Y-m-d'); ?>" required>
                        </div>
                        
                        <div class="col-md-4">
                            <label class="form-label">&nbsp;</label>
                            <div>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-search"></i> ছাত্র-ছাত্রী খুঁজুন
                                </button>
                                <a href="dashboard.php" class="btn btn-secondary">
                                    <i class="fas fa-arrow-left"></i> ড্যাশবোর্ডে ফিরুন
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Attendance Entry Form -->
        <?php if (!empty($students)): ?>
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h5>
                                <i class="fas fa-users"></i> উপস্থিতি নিন
                                <small class="text-muted">
                                    (তারিখ: <?php echo date('d/m/Y', strtotime($attendance_date)); ?>)
                                </small>
                            </h5>
                        </div>
                        <div class="card-body">
                            <form method="POST">
                                <input type="hidden" name="class_id" value="<?php echo $selected_class_id; ?>">
                                <input type="hidden" name="attendance_date" value="<?php echo $attendance_date; ?>">
                                
                                <!-- Subject Selection (Optional) -->
                                <?php if (!empty($subjects)): ?>
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label for="subject_id" class="form-label">বিষয় (ঐচ্ছিক)</label>
                                            <select class="form-select" id="subject_id" name="subject_id">
                                                <option value="">বিষয় নির্বাচন করুন</option>
                                                <?php foreach ($subjects as $subject): ?>
                                                    <option value="<?php echo $subject['id']; ?>">
                                                        <?php echo htmlspecialchars($subject['name'] . ' (' . $subject['code'] . ')'); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="table-responsive">
                                    <div class="mb-3">
                                        <button type="button" class="btn btn-success btn-sm" id="select-all-present">
                                            <i class="fas fa-user-check"></i> সব উপস্থিতি
                                        </button>
                                        <button type="button" class="btn btn-danger btn-sm" id="select-all-absent">
                                            <i class="fas fa-user-times"></i> সব অনুপস্থিতি
                                        </button>
                                        <button type="button" class="btn btn-warning btn-sm" id="select-all-late">
                                            <i class="fas fa-clock"></i> সব বিলম্ব
                                        </button>
                                    </div>
                                    <table class="table table-striped table-hover">
                                        <thead class="table-dark">
                                            <tr>
                                                <th>ছাত্র/ছাত্রী</th>
                                                <th>রোল</th>
                                                <th>আইডি</th>
                                                <th class="text-center">অবস্থা</th>
                                                <th>মন্তব্য</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($students as $student): ?>
                                                <tr id="row_<?php echo $student['id']; ?>">
                                                    <td><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></td>
                                                    <td><?php echo htmlspecialchars($student['roll_number']); ?></td>
                                                    <td><?php echo htmlspecialchars($student['student_id']); ?></td>
                                                    <td class="text-center">
                                                        <div class="btn-group" role="group">
                                                            <input type="radio" class="btn-check" name="attendance[<?php echo $student['id']; ?>]" 
                                                                   id="present_<?php echo $student['id']; ?>" 
                                                                   value="present" 
                                                                   <?php echo (isset($student['existing_status']) && $student['existing_status'] == 'present') ? 'checked' : ''; ?>>
                                                            <label class="btn btn-outline-success" for="present_<?php echo $student['id']; ?>">
                                                                <i class="fas fa-check"></i> উপস্থিত
                                                            </label>
                                                            
                                                            <input type="radio" class="btn-check" name="attendance[<?php echo $student['id']; ?>]" 
                                                                   id="absent_<?php echo $student['id']; ?>" 
                                                                   value="absent" 
                                                                   <?php echo (isset($student['existing_status']) && $student['existing_status'] == 'absent') ? 'checked' : ''; ?>>
                                                            <label class="btn btn-outline-danger" for="absent_<?php echo $student['id']; ?>">
                                                                <i class="fas fa-times"></i> অনুপস্থিত
                                                            </label>
                                                            
                                                            <input type="radio" class="btn-check" name="attendance[<?php echo $student['id']; ?>]" 
                                                                   id="late_<?php echo $student['id']; ?>" 
                                                                   value="late" 
                                                                   <?php echo (isset($student['existing_status']) && $student['existing_status'] == 'late') ? 'checked' : ''; ?>>
                                                            <label class="btn btn-outline-warning" for="late_<?php echo $student['id']; ?>">
                                                                <i class="fas fa-clock"></i> বিলম্ব
                                                            </label>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <input type="text" class="form-control" 
                                                               name="remarks[<?php echo $student['id']; ?>]" 
                                                               value="<?php echo $student['existing_remarks'] ?? ''; ?>"
                                                               placeholder="মন্তব্য (যদি থাকে)">
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                
                                <div class="row mt-3">
                                    <div class="col-12 text-end">
                                        <button type="submit" name="save_attendance" class="btn btn-success btn-lg">
                                            <i class="fas fa-save"></i> উপস্থিতি সেভ করুন
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        <?php elseif (isset($_GET['search']) && $_GET['search'] == '1'): ?>
            <div class="row">
                <div class="col-12">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> নির্বাচিত ক্লাসের জন্য কোন ছাত্র-ছাত্রী পাওয়া যায়নি।
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Add row highlighting based on attendance status
        document.addEventListener('change', function(e) {
            if (e.target.name && e.target.name.startsWith('attendance[')) {
                const studentId = e.target.name.match(/\[(\d+)\]/)[1];
                const row = document.getElementById('row_' + studentId);
                
                // Remove all classes
                row.classList.remove('present', 'absent', 'late');
                
                // Add class based on selected status
                if (e.target.value === 'present') {
                    row.classList.add('present');
                } else if (e.target.value === 'absent') {
                    row.classList.add('absent');
                } else if (e.target.value === 'late') {
                    row.classList.add('late');
                }
            }
        });
        
        // Initialize row colors on page load
        document.addEventListener('DOMContentLoaded', function() {
            const radioButtons = document.querySelectorAll('input[name^="attendance["]:checked');
            radioButtons.forEach(function(radio) {
                const event = new Event('change');
                radio.dispatchEvent(event);
            });
            
            // Add event listeners for select all buttons
            const selectAllPresent = document.getElementById('select-all-present');
            const selectAllAbsent = document.getElementById('select-all-absent');
            const selectAllLate = document.getElementById('select-all-late');
            
            if (selectAllPresent) {
                selectAllPresent.addEventListener('click', function() {
                    const presentRadios = document.querySelectorAll('input[name^="attendance["][value="present"]');
                    presentRadios.forEach(function(radio) {
                        radio.checked = true;
                        // Trigger change event to update row styling
                        const event = new Event('change');
                        radio.dispatchEvent(event);
                    });
                });
            }
            
            if (selectAllAbsent) {
                selectAllAbsent.addEventListener('click', function() {
                    const absentRadios = document.querySelectorAll('input[name^="attendance["][value="absent"]');
                    absentRadios.forEach(function(radio) {
                        radio.checked = true;
                        // Trigger change event to update row styling
                        const event = new Event('change');
                        radio.dispatchEvent(event);
                    });
                });
            }
            
            if (selectAllLate) {
                selectAllLate.addEventListener('click', function() {
                    const lateRadios = document.querySelectorAll('input[name^="attendance["][value="late"]');
                    lateRadios.forEach(function(radio) {
                        radio.checked = true;
                        // Trigger change event to update row styling
                        const event = new Event('change');
                        radio.dispatchEvent(event);
                    });
                });
            }
        });
    </script>
</body>
</html>