<?php
$page_title = "মুহাসাবা রিপোর্ট";
include 'db_connect.php';
if ($_SESSION['role'] !== 'admin' && $_SESSION['role'] !== 'teacher') {
    die("এই পাতাটি দেখার জন্য আপনার অনুমতি নেই।");
}
include 'templates/header.php';
include_once __DIR__ . '/config/class_list.php';

// --- Initialize Variables ---
$report_data = [];
$start_date = null;
$end_date = null;
$report_type = $_GET['report_type'] ?? 'daily';
$selected_class_id = $_GET['class_id'] ?? null;

if (isset($_GET['generate_report']) && $selected_class_id) {
    // --- Date Calculation with NEW Yearly option ---
    $daily_date = $_GET['daily_date'] ?? date('Y-m-d');
    if ($report_type === 'daily') {
        $start_date = $end_date = $daily_date;
    } elseif ($report_type === 'weekly' && !empty($_GET['weekly_date'])) {
        $weekly_date = $_GET['weekly_date'];
        $week_parts = explode('-W', $weekly_date);
        $date = new DateTime(); $date->setISODate($week_parts[0], $week_parts[1]);
        $start_date = $date->format('Y-m-d'); $date->modify('+6 days');
        $end_date = $date->format('Y-m-d');
    } elseif ($report_type === 'monthly' && !empty($_GET['monthly_date'])) {
        $monthly_date = $_GET['monthly_date'];
        $start_date = date('Y-m-01', strtotime($monthly_date));
        $end_date = date('Y-m-t', strtotime($monthly_date));
    } elseif ($report_type === 'yearly' && !empty($_GET['yearly_date'])) {
        $yearly_date = $_GET['yearly_date'];
        $start_date = "$yearly_date-01-01";
        $end_date = "$yearly_date-12-31";
    }

    if ($start_date && $end_date) {
        // --- NEW Scoring Logic in SQL ---
        $sql = "
            SELECT 
                s.student_id, 
                s.name_bn,
                (
                    -- Lesson Quality Score
                    COALESCE(SUM(CASE mr.lesson_quality WHEN 'good' THEN 25 WHEN 'average' THEN 15 WHEN 'poor' THEN 5 ELSE 0 END), 0) +
                    -- Sabaq Para Quality Score
                    COALESCE(SUM(CASE mr.sabaq_para_quality WHEN 'good' THEN 25 WHEN 'average' THEN 15 WHEN 'poor' THEN 5 ELSE 0 END), 0) +
                    -- Amokta Quality Score
                    COALESCE(SUM(CASE mr.amokta_quality WHEN 'good' THEN 20 WHEN 'average' THEN 10 WHEN 'poor' THEN 5 ELSE 0 END), 0) +
                    -- Other Scores
                    (COALESCE(SUM(mr.congregation_prayers), 0) * 4) +
                    (COALESCE(SUM(mr.tahajjud_nafl_prayed), 0) * 3) +
                    (COALESCE(SUM(mr.served_elders), 0) * 3) +
                    (COALESCE(SUM(mr.used_miswak), 0) * 2) +
                    (COALESCE(SUM(mr.greeted), 0) * 2)
                ) as total_score
            FROM students s
            LEFT JOIN muhasaba_records mr ON s.id = mr.student_id AND mr.record_date BETWEEN ? AND ?
            WHERE s.class_id = ? AND s.status = 'active'
            GROUP BY s.id, s.student_id, s.name_bn
            ORDER BY total_score DESC, s.student_id ASC
        ";
        
        $stmt = $conn->prepare($sql);
        if($stmt === false) { die("Error preparing query: " . $conn->error); }
        $stmt->bind_param("ssi", $start_date, $end_date, $selected_class_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $report_data = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
    }
}
?>

<div class="card shadow-sm" id="report-container">
    <div class="card-header bg-info text-white"><h4 class="mb-0">মুহাসাবা রিপোর্ট (র‍্যাঙ্কিং)</h4></div>
    <div class="card-body">
        <!-- Filter Form with NEW Yearly option -->
        <form id="filter-form" method="GET" action="" class="p-3 mb-4 border rounded bg-light no-print">
            <div class="row align-items-end g-3">
                <div class="col-md-3">
                    <label class="form-label fw-bold">রিপোর্টের ধরণ</label>
                    <select id="report_type_select" name="report_type" class="form-select">
                        <option value="daily" <?php if($report_type == 'daily') echo 'selected'; ?>>দৈনিক</option>
                        <option value="weekly" <?php if($report_type == 'weekly') echo 'selected'; ?>>সাপ্তাহিক</option>
                        <option value="monthly" <?php if($report_type == 'monthly') echo 'selected'; ?>>মাসিক</option>
                        <option value="yearly" <?php if($report_type == 'yearly') echo 'selected'; ?>>বাৎসরিক</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label fw-bold">তারিখ / সময়কাল</label>
                    <input type="date" id="daily_date_input" name="daily_date" class="form-control" value="<?php echo $_GET['daily_date'] ?? date('Y-m-d'); ?>">
                    <input type="week" id="weekly_date_input" name="weekly_date" class="form-control" value="<?php echo $_GET['weekly_date'] ?? ''; ?>" style="display:none;">
                    <input type="month" id="monthly_date_input" name="monthly_date" class="form-control" value="<?php echo $_GET['monthly_date'] ?? ''; ?>" style="display:none;">
                    <!-- Yearly Input -->
                    <select id="yearly_date_input" name="yearly_date" class="form-select" style="display:none;">
                        <?php for ($i = date('Y'); $i >= date('Y') - 5; $i--): ?>
                            <option value="<?php echo $i; ?>" <?php if(isset($_GET['yearly_date']) && $_GET['yearly_date'] == $i) echo 'selected'; ?>><?php echo $i; ?></option>
                        <?php endfor; ?>
                    </select>
                </div>
                <div class="col-md-3"><label class="form-label fw-bold"> শ্রেণি</label><select name="class_id" class="form-select" required><option value="">-- শ্রেণি --</option><?php foreach($classes as $id => $name) { $selected = ($selected_class_id == $id) ? 'selected' : ''; echo "<option value='$id' $selected>$name</option>"; } ?></select></div>
                <div class="col-md-3"><button type="submit" name="generate_report" class="btn btn-primary w-100">জেনারেট রিপোর্ট</button></div>
            </div>
        </form>

        <?php if (isset($_GET['generate_report']) && $selected_class_id): ?>
            <div class="text-center mt-4">
                <h4>মুহাসাবা র‍্যাঙ্কিং (শ্রেণি: <?php echo htmlspecialchars($classes[$selected_class_id]); ?>)</h4>
                <p class="lead"><strong>সময়কাল:</strong> <?php echo date('d M, Y', strtotime($start_date)); ?> থেকে <?php echo date('d M, Y', strtotime($end_date)); ?></p>
                <hr>
            </div>
            <?php if(!empty($report_data)): ?>
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead class="table-light text-center align-middle"><tr><th>অবস্থান</th><th>ছাত্রের নাম</th><th>মোট স্কোর</th></tr></thead>
                        <tbody>
                            <?php $rank = 1; foreach ($report_data as $data): ?>
                            <tr class="text-center">
                                <td class="fw-bold"><?php echo $rank++; ?></td>
                                <td class="text-start"><?php echo htmlspecialchars($data['name_bn']); ?></td>
                                <td class="fw-bold"><?php echo number_format($data['total_score']); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?><div class="alert alert-warning text-center">এই ফিল্টার অনুযায়ী কোনো মুহাসাবা রেকর্ড পাওয়া যায়নি।</div><?php endif; ?>
            <div class="text-center mt-3 no-print"><button class="btn btn-secondary" onclick="window.print()"><i class="fas fa-print"></i> প্রিন্ট রিপোর্ট</button></div>
        <?php endif; ?>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    function toggleDateInputs() {
        const reportType = $('#report_type_select').val();
        $('#daily_date_input, #weekly_date_input, #monthly_date_input, #yearly_date_input').hide();
        if (reportType === 'daily') $('#daily_date_input').show();
        else if (reportType === 'weekly') $('#weekly_date_input').show();
        else if (reportType === 'monthly') $('#monthly_date_input').show();
        else if (reportType === 'yearly') $('#yearly_date_input').show();
    }
    $('#report_type_select').on('change', toggleDateInputs);
    toggleDateInputs();
});
</script>
<style> @media print { .no-print { display: none !important; } } </style>
<?php include 'templates/footer.php'; ?>

"please realize this code,  I tested it and found that it doesn't count the score. please fix it"