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

// Get search parameters from URL
$roll = $_GET['roll'] ?? '';
$class_name = $_GET['class'] ?? '';
$session = $_GET['session'] ?? date('Y');

$student = null;
$class_id = null;
$attendance_summary = null; // Initialize here
$attendance_records = []; // Initialize here

if ($roll && $class_name && $session) {
    // Get class_id from class_name
    $stmt = $pdo->prepare("SELECT id FROM classes WHERE name = ?");
    $stmt->execute([$class_name]);
    $class = $stmt->fetch();
    if ($class) {
        $class_id = $class['id'];
    }

    if ($class_id) {
        // Get student details from roll_number, class_id and session
        $stmt = $pdo->prepare(
            "SELECT s.*, c.name as class_name, c.section 
            FROM students s 
            JOIN classes c ON s.class_id = c.id 
            WHERE s.roll_number = ? AND s.class_id = ? AND s.session = ?"
        );
        $stmt->execute([$roll, $class_id, $session]);
        $student = $stmt->fetch();
    }
    
    if ($student) {
        $start_date = $session . '-01-01';
        $end_date = $session . '-12-31';

        // Calculate Fee Status
        $fee_summary = null;
        $total_due = 0;
        try {
            $stmt = $pdo->prepare(
                "SELECT 
                    COALESCE(SUM(amount), 0) as total_payable,
                    COALESCE(SUM(paid_amount), 0) as total_paid
                FROM fees 
                WHERE student_id = ? AND academic_year = ?"
            );
            $stmt->execute([$student['id'], $session]);
            $fee_summary = $stmt->fetch();
            if ($fee_summary) {
                $total_due = $fee_summary['total_payable'] - $fee_summary['total_paid'];
            }
        } catch (Exception $e) {
            $fee_summary = null;
        }

        // Calculate Attendance Summary
        try {
            $stmt_total = $pdo->prepare("SELECT COUNT(*) FROM attendance WHERE student_id = ? AND date BETWEEN ? AND ?");
            $stmt_total->execute([$student['id'], $start_date, $end_date]);
            $total_days = $stmt_total->fetchColumn();

            $stmt_present = $pdo->prepare("SELECT COUNT(*) FROM attendance WHERE student_id = ? AND date BETWEEN ? AND ? AND status = 'present'");
            $stmt_present->execute([$student['id'], $start_date, $end_date]);
            $present_days = $stmt_present->fetchColumn();

            $attendance_summary = [
                'total_days' => $total_days,
                'present_days' => $present_days
            ];
        } catch (Exception $e) {
            $attendance_summary = null;
        }

        // Fetch detailed attendance records
        try {
            $stmt = $pdo->prepare(
                "SELECT date, status, remarks
                FROM attendance
                WHERE student_id = ? AND date BETWEEN ? AND ?
                ORDER BY date DESC"
            );
            $stmt->execute([$student['id'], $start_date, $end_date]);
            $attendance_records = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            $attendance_records = [];
        }
    }
}

// Fetch data for search form dropdowns
$classes_stmt = $pdo->query("SELECT name FROM classes ORDER BY name");
$all_classes = $classes_stmt->fetchAll(PDO::FETCH_COLUMN);

$sessions_stmt = $pdo->query("SELECT DISTINCT session FROM students ORDER BY session DESC");
$all_sessions = $sessions_stmt->fetchAll(PDO::FETCH_COLUMN);

?>

<!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/style.css" rel="stylesheet">
    <style>
        @media print {
            .no-print { display: none !important; }
        }
        .report-card {
            border: 2px solid #000;
            padding: 20px;
            margin: 20px 0;
            background: white;
        }
        .school-header {
            text-align: center;
            border-bottom: 2px solid #000;
            padding-bottom: 15px;
            margin-bottom: 20px;
        }
        .student-info {
            margin-bottom: 20px;
        }
        .info-row {
            display: flex;
            margin-bottom: 8px;
        }
        .info-label {
            font-weight: bold;
            min-width: 120px;
        }
        .online-pay-btn {
            margin-left: 10px;
            padding: 5px 10px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
        }
        .online-pay-btn:hover {
            background-color: #218838;
            text-decoration: none;
            color: white;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <?php if ($student): ?>
        <!-- Action Buttons -->
        <div class="text-center mb-3 no-print">
            <button onclick="history.back()" class="btn btn-secondary btn-lg me-2">
                <i class="fas fa-arrow-left"></i> পেছনে যান
            </button>
            <a href="public_home.php" class="btn btn-primary btn-lg me-2">
                <i class="fas fa-home"></i> হোম পেজ
            </a>
            <button onclick="window.print()" class="btn btn-success btn-lg">
                <i class="fas fa-print"></i> প্রিন্ট করুন
            </button>
        </div>

        <!-- Report Card -->
        <div class="report-card">
            <!-- School Header -->
            <div class="school-header">
                <h3>কুড়ুলগাছি মাধ্যমিক বিদ্যালয়</h3>
                <p>দামুড়হুদা, চুয়াডাঙ্গা, বাংলাদেশ</p>
                <h4>ফি ও উপস্থিতি রিপোর্ট</h4>
            </div>

            <!-- Student Information -->
            <div class="student-info">
                <h5>শিক্ষার্থীর তথ্য</h5>
                <div class="info-row">
                    <span class="info-label">নাম:</span>
                    <span><?php echo $student['first_name'] . ' ' . $student['last_name']; ?></span>
                </div>
                <div class="info-row">
                    <span class="info-label">রোল নং:</span>
                    <span><?php echo $student['roll_number']; ?></span>
                </div>
                <div class="info-row">
                    <span class="info-label">শ্রেণি:</span>
                    <span><?php echo $student['class_name'] . ($student['section'] ? ' - ' . $student['section'] : ''); ?></span>
                </div>
                <div class="info-row">
                    <span class="info-label">সেশন:</span>
                    <span><?php echo $session; ?></span>
                </div>
            </div>

            <!-- Fee and Attendance Summary -->
            <div>
                <h5>ফি ও উপস্থিতির সারসংক্ষেপ</h5>
                <?php if (isset($fee_summary)): ?>
                <div class="info-row">
                    <span class="info-label">ফি স্ট্যাটাস:</span>
                    <span>
                        <strong style="color: <?php echo $total_due > 0 ? 'red' : 'green'; ?>">
                            <?php 
                            if ($total_due > 0) {
                                echo 'বকেয়া (৳' . number_format($total_due, 2) . ')';
                                // Add Online Pay button for due amounts
                                echo ' <a href="fees/student_payment.php?student_id=' . $student['id'] . '&amount=' . $total_due . '" class="online-pay-btn">অনলাইন পে</a>';
                            } else {
                                echo 'পরিশোধিত';
                            }
                            ?>
                        </strong>
                    </span>
                </div>
                <?php else: ?>
                <div class="info-row">
                    <span class="info-label">ফি স্ট্যাটাস:</span>
                    <span>কোনো তথ্য পাওয়া যায়নি।</span>
                </div>
                <?php endif; ?>

                <?php if (isset($attendance_summary)): ?>
                    <?php if ($attendance_summary['total_days'] > 0): ?>
                    <div class="info-row">
                        <span class="info-label">উপস্থিতি:</span>
                        <span>
                            <?php
                            $present_days = $attendance_summary['present_days'] ?? 0;
                            $attendance_percentage = round(($present_days / $attendance_summary['total_days']) * 100, 2);
                            echo $attendance_percentage . '% (' . $present_days . '/' . $attendance_summary['total_days'] . ' দিন)';
                            ?>
                        </span>
                    </div>
                    <?php else: ?>
                    <div class="info-row">
                        <span class="info-label">উপস্থিতি:</span>
                        <span>এই সেশনের জন্য কোনো উপস্থিতির তথ্য পাওয়া যায়নি।</span>
                    </div>
                    <?php endif; ?>
                <?php else: ?>
                <div class="info-row">
                    <span class="info-label">উপস্থিতি:</span>
                    <span>উপস্থিতির তথ্য আনতে সমস্যা হয়েছে।</span>
                </div>
                <?php endif; ?>
            </div>

            <!-- Detailed Attendance Report -->
            <?php if (!empty($attendance_records)): ?>
            <div class="mt-4">
                <h5 class="mt-5">বিস্তারিত উপস্থিতি রিপোর্ট (সেশন: <?php echo $session; ?>)</h5>
                <div class="table-responsive">
                    <table class="table table-striped table-bordered">
                        <thead>
                            <tr>
                                <th>তারিখ</th>
                                <th>স্ট্যাটাস</th>
                                <th>মন্তব্য</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($attendance_records as $record): ?>
                                <tr>
                                    <td><?php echo date('d/m/Y', strtotime($record['date'])); ?></td>
                                    <td>
                                        <?php 
                                            $status = $record['status'];
                                            $badgeClass = 'bg-secondary';
                                            $statusText = 'N/A';
                                            if ($status === 'present') { $badgeClass = 'bg-success'; $statusText = 'Present'; }
                                            elseif ($status === 'absent') { $badgeClass = 'bg-danger'; $statusText = 'Absent'; }
                                            elseif ($status === 'late') { $badgeClass = 'bg-warning text-dark'; $statusText = 'Late'; }
                                            elseif ($status === 'excused') { $badgeClass = 'bg-info text-dark'; $statusText = 'Excused'; }
                                        ?>
                                        <span class="badge <?php echo $badgeClass; ?>"><?php echo $statusText; ?></span>
                                    </td>
                                    <td><?php echo htmlspecialchars($record['remarks'] ?? ''); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php endif; ?>

        </div>

        <?php else: ?>
        <div class="no-print">
            <div class="card shadow-sm">
                <div class="card-header">
                    <h4 class="card-title text-center">ফি ও উপস্থিতি অনুসন্ধান করুন</h4>
                </div>
                <div class="card-body">
                    <?php if (!empty($roll)):
 ?>
                        <div class="alert alert-warning text-center">
                            <i class="fas fa-exclamation-triangle"></i> 
                            শিক্ষার্থীকে খুঁজে পাওয়া যায়নি। রোল, শ্রেণি এবং সেশন সঠিক দিয়েছেন কিনা তা অনুগ্রহ করে যাচাই করুন।
                        </div>
                    <?php endif; ?>
                    <form method="GET" action="public_student_report.php" class="row g-3 justify-content-center">
                        <div class="col-md-4">
                            <label for="roll" class="form-label">রোল নম্বর</label>
                            <input type="text" id="roll" name="roll" class="form-control" value="<?php echo htmlspecialchars($roll); ?>" required>
                        </div>
                        <div class="col-md-4">
                            <label for="class" class="form-label">শ্রেণি</label>
                            <select id="class" name="class" class="form-select" required>
                                <option value="">শ্রেণি নির্বাচন করুন</option>
                                <?php foreach ($all_classes as $class_item): ?>
                                    <option value="<?php echo htmlspecialchars($class_item); ?>" <?php echo ($class_name === $class_item) ? 'selected' : ''; ?> >
                                        <?php echo htmlspecialchars($class_item); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="session" class="form-label">সেশন</label>
                            <select id="session" name="session" class="form-select" required>
                                <option value="">সেশন নির্বাচন করুন</option>
                                <?php foreach ($all_sessions as $session_item): ?>
                                    <option value="<?php echo htmlspecialchars($session_item); ?>" <?php echo ($session === $session_item) ? 'selected' : ''; ?> >
                                        <?php echo htmlspecialchars($session_item); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-12 text-center">
                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="fas fa-search"></i> অনুসন্ধান করুন
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>