<?php
// Filename: api_dashboard.php
require 'config.php';

error_reporting(0); 
ini_set('display_errors', 0);
ob_start();

header('Content-Type: application/json');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

if (empty($_SESSION['user_id'])) { ob_clean(); echo json_encode(['error' => 'auth_required']); exit; }
session_write_close(); 

$user_id = $_SESSION['user_id'];
$since = $_GET['since'] ?? date('Y-m-d H:i:s', strtotime('-10 seconds'));
$today = date('Y-m-d'); 
$now = date('H:i:s'); 
$day_num = date('N');

$response = [
    'notifications' => 0, 
    'latest_alert' => null,
    'announcement' => null,
    'birthdays' => [], // List of names
    'next_holiday' => null,
    'att_health' => null, 
    'status' => null
];

try {
    global $pdo;

    // 1. Notifications
    $n_stmt = $pdo->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0");
    $n_stmt->execute([$user_id]);
    $response['notifications'] = (int)$n_stmt->fetchColumn();

    if ($response['notifications'] > 0) {
        $l_stmt = $pdo->prepare("SELECT message FROM notifications WHERE user_id = ? AND is_read = 0 AND created_at > ? ORDER BY created_at DESC LIMIT 1");
        $l_stmt->execute([$user_id, $since]);
        if ($new = $l_stmt->fetchColumn()) $response['latest_alert'] = ['message' => $new];
    }

    // 2. Announcement (Ticker)
    $a_stmt = $pdo->prepare("SELECT title, message FROM announcements WHERE type = 'global' AND start_date <= NOW() AND (end_date IS NULL OR end_date >= NOW()) ORDER BY created_at DESC LIMIT 1");
    $a_stmt->execute();
    $response['announcement'] = $a_stmt->fetch(PDO::FETCH_ASSOC);

    // 3. Holiday Check
    $h_stmt = $pdo->prepare("SELECT description FROM school_holidays WHERE ? BETWEEN start_date AND end_date LIMIT 1");
    $h_stmt->execute([$today]);
    $holiday_row = $h_stmt->fetch(PDO::FETCH_ASSOC);
    $is_holiday = !empty($holiday_row);
    
    // 4. Next Holiday
    $nh_stmt = $pdo->prepare("SELECT description, DATEDIFF(start_date, NOW()) as days_left FROM school_holidays WHERE start_date > NOW() ORDER BY start_date ASC LIMIT 1");
    $nh_stmt->execute();
    $response['next_holiday'] = $nh_stmt->fetch(PDO::FETCH_ASSOC);

    // 5. CLASS TEACHER DATA
    $ct_stmt = $pdo->prepare("SELECT id FROM classes WHERE class_teacher_id = ?");
    $ct_stmt->execute([$user_id]);
    $class_id = $ct_stmt->fetchColumn();

    if ($class_id) {
        // A. Birthdays (Only for my class)
        $mmdd = date('md');
        $b_stmt = $pdo->prepare("SELECT full_name FROM students WHERE class_id = ? AND SUBSTRING(ic_number, 3, 4) = ?");
        $b_stmt->execute([$class_id, $mmdd]);
        $response['birthdays'] = $b_stmt->fetchAll(PDO::FETCH_COLUMN);

        // B. Attendance Trend
        $tot_stmt = $pdo->prepare("SELECT COUNT(*) FROM students WHERE class_id = ?");
        $tot_stmt->execute([$class_id]);
        $total_std = (int)$tot_stmt->fetchColumn();

        if ($total_std > 0) {
            // Today
            $abs_today = $pdo->prepare("SELECT COUNT(DISTINCT student_id) FROM student_attendance WHERE student_id IN (SELECT id FROM students WHERE class_id=?) AND date = ? AND status='absent'");
            $abs_today->execute([$class_id, $today]);
            $pct_today = 100 - (($abs_today->fetchColumn() / $total_std) * 100);

            // Previous Recorded Day
            $prev_date_q = $pdo->prepare("SELECT date FROM student_attendance WHERE student_id IN (SELECT id FROM students WHERE class_id=?) AND date < ? ORDER BY date DESC LIMIT 1");
            $prev_date_q->execute([$class_id, $today]);
            $prev_date = $prev_date_q->fetchColumn();

            $pct_prev = 0;
            if ($prev_date) {
                $abs_prev = $pdo->prepare("SELECT COUNT(DISTINCT student_id) FROM student_attendance WHERE student_id IN (SELECT id FROM students WHERE class_id=?) AND date = ? AND status='absent'");
                $abs_prev->execute([$class_id, $prev_date]);
                $pct_prev = 100 - (($abs_prev->fetchColumn() / $total_std) * 100);
            }

            $diff = $pct_today - $pct_prev;
            $response['att_health'] = [
                'trend' => ($diff >= 0) ? 'up' : 'down',
                'diff' => round(abs($diff), 1)
            ];
        }
    }

    // 6. Live Status Text
    if ($is_holiday) {
        $response['status'] = ['text' => $holiday_row['description'], 'sub' => "No classes today"];
    } elseif ($day_num >= 6) {
        $response['status'] = ['text' => "Weekend Break", 'sub' => "Enjoy your weekend"];
    } else {
        $sched_stmt = $pdo->prepare("SELECT t.id, t.start_time, t.end_time, t.subject, c.class_name FROM timetable t JOIN classes c ON t.class_id = c.id WHERE t.teacher_id = ? AND t.day_of_week = ? ORDER BY start_time");
        $sched_stmt->execute([$user_id, $day_num]);
        $classes = $sched_stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $found = false;
        foreach ($classes as $cls) {
            if ($now >= $cls['start_time'] && $now <= $cls['end_time']) {
                $response['status'] = [
                    'text' => $cls['subject'],
                    'sub'  => $cls['class_name'] . " • Ends " . substr($cls['end_time'], 0, 5)
                ];
                $found = true; break;
            }
        }
        if (!$found) {
            $response['status'] = ['text' => "Free Period", 'sub' => "No active class"];
        }
    }

    ob_clean(); echo json_encode($response);

} catch (Exception $e) { ob_clean(); echo json_encode(['error' => $e->getMessage()]); }
?>