<?php
session_start();
require_once '../config/database.php';
require_once '../includes/site_settings.php';

// Check if user is logged in and has permission
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] != 'admin' && $_SESSION['user_role'] != 'teacher')) {
    header('Location: ../login.php');
    exit();
}

// Get system name for branding
$system_name = get_system_name($pdo);

// Get teacher's assigned classes if user is a teacher
$teacher_id = null;
$assigned_class_ids = [];
if ($_SESSION['user_role'] == 'teacher') {
    // Get teacher ID
    $stmt = $pdo->prepare("SELECT id FROM teachers WHERE user_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $teacher = $stmt->fetch();
    if ($teacher) {
        $teacher_id = $teacher['id'];
        
        // Get assigned class IDs
        $stmt = $pdo->prepare("SELECT DISTINCT c.id FROM classes c WHERE (c.class_teacher_id = ? OR c.id IN (SELECT class_id FROM class_subjects WHERE teacher_id = ?)) AND c.status = 'active'");
        $stmt->execute([$teacher_id, $teacher_id]);
        $assigned_classes = $stmt->fetchAll();
        $assigned_class_ids = array_column($assigned_classes, 'id');
    }
}

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

// Get classes for dropdown
if ($_SESSION['user_role'] == 'teacher' && !empty($assigned_class_ids)) {
    // Teacher: only show assigned classes
    $placeholders = str_repeat('?,', count($assigned_class_ids) - 1) . '?';
    $stmt = $pdo->prepare("SELECT id, name, section FROM classes WHERE id IN ($placeholders) AND status = 'active' ORDER BY name, section");
    $stmt->execute($assigned_class_ids);
    $classes = $stmt->fetchAll();
} else {
    // Admin: show all classes
    $stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section");
    $classes = $stmt->fetchAll();
}

// Get sessions for dropdown
$stmt = $pdo->query("SELECT DISTINCT session FROM students WHERE session IS NOT NULL AND session != '' ORDER BY session DESC");
$sessions = $stmt->fetchAll(PDO::FETCH_COLUMN);
if (empty($sessions)) {
    $currentYear = date('Y');
    for ($i = 0; $i < 5; $i++) {
        $sessions[] = $currentYear - $i;
    }
}

$selected_class = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;
$selected_session = isset($_GET['session']) ? $_GET['session'] : date('Y');
$selected_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

$students = [];
$existing_attendance = [];

if ($selected_class > 0 && $selected_session) {
    // Get students in the selected class and session
    $stmt = $pdo->prepare("
        SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.photo
        FROM students s 
        WHERE s.class_id = ? AND s.session = ? AND s.status = 'active'
        ORDER BY s.roll_number
    ");
    $stmt->execute([$selected_class, $selected_session]);
    $students = $stmt->fetchAll();
    
    // Get existing attendance for the selected date
    $stmt = $pdo->prepare("
        SELECT student_id, status, remarks 
        FROM attendance 
        WHERE class_id = ? AND date = ?
    ");
    $stmt->execute([$selected_class, $selected_date]);
    $attendance_records = $stmt->fetchAll();
    
    foreach ($attendance_records as $record) {
        $existing_attendance[$record['student_id']] = [
            'status' => $record['status'],
            'remarks' => $record['remarks']
        ];
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_attendance'])) {
    $class_id = (int)$_POST['class_id'];
    $session = $_POST['session'];
    $date = $_POST['date'];
    $attendance_data = $_POST['attendance'] ?? [];
    
    if (empty($attendance_data)) {
        $error_message = 'কোন উপস্থিতি তথ্য পাওয়া যায়নি';
    } else {
        try {
            $pdo->beginTransaction();
            
            // Delete existing attendance for this class and date
            $stmt = $pdo->prepare("DELETE FROM attendance WHERE class_id = ? AND date = ?");
            $stmt->execute([$class_id, $date]);
            
            // Insert new attendance records
            $stmt = $pdo->prepare("
                INSERT INTO attendance (student_id, class_id, date, status, remarks, marked_by) 
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            
            foreach ($attendance_data as $student_id => $data) {
                $status = $data['status'];
                $remarks = trim($data['remarks'] ?? '');
                
                $stmt->execute([$student_id, $class_id, $date, $status, $remarks, $_SESSION['user_id']]);
            }
            
            $pdo->commit();
            $success_message = 'উপস্থিতি সফলভাবে সংরক্ষণ করা হয়েছে';
            
            // Refresh existing attendance data
            $stmt = $pdo->prepare("
                SELECT student_id, status, remarks 
                FROM attendance 
                WHERE class_id = ? AND date = ?
            ");
            $stmt->execute([$class_id, $date]);
            $attendance_records = $stmt->fetchAll();
            
            $existing_attendance = [];
            foreach ($attendance_records as $record) {
                $existing_attendance[$record['student_id']] = [
                    'status' => $record['status'],
                    'remarks' => $record['remarks']
                ];
            }
            
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = 'উপস্থিতি সংরক্ষণে সমস্যা হয়েছে: ' . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>উপস্থিতি নিন - <?php echo htmlspecialchars($system_name); ?></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/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-graduation-cap"></i> <?php echo htmlspecialchars($system_name); ?>
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="../index.php">
                    <i class="fas fa-home"></i> হোম
                </a>
                <a class="nav-link" href="../logout.php">
                    <i class="fas fa-sign-out-alt"></i> লগআউট
                </a>
            </div>
        </div>
    </nav>
    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-calendar-check"></i> উপস্থিতি নিন</h5>
                    </div>
                    <div class="card-body">
                        <?php if ($success_message): ?>
                            <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>
                        <?php endif; ?>
                        
                        <?php if ($error_message): ?>
                            <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>
                        <?php endif; ?>

                        <!-- Class, Session and Date Selection -->
                        <form method="GET" class="mb-4">
                            <div class="row">
                                <div class="col-md-4">
                                    <label for="class_id" class="form-label">ক্লাস নির্বাচন করুন</label>
                                    <select class="form-select" id="class_id" name="class_id" required>
                                        <option value="">ক্লাস নির্বাচন করুন</option>
                                        <?php foreach ($classes as $class): ?>
                                            <option value="<?php echo $class['id']; ?>" 
                                                    <?php echo ($selected_class == $class['id']) ? 'selected' : ''; ?>>
                                                <?php echo $class['name'] . ' - ' . $class['section']; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label for="session" class="form-label">সেশন</label>
                                    <select class="form-select" id="session" name="session" required>
                                        <option value="">সেশন নির্বাচন করুন</option>
                                        <?php foreach ($sessions as $session): ?>
                                            <option value="<?php echo $session; ?>" 
                                                    <?php echo ($selected_session == $session) ? 'selected' : ''; ?>>
                                                <?php echo $session; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label for="date" class="form-label">তারিখ</label>
                                    <input type="date" class="form-control" id="date" name="date" 
                                           value="<?php echo $selected_date; ?>" required>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">&nbsp;</label>
                                    <div class="d-grid">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-search"></i> ছাত্র-ছাত্রী লোড করুন
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>

                        <?php if (!empty($students)): ?>
                            <!-- Attendance Form -->
                            <form method="POST" action="">
                                <input type="hidden" name="class_id" value="<?php echo $selected_class; ?>">
                                <input type="hidden" name="session" value="<?php echo $selected_session; ?>">
                                <input type="hidden" name="date" value="<?php echo $selected_date; ?>">
                                
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h6>
                                        <?php 
                                        $class_info = array_filter($classes, function($c) use ($selected_class) {
                                            return $c['id'] == $selected_class;
                                        });
                                        $class_info = reset($class_info);
                                        echo $class_info['name'] . ' - ' . $class_info['section']; 
                                        ?> 
                                        (সেশন: <?php echo $selected_session; ?>) এর উপস্থিতি (<?php echo date('d/m/Y', strtotime($selected_date)); ?>)
                                    </h6>
                                    <div>
                                        <button type="button" class="btn btn-sm btn-success" onclick="markAllPresent()">
                                            <i class="fas fa-check-double"></i> সবাইকে উপস্থিত
                                        </button>
                                        <button type="button" class="btn btn-sm btn-danger" onclick="markAllAbsent()">
                                            <i class="fas fa-times"></i> সবাইকে অনুপস্থিত
                                        </button>
                                    </div>
                                </div>

                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>ছবি</th>
                                                <th>রোল</th>
                                                <th>নাম</th>
                                                <th>উপস্থিতি</th>
                                                <th>মন্তব্য</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($students as $student): ?>
                                                <?php 
                                                $current_status = $existing_attendance[$student['id']]['status'] ?? 'present';
                                                $current_remarks = $existing_attendance[$student['id']]['remarks'] ?? '';
                                                ?>
                                                <tr>
                                                    <td>
                                                        <?php if ($student['photo'] && file_exists('../' . $student['photo'])): ?>
                                                            <img src="../<?php echo $student['photo']; ?>" 
                                                                 alt="<?php echo $student['first_name']; ?>" 
                                                                 class="profile-img-small">
                                                        <?php else: ?>
                                                            <div class="bg-secondary rounded-circle d-flex align-items-center justify-content-center" 
                                                                 style="width: 40px; height: 40px;">
                                                                <i class="fas fa-user text-white"></i>
                                                            </div>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-info"><?php echo $student['roll_number']; ?></span>
                                                    </td>
                                                    <td>
                                                        <strong><?php echo $student['first_name'] . ' ' . $student['last_name']; ?></strong>
                                                        <br><small class="text-muted"><?php echo $student['student_id']; ?></small>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group" role="group">
                                                            <input type="radio" class="btn-check" 
                                                                   name="attendance[<?php echo $student['id']; ?>][status]" 
                                                                   value="present" 
                                                                   id="present_<?php echo $student['id']; ?>"
                                                                   <?php echo ($current_status == 'present') ? 'checked' : ''; ?>>
                                                            <label class="btn btn-outline-success btn-sm" 
                                                                   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']; ?>][status]" 
                                                                   value="absent" 
                                                                   id="absent_<?php echo $student['id']; ?>"
                                                                   <?php echo ($current_status == 'absent') ? 'checked' : ''; ?>>
                                                            <label class="btn btn-outline-danger btn-sm" 
                                                                   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']; ?>][status]" 
                                                                   value="late" 
                                                                   id="late_<?php echo $student['id']; ?>"
                                                                   <?php echo ($current_status == 'late') ? 'checked' : ''; ?>>
                                                            <label class="btn btn-outline-warning btn-sm" 
                                                                   for="late_<?php echo $student['id']; ?>">
                                                                <i class="fas fa-clock"></i> দেরি
                                                            </label>

                                                            <input type="radio" class="btn-check" 
                                                                   name="attendance[<?php echo $student['id']; ?>][status]" 
                                                                   value="excused" 
                                                                   id="excused_<?php echo $student['id']; ?>"
                                                                   <?php echo ($current_status == 'excused') ? 'checked' : ''; ?>>
                                                            <label class="btn btn-outline-info btn-sm" 
                                                                   for="excused_<?php echo $student['id']; ?>">
                                                                <i class="fas fa-user-clock"></i> ছুটি
                                                            </label>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <input type="text" class="form-control form-control-sm" 
                                                               name="attendance[<?php echo $student['id']; ?>][remarks]" 
                                                               placeholder="মন্তব্য (ঐচ্ছিক)"
                                                               value="<?php echo htmlspecialchars($current_remarks); ?>">
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>

                                <div class="row mt-4">
                                    <div class="col-md-12">
                                        <div class="d-flex justify-content-between">
                                            <a href="report.php" class="btn btn-secondary">
                                                <i class="fas fa-chart-bar"></i> উপস্থিতি রিপোর্ট
                                            </a>
                                            <button type="submit" name="submit_attendance" class="btn btn-success">
                                                <i class="fas fa-save"></i> উপস্থিতি সংরক্ষণ করুন
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        <?php elseif ($selected_class > 0): ?>
                            <div class="text-center py-5">
                                <i class="fas fa-users fa-4x text-muted mb-3"></i>
                                <h4 class="text-muted">এই ক্লাসে কোন ছাত্র-ছাত্রী নেই</h4>
                                <p class="text-muted">নির্বাচিত ক্লাস ও সেশনে কোন সক্রিয় ছাত্র-ছাত্রী পাওয়া যায়নি।</p>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-5">
                                <i class="fas fa-calendar-check fa-4x text-muted mb-3"></i>
                                <h4 class="text-muted">ক্লাস ও সেশন নির্বাচন করুন</h4>
                                <p class="text-muted">উপস্থিতি নেওয়ার জন্য প্রথমে একটি ক্লাস ও সেশন নির্বাচন করুন।</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/js/script.js"></script>
    <script>
        function markAllPresent() {
            const presentRadios = document.querySelectorAll('input[type="radio"][value="present"]');
            presentRadios.forEach(radio => {
                radio.checked = true;
            });
        }
        
        function markAllAbsent() {
            const absentRadios = document.querySelectorAll('input[type="radio"][value="absent"]');
            absentRadios.forEach(radio => {
                radio.checked = true;
            });
        }
        
        // Auto-submit form when class, session or date changes
        document.getElementById('class_id').addEventListener('change', function() {
            if (this.value) {
                this.form.submit();
            }
        });

        document.getElementById('session').addEventListener('change', function() {
            const classSelect = document.getElementById('class_id');
            if (classSelect.value) {
                this.form.submit();
            }
        });
        
        document.getElementById('date').addEventListener('change', function() {
            const classSelect = document.getElementById('class_id');
            if (classSelect.value) {
                this.form.submit();
            }
        });
    </script>
</body>
</html>
