<?php
header("Content-Type: application/json");
require("../../includes/config.php");

// Unique pagination variables
$stu_limit   = 10; 
$stu_page    = isset($_GET['stu_page']) ? (int)$_GET['stu_page'] : 1;
$stu_offset = ($stu_page - 1) * $stu_limit;

// --- Receive filters from GET request ---
$year_id    = $_GET['year_id'] ?? ''; 
$class_id   = $_GET['class_id'] ?? '';
$search     = $_GET['search'] ?? '';
$section_id = $_GET['section_id'] ?? ''; 
$medium_id  = $_GET['medium_id'] ?? ''; 

try {
    $target_year = !empty($year_id) ? $year_id : APP_YEAR_ID;
    
    $params = [':year_id' => $target_year];
    $where_clauses = ["e.academic_year_id = :year_id"];

    if (!empty($class_id)) {
        $where_clauses[] = "e.class_id = :class_id";
        $params[':class_id'] = $class_id;
    }

    if (!empty($section_id)) {
        $where_clauses[] = "e.section_id = :section_id";
        $params[':section_id'] = $section_id;
    }

    if (!empty($medium_id)) {
        $where_clauses[] = "e.medium_id = :medium_id";
        $params[':medium_id'] = $medium_id;
    }

    if (!empty($search)) {
        $where_clauses[] = "(s.student_name LIKE :search OR e.roll_no LIKE :search OR s.parent_phone LIKE :search)";
        $params[':search'] = "%$search%";
    }

    $where_sql = " WHERE " . implode(" AND ", $where_clauses);

    // 1. Get total count for pagination
    $count_sql = "SELECT COUNT(*) FROM students s JOIN enrollments e ON s.id = e.student_id $where_sql";
    $count_stmt = $pdo->prepare($count_sql);
    $count_stmt->execute($params);
    $total_records = $count_stmt->fetchColumn();
    $total_pages = ceil($total_records / $stu_limit);

    // 2. Get data with Limit (Removed stream_name and JOIN streams)
    $data_sql = "SELECT s.id, s.student_name, s.parent_phone, s.student_photo, 
                        e.promotion_status, e.id AS enrollment_id, e.roll_no, 
                        c.class_name, 
                        sec.section_name,
                        m.medium_name 
                 FROM students s
                 JOIN enrollments e ON s.id = e.student_id
                 JOIN classes c ON e.class_id = c.id
                 LEFT JOIN sections sec ON e.section_id = sec.id
                 LEFT JOIN mediums m ON e.medium_id = m.id
                 $where_sql 
                 ORDER BY c.id ASC, e.roll_no ASC 
                 LIMIT $stu_limit OFFSET $stu_offset";
    
    $stmt = $pdo->prepare($data_sql);
    $stmt->execute($params);
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        "status"      => true, 
        "data"        => $students,
        "total_pages" => $total_pages,
        "curr_page"   => $stu_page,
        "debug_year"  => $target_year 
    ]);
} catch (Exception $e) {
    echo json_encode(["status" => false, "msg" => $e->getMessage()]);
}
?>