<?php
/**
 * Parent Portal - Attendance
 */

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../config/database.php';

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if user is logged in as parent
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'parent') {
    header('Location: ../parent_login.php');
    exit;
}

// Get parent information
$stmt = $pdo->prepare("SELECT * FROM parents WHERE user_id = ?");
$stmt->execute([$_SESSION['user_id']]);
$parent = $stmt->fetch();

if (!$parent) {
    header('Location: ../parent_register.php');
    exit;
}

// Get associated students
try {
    $stmt = $pdo->prepare("
        SELECT s.*, c.name as class_name
        FROM students s
        LEFT JOIN classes c ON s.class_id = c.id
        WHERE s.id IN (
            SELECT student_id FROM parent_students WHERE parent_id = ?
        ) AND s.status = 'active'
    ");
    $stmt->execute([$parent['id']]);
    $students = $stmt->fetchAll();
} catch (Exception $e) {
    $students = [];
}

// Get selected student
$selected_student_id = $_GET['student_id'] ?? ($students[0]['id'] ?? null);

// Get attendance data for selected student
$attendance_data = [];
$monthly_summary = [];
if ($selected_student_id) {
    try {
        // Get last 30 days attendance
        $stmt = $pdo->prepare("
            SELECT a.*, sub.name as subject_name
            FROM attendance a
            LEFT JOIN subjects sub ON a.subject_id = sub.id
            WHERE a.student_id = ?
            ORDER BY a.date DESC
            LIMIT 30
        ");
        $stmt->execute([$selected_student_id]);
        $attendance_data = $stmt->fetchAll();
        
        // Get monthly summary
        $stmt = $pdo->prepare("
            SELECT 
                DATE_FORMAT(date, '%Y-%m') as month,
                COUNT(*) as total_days,
                SUM(CASE WHEN status = 'present' THEN 1 ELSE 0 END) as present_days,
                SUM(CASE WHEN status = 'absent' THEN 1 ELSE 0 END) as absent_days,
                SUM(CASE WHEN status = 'late' THEN 1 ELSE 0 END) as late_days
            FROM attendance 
            WHERE student_id = ?
            GROUP BY DATE_FORMAT(date, '%Y-%m')
            ORDER BY month DESC
            LIMIT 6
        ");
        $stmt->execute([$selected_student_id]);
        $monthly_summary = $stmt->fetchAll();
        
    } catch (Exception $e) {
        $attendance_data = [];
        $monthly_summary = [];
    }
}

// Calculate overall statistics
$total_days = count($attendance_data);
$present_days = count(array_filter($attendance_data, function($a) { return $a['status'] == 'present'; }));
$absent_days = count(array_filter($attendance_data, function($a) { return $a['status'] == 'absent'; }));
$late_days = count(array_filter($attendance_data, function($a) { return $a['status'] == 'late'; }));

$attendance_percentage = $total_days > 0 ? round(($present_days / $total_days) * 100, 1) : 0;
?>

<!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 rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .parent-sidebar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: white;
        }
        .parent-sidebar .nav-link {
            color: rgba(255,255,255,0.8);
            padding: 15px 20px;
            border-radius: 8px;
            margin: 5px 0;
            text-decoration: none;
            display: block;
        }
        .parent-sidebar .nav-link:hover, .parent-sidebar .nav-link.active {
            background: rgba(255,255,255,0.2);
            color: white;
        }
        .attendance-card {
            border-left: 4px solid #17a2b8;
        }
        .status-present { background-color: #d4edda; border-color: #28a745; }
        .status-absent { background-color: #f8d7da; border-color: #dc3545; }
        .status-late { background-color: #fff3cd; border-color: #ffc107; }
        .attendance-chart {
            height: 200px;
            background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    </style>
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Parent Sidebar -->
            <nav class="col-md-2 d-none d-md-block parent-sidebar p-3">
                <div class="text-center mb-4">
                    <div class="bg-white rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width:80px;height:80px;">
                        <i class="fas fa-user-tie fa-2x text-primary"></i>
                    </div>
                    <h6 class="mb-0"><?= htmlspecialchars($parent['father_name']) ?></h6>
                    <small>অভিভাবক</small>
                </div>
                
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" href="index.php">
                            <i class="fas fa-home me-2"></i> ড্যাশবোর্ড
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="results.php">
                            <i class="fas fa-chart-line me-2"></i> ফলাফল
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="subjects.php">
                            <i class="fas fa-book me-2"></i> বিষয়সমূহ
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="fees.php">
                            <i class="fas fa-money-bill-wave me-2"></i> ফি পেমেন্ট
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="events.php">
                            <i class="fas fa-calendar-alt me-2"></i> ইভেন্ট
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="attendance.php">
                            <i class="fas fa-clipboard-check me-2"></i> উপস্থিতি
                        </a>
                    </li>
                    <li class="nav-item mt-4">
                        <a class="nav-link text-warning" href="../parent_logout.php">
                            <i class="fas fa-sign-out-alt me-2"></i> লগআউট
                        </a>
                    </li>
                </ul>
            </nav>
            
            <!-- Main Content -->
            <main class="col-md-10 ms-sm-auto px-md-4 py-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2 class="h3"><i class="fas fa-clipboard-check text-info"></i> শিক্ষার্থীর উপস্থিতি</h2>
                    <div class="text-muted">
                        <?= date('l, d F Y', strtotime('now')) ?>
                    </div>
                </div>
                
                <?php if (count($students) > 0): ?>
                <!-- Student Selection -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-filter"></i> শিক্ষার্থী নির্বাচন করুন</h5>
                    </div>
                    <div class="card-body">
                        <form method="GET">
                            <div class="row">
                                <div class="col-md-6">
                                    <select name="student_id" class="form-select" onchange="this.form.submit()">
                                        <?php foreach ($students as $student): ?>
                                            <option value="<?= $student['id'] ?>" <?= $selected_student_id == $student['id'] ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?> - 
                                                <?= htmlspecialchars($student['class_name'] ?? 'N/A') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                
                <?php if ($selected_student_id): ?>
                <div class="row">
                    <!-- Attendance Statistics -->
                    <div class="col-md-8">
                        <div class="card attendance-card">
                            <div class="card-header bg-info text-white">
                                <h5 class="mb-0"><i class="fas fa-chart-bar"></i> উপস্থিতির পরিসংখ্যান (শেষ ৩০ দিন)</h5>
                            </div>
                            <div class="card-body">
                                <?php if ($total_days > 0): ?>
                                <div class="row text-center mb-4">
                                    <div class="col-md-3 mb-3">
                                        <div class="card">
                                            <div class="card-body">
                                                <h3 class="text-success"><?= $present_days ?></h3>
                                                <p class="text-muted mb-0">উপস্থিত</p>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <div class="card">
                                            <div class="card-body">
                                                <h3 class="text-danger"><?= $absent_days ?></h3>
                                                <p class="text-muted mb-0">অনুপস্থিত</p>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <div class="card">
                                            <div class="card-body">
                                                <h3 class="text-warning"><?= $late_days ?></h3>
                                                <p class="text-muted mb-0">দেরিতে</p>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <div class="card">
                                            <div class="card-body">
                                                <h3 class="text-primary"><?= $total_days ?></h3>
                                                <p class="text-muted mb-0">মোট দিন</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="text-center mb-4">
                                    <h2 class="<?= $attendance_percentage >= 90 ? 'text-success' : ($attendance_percentage >= 75 ? 'text-warning' : 'text-danger') ?>">
                                        <?= $attendance_percentage ?>%
                                    </h2>
                                    <p class="text-muted">উপস্থিতির হার</p>
                                </div>
                                
                                <!-- Attendance Chart Visualization -->
                                <div class="attendance-chart mb-4">
                                    <div class="text-center">
                                        <h5 class="text-primary">উপস্থিতির চার্ট</h5>
                                        <div class="progress-stacked mt-3" style="height: 30px;">
                                            <div class="progress" role="progressbar" style="width: <?= ($present_days/$total_days)*100 ?>%">
                                                <div class="progress-bar bg-success">উপস্থিত</div>
                                            </div>
                                            <div class="progress" role="progressbar" style="width: <?= ($absent_days/$total_days)*100 ?>%">
                                                <div class="progress-bar bg-danger">অনুপস্থিত</div>
                                            </div>
                                            <div class="progress" role="progressbar" style="width: <?= ($late_days/$total_days)*100 ?>%">
                                                <div class="progress-bar bg-warning">দেরিতে</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Detailed Attendance Table -->
                                <h5 class="mb-3"><i class="fas fa-list"></i> বিস্তারিত উপস্থিতি</h5>
                                <div class="table-responsive">
                                    <table class="table table-striped table-hover">
                                        <thead class="table-dark">
                                            <tr>
                                                <th>তারিখ</th>
                                                <th>বিষয়</th>
                                                <th>অ্যাটেন্ডেন্স</th>
                                                <th>মন্তব্য</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($attendance_data as $attendance): 
                                                $status_class = 'status-' . $attendance['status'];
                                            ?>
                                            <tr>
                                                <td><?= date('d-m-Y', strtotime($attendance['date'])) ?></td>
                                                <td>
                                                    <?= htmlspecialchars($attendance['subject_name'] ?? 'সাধারণ') ?>
                                                </td>
                                                <td>
                                                    <span class="badge <?= $status_class ?>">
                                                        <?= ucfirst($attendance['status']) ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <?= htmlspecialchars($attendance['remarks'] ?? '-') ?>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php else: ?>
                                <div class="text-center py-5">
                                    <i class="fas fa-clipboard fa-3x text-muted mb-3"></i>
                                    <h5 class="text-muted">কোনো উপস্থিতি তথ্য পাওয়া যায়নি</h5>
                                    <p class="text-muted">এখনও কোনো ক্লাস হয়নি বা তথ্য আপডেট করা হয়নি।</p>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Monthly Summary -->
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header bg-secondary text-white">
                                <h5 class="mb-0"><i class="fas fa-calendar-alt"></i> মাসিক সারাংশ</h5>
                            </div>
                            <div class="card-body">
                                <?php if (count($monthly_summary) > 0): ?>
                                <?php foreach ($monthly_summary as $month): 
                                    $month_percentage = $month['total_days'] > 0 ? 
                                        round(($month['present_days'] / $month['total_days']) * 100, 1) : 0;
                                ?>
                                <div class="mb-3 p-2 border rounded">
                                    <h6 class="mb-2"><?= date('F Y', strtotime($month['month'] . '-01')) ?></h6>
                                    <div class="progress mb-2" style="height: 10px;">
                                        <div class="progress-bar bg-success" role="progressbar" 
                                             style="width: <?= ($month['present_days']/$month['total_days'])*100 ?>%"></div>
                                        <div class="progress-bar bg-warning" role="progressbar" 
                                             style="width: <?= ($month['late_days']/$month['total_days'])*100 ?>%"></div>
                                        <div class="progress-bar bg-danger" role="progressbar" 
                                             style="width: <?= ($month['absent_days']/$month['total_days'])*100 ?>%"></div>
                                    </div>
                                    <div class="small text-muted">
                                        উপস্থিত: <?= $month['present_days'] ?> | 
                                        দেরিতে: <?= $month['late_days'] ?> | 
                                        অনুপস্থিত: <?= $month['absent_days'] ?>
                                    </div>
                                    <div class="small">
                                        হার: <strong><?= $month_percentage ?>%</strong>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                                <?php else: ?>
                                <div class="text-center py-4">
                                    <i class="fas fa-calendar-times fa-2x text-muted mb-2"></i>
                                    <p class="text-muted mb-0">কোনো মাসিক তথ্য নেই</p>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <!-- Attendance Notice -->
                        <div class="card mt-3">
                            <div class="card-header bg-warning text-dark">
                                <h5 class="mb-0"><i class="fas fa-exclamation-triangle"></i> গুরুত্বপূর্ণ</h5>
                            </div>
                            <div class="card-body">
                                <ul class="small mb-0">
                                    <li>৭৫% এর কম উপস্থিতি হলে পরীক্ষার জন্য অযোগ্য হতে পারেন</li>
                                    <li>দেরিতে আসলে শিক্ষকের অনুমতি নিন</li>
                                    <li>অনুপস্থিতির জন্য প্রিন্সিপালের অনুমতি প্রয়োজন</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <?php else: ?>
                <div class="alert alert-info">
                    <h5><i class="fas fa-info-circle"></i> কোনো শিক্ষার্থী খুঁজে পাওয়া যায়নি</h5>
                    <p>সিস্টেমে আপনার শিক্ষার্থীর একাউন্ট অ্যাকটিভ করতে স্কুল অফিসে যোগাযোগ করুন।</p>
                </div>
                <?php endif; ?>
            </main>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>