<?php 
// Filename: student_reports.php
require 'config.php';
requireLogin();

$uid       = $_SESSION['user_id'];
$back_link = 'dashboard.php'; 

// --- SAFE SETTINGS FETCHING ---
function safeGet($key, $default = '') {
    return function_exists('getSetting') ? getSetting($key, $default) : $default;
}

$school_name        = safeGet('school_name', 'SMK Muadzam Shah');
$school_address     = safeGet('school_address', '');
$school_phone       = safeGet('school_phone', '');
$school_email       = safeGet('school_email', '');
$school_code        = safeGet('school_code', '');
$letter_ref_prefix  = safeGet('letter_ref_prefix', 'Rujukan : ');
$letter_logo_path   = safeGet('letter_logo_path', '');
$official_logo_path = safeGet('official_logo_path', '');

$active_logo = $letter_logo_path ?: $official_logo_path;
$addr_print  = preg_replace('/,\s*/', ",<br>", htmlspecialchars($school_address));

// 1. GET ASSIGNED CLASS
$stmt = $pdo->prepare("SELECT id, class_name, form_level FROM classes WHERE class_teacher_id = ?");
$stmt->execute([$uid]);
$my_class = $stmt->fetch();

if (!$my_class) {
    die("<div class='container mt-5 text-center'><div class='alert alert-warning shadow-sm border-0 rounded-4'><strong>Access Denied</strong><br>You are not assigned as a Class Teacher.<br><a href='{$back_link}' class='btn btn-sm btn-dark mt-3 rounded-pill px-4'>Back to Dashboard</a></div></div>");
}

$class_id   = $my_class['id'];
$class_name = $my_class['class_name'];
$form_level = $my_class['form_level'];

// --- SMART DATE LOGIC & TAB PERSISTENCE ---
$year       = date('Y');
// Default to 'monthly' since we removed 'list' from UI
$active_tab = $_GET['active_tab'] ?? 'monthly'; 

if (isset($_GET['month_filter']) && $_GET['month_filter'] !== '') {
    $selected_month = (int) $_GET['month_filter'];
    $start_date     = date('Y-m-01', mktime(0, 0, 0, $selected_month, 1, $year));
    $end_date       = date('Y-m-t', mktime(0, 0, 0, $selected_month, 1, $year));
    $active_tab     = 'monthly';
} else {
    $start_date = $_GET['start'] ?? date('Y-m-01');
    $end_date   = $_GET['end']   ?? date('Y-m-t');
}

// 2. CALCULATION ENGINE
$week_start   = safeGet('week_start_day', 1); 
$weekend_days = ($week_start == 1) ? [6, 7] : [5, 6]; 

$hol_stmt = $pdo->prepare("SELECT start_date, end_date, description, type FROM school_holidays WHERE YEAR(start_date) = ?");
$hol_stmt->execute([$year]);
$all_events = $hol_stmt->fetchAll();

$holidays = [];
foreach ($all_events as $event) {
    if ($event['type'] === 'school_event' || $event['type'] === 'cuti_ganti') continue;
    $holidays[] = $event;
}

$holiday_map = [];
foreach ($holidays as $h) {
    $curr = strtotime($h['start_date']);
    $end  = strtotime($h['end_date']);
    while ($curr <= $end) {
        $holiday_map[date('Y-m-d', $curr)] = $h['description'];
        $curr = strtotime('+1 day', $curr);
    }
}

if (!function_exists('calculateNetDays')) {
    function calculateNetDays($start, $end, $holidays, $weekends) {
        $s = strtotime($start); 
        $e = strtotime($end);
        $school = 0; 
        $hol    = 0;

        while ($s <= $e) {
            $d   = date('N', $s); 
            $ymd = date('Y-m-d', $s);
            $is_we = in_array($d, $weekends, true);
            $is_ho = false;
            foreach ($holidays as $h) {
                if ($ymd >= $h['start_date'] && $ymd <= $h['end_date']) { $is_ho = true; break; }
            }
            if ($is_we) {} elseif ($is_ho) { $hol++; } else { $school++; }
            $s = strtotime('+1 day', $s);
        }
        return ['school' => $school, 'holiday' => $hol];
    }
}

$period_stats = calculateNetDays($start_date, $end_date, $holidays, $weekend_days);

// 3. SSDM & ATTENDANCE + DISCIPLINE
$disc_sql = "SELECT sd.student_id, sd.infraction, sd.severity, sd.reported_date FROM student_discipline sd JOIN students s ON sd.student_id = s.id WHERE s.class_id = ? AND YEAR(sd.reported_date) = ? ORDER BY sd.reported_date ASC";
$stmt = $pdo->prepare($disc_sql);
$stmt->execute([$class_id, $year]);
$disc_raw = $stmt->fetchAll(PDO::FETCH_GROUP); 

$ssdm_sql = "SELECT s.id, s.full_name, s.ic_number, s.parent_phone, sa.date, sa.status FROM students s LEFT JOIN student_attendance sa ON s.id = sa.student_id AND YEAR(sa.date) = ? WHERE s.class_id = ? ORDER BY s.id, sa.date DESC";
$stmt = $pdo->prepare($ssdm_sql);
$stmt->execute([$year, $class_id]);
$raw_data = $stmt->fetchAll(PDO::FETCH_GROUP); 

$student_reports      = [];
$view_month           = (int) date('m', strtotime($start_date));
$view_year            = (int) date('Y', strtotime($start_date));
$days_in_view_month   = cal_days_in_month(CAL_GREGORIAN, $view_month, $view_year);
$monthly_attendance_map = [];

foreach ($raw_data as $sid => $records) {
    if (empty($records)) continue;

    $info           = $records[0]; 
    $present_period = 0;
    
    $monthly_attendance_map[$sid] = [];

    foreach ($records as $r) {
        $st = isset($r['status']) ? strtolower(trim((string)$r['status'])) : '';
        $dt = $r['date'] ?? null;
        if (!empty($dt) && $dt >= $start_date && $dt <= $end_date && ($st === 'present' || $st === '1' || $st === 'p')) {
            $present_period++;
        }
        if (!empty($dt)) {
            $clean_date_key = substr($dt, 0, 10); 
            $monthly_attendance_map[$sid][$clean_date_key] = $st;
        }
    }

    $pct = ($period_stats['school'] > 0) ? round(($present_period / $period_stats['school']) * 100) : 0;

    // DISCIPLINE LOGIC
    $disc_records = $disc_raw[$sid] ?? [];
    $disc_status = null;
    $latest_infraction = '';
    $disc_count = count($disc_records);
    if (!empty($disc_records)) {
        $has_major = false;
        foreach ($disc_records as $dr) {
            $inf = $dr['infraction'] ?? '';
            if (($dr['severity'] ?? '') === 'high' || stripos($inf, 'rokok') !== false || stripos($inf, 'gaduh') !== false) {
                $has_major = true; break;
            }
        }
        $disc_status = $has_major ? ['title' => 'Major', 'color' => 'danger'] : ['title' => 'Minor', 'color' => 'warning'];
        $latest_infraction = $disc_records[$disc_count - 1]['infraction'] ?? '';
    }
    
    $student_reports[] = [
        'id' => $sid, 'name' => $info['full_name'], 'ic' => $info['ic_number'], 'parent' => $info['parent_phone'],
        'pct' => $pct, 
        'disc_status' => $disc_status, 'disc_count' => $disc_count, 'latest_infraction' => $latest_infraction
    ];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>Class Report - <?= htmlspecialchars($class_name) ?></title>
    
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">

    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; ... }
        /* HEADER */
        .app-header {
            background: var(--primary-grad); padding: 30px 20px 80px 20px;
            border-radius: 0 0 35px 35px; color: white; text-align: center;
        }

        /* FLOATING CARD FOR TABS */
        .floating-card {
            background: white; margin: -60px 20px 20px 20px;
            border-radius: 24px; padding: 10px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.08);
            position: relative; z-index: 10;
        }

        /* TABS STYLING */
        .nav-pills .nav-link { 
            border-radius: 16px; font-weight: 600; color: var(--text-gray); 
            padding: 12px; width: 100%; text-align: center; background: transparent;
        }
        .nav-pills .nav-link.active { background: #f5f3ff; color: #8B5CF6; }

        /* STUDENT ITEM (Discipline) */
        .student-item { 
            background: white; border-radius: 16px; padding: 15px; margin-bottom: 10px; 
            border: 1px solid #f1f5f9; display: flex; align-items: center; justify-content: space-between;
            box-shadow: 0 2px 5px rgba(0,0,0,0.02);
        }
        .student-item.disc-flagged { border-left: 4px solid #fd7e14; }

        /* MONTHLY TABLE */
        .monthly-table-wrapper { overflow-x: auto; white-space: nowrap; border-radius: 16px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); background: white; margin-top: 10px; }
        .monthly-table { width: 100%; border-collapse: separate; border-spacing: 2px; }
        .monthly-table th, .monthly-table td { padding: 10px; text-align: center; font-size: 0.75rem; }
        .monthly-table th { background: #f8f9fa; font-weight: 700; color: #64748b; }
        .monthly-table .col-name { position: sticky; left: 0; background: #fff; z-index: 5; text-align: left; font-weight: 700; border-right: 1px solid #f1f5f9; padding-left: 15px; }
        
        .cell-p { background-color: #d1e7dd; color: #0f5132; border-radius: 4px; } 
        .cell-a { background-color: #f8d7da; color: #842029; border-radius: 4px; } 
        .cell-h { background-color: #cff4fc; color: #055160; border-radius: 4px; } 
        .cell-w { background-color: #f1f5f9; color: #adb5bd; }

        /* PRINT STYLES */
        @media print { 
            body { background: #fff !important; padding: 0; } 
            .no-print, .floating-card, .app-header { display: none !important; } 
            .print-area { display: block !important; } 
        }

        /* BOTTOM NAV 
        .bottom-nav { position: fixed; bottom: 0; left: 0; right: 0; background: white; padding: 10px 30px 25px 30px; display: flex; justify-content: space-between; border-radius: 30px 30px 0 0; box-shadow: 0 -5px 20px rgba(0,0,0,0.05); z-index: 100; }
        .nav-btn { display: flex; flex-direction: column; align-items: center; color: #94a3b8; text-decoration: none; font-size: 0.7rem; font-weight: 600; }
        .nav-btn.active { color: #8B5CF6; }
        .nav-btn i { font-size: 1.4rem; margin-bottom: 4px; } */
    </style>
</head>
<body>

    <div class="app-header no-print">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold fs-5">Reports</div>
            <div style="width: 24px;"></div>
        </div>
        <h2 class="mb-0 fw-bold"><?= htmlspecialchars($class_name) ?></h2>
        <div class="opacity-75 small">Form <?= htmlspecialchars($form_level) ?></div>
    </div>

    <div class="floating-card no-print">
        <ul class="nav nav-pills" id="chartTabs" role="tablist">
            <li class="nav-item col-6 pe-1">
                <button class="nav-link <?= ($active_tab=='monthly' || $active_tab=='list') ? 'active' : '' ?>" data-bs-toggle="tab" data-bs-target="#tab-monthly">
                    Monthly
                </button>
            </li>
            <li class="nav-item col-6 ps-1">
                <button class="nav-link <?= $active_tab=='disc'?'active':'' ?>" data-bs-toggle="tab" data-bs-target="#tab-disc">
                    Discipline
                </button>
            </li>
        </ul>
    </div>

    <div class="px-3 pb-4 no-print">
        <div class="tab-content">
            
            <div class="tab-pane fade <?= ($active_tab=='monthly' || $active_tab=='list') ? 'show active' : '' ?>" id="tab-monthly">
                
                <div class="d-flex justify-content-center mb-3">
                    <form method="GET" class="d-flex align-items-center bg-white rounded-pill p-1 shadow-sm border">
                        <input type="hidden" name="active_tab" value="monthly">
                        <select name="month_filter" class="form-select form-select-sm border-0 bg-transparent fw-bold" style="width:auto; outline:none; box-shadow:none;" onchange="this.form.submit()">
                            <?php 
                            $curr_m = (isset($_GET['month_filter']) && $_GET['month_filter'] !== '') ? (int) $_GET['month_filter'] : (int) date('n', strtotime($start_date)); 
                            for ($m=1; $m<=12; $m++): ?>
                                <option value="<?= $m ?>" <?= $m==$curr_m ? 'selected':'' ?>><?= date('F', mktime(0,0,0,$m,1)) ?></option>
                            <?php endfor; ?>
                        </select>
                        <i class="bi bi-calendar3 text-muted me-3"></i>
                    </form>
                </div>

                <div class="monthly-table-wrapper">
                    <table class="monthly-table">
                        <thead>
                            <tr>
                                <th class="col-name">Student Name</th>
                                <?php for ($d=1; $d<=$days_in_view_month; $d++): 
                                    $ts = strtotime(sprintf('%04d-%02d-%02d', $view_year, $view_month, $d)); 
                                    $dow = date('D', $ts); 
                                    $is_we = in_array((int)date('N', $ts), $weekend_days, true); 
                                    $color = $is_we ? 'text-muted' : 'text-dark'; 
                                ?>
                                <th class="<?= $color ?>">
                                    <div><?= substr($dow, 0, 1) ?></div>
                                    <div><?= $d ?></div>
                                </th>
                                <?php endfor; ?>
                                <th>%</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($student_reports as $s): ?>
                            <tr>
                                <td class="col-name text-truncate" style="max-width:150px;"><?= htmlspecialchars($s['name']) ?></td>
                                <?php for ($d=1; $d<=$days_in_view_month; $d++): 
                                    $date_key = sprintf('%04d-%02d-%02d', $view_year, $view_month, $d); 
                                    $day_num = (int) date('N', strtotime($date_key)); 
                                    $status_code = '&nbsp;'; 
                                    $cell_class = ''; 

                                    if (in_array($day_num, $weekend_days, true)) { 
                                        $cell_class = 'cell-w'; 
                                    } elseif (isset($holiday_map[$date_key])) { 
                                        $cell_class = 'cell-h'; $status_code = 'H'; 
                                    } elseif (isset($monthly_attendance_map[$s['id']][$date_key])) { 
                                        $status = $monthly_attendance_map[$s['id']][$date_key]; 
                                        if ($status === 'present' || $status === '1' || $status === 'p') { $cell_class = 'cell-p'; $status_code = 'P'; } 
                                        elseif ($status === 'absent' || $status === '0' || $status === 'a') { $cell_class = 'cell-a'; $status_code = 'A'; } 
                                    } 
                                ?>
                                <td class="<?= $cell_class ?>"><?= $status_code ?></td>
                                <?php endfor; ?>
                                <td class="fw-bold text-end"><?= $s['pct'] ?>%</td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="tab-pane fade <?= $active_tab=='disc'?'show active':'' ?>" id="tab-disc">
                <div class="mb-3 px-1 small text-muted text-uppercase fw-bold ls-1">Record List</div>
                <?php foreach ($student_reports as $s): ?>
                    <div class="student-item <?= $s['disc_status'] ? 'disc-flagged' : '' ?>">
                        <div class="me-2 overflow-hidden">
                            <div class="fw-bold text-dark text-truncate"><?= htmlspecialchars($s['name']) ?></div>
                            <?php if ($s['disc_status']): ?>
                                <div class="mt-1 small text-danger fw-bold">
                                    <i class="bi bi-exclamation-circle me-1"></i> <?= htmlspecialchars($s['latest_infraction']) ?>
                                </div>
                            <?php else: ?>
                                <div class="mt-1 small text-success bg-success bg-opacity-10 d-inline-block px-2 rounded">Clean Record</div>
                            <?php endif; ?>
                        </div>
                        <div class="text-end">
                            <?php if ($s['disc_count'] > 0): ?>
                                <span class="badge bg-warning text-dark rounded-pill"><?= $s['disc_count'] ?> Cases</span>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

        </div>
    </div>

    <div class="text-center no-print mt-4">
        <button onclick="window.print()" class="btn btn-outline-secondary btn-sm rounded-pill px-4">
            <i class="bi bi-printer me-2"></i>Print Report
        </button>
    </div>

    <?php include 'menu.php'; ?>

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