<?php
declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../config.php';
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

header('Content-Type: application/json');
$conn   = getDBConnection();
$action = trim((string) ($_POST['action'] ?? $_GET['action'] ?? ''));
$userId = (int) $_SESSION['user_id'];

if (!$conn instanceof mysqli) {
    echo json_encode(['success' => false, 'message' => 'Database unavailable']); exit;
}

// Ensure attendance table exists
$conn->query("CREATE TABLE IF NOT EXISTS attendance (
  id INT AUTO_INCREMENT PRIMARY KEY,
  student_id INT NOT NULL,
  class_name VARCHAR(100) NOT NULL,
  attendance_date DATE NOT NULL,
  status ENUM('present','absent','late','excused') NOT NULL DEFAULT 'present',
  recorded_by INT DEFAULT NULL,
  notes VARCHAR(255) DEFAULT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY unique_attendance (student_id, attendance_date),
  KEY idx_class_date (class_name, attendance_date),
  KEY idx_student (student_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

switch ($action) {

    // ── GET STUDENTS FOR A CLASS (for take-register tab) ──────────────
    case 'get_students':
        $class = trim((string) ($_GET['class'] ?? ''));
        if ($class === '') { echo json_encode([]); break; }

        $stmt = $conn->prepare(
            "SELECT s.id,
                    CONCAT(s.first_name, ' ', s.last_name) AS full_name,
                    s.student_id AS student_id_number,
                    a.status AS today_status
             FROM students s
             LEFT JOIN attendance a
               ON a.student_id = s.id AND a.attendance_date = ?
             WHERE s.class = ? AND s.status = 'active'
             ORDER BY s.first_name, s.last_name"
        );
        $date = trim((string) ($_GET['date'] ?? date('Y-m-d')));
        $stmt->bind_param('ss', $date, $class);
        $stmt->execute();
        $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        echo json_encode($rows);
        break;

    // ── GET SAVED REGISTER (check if already submitted) ───────────────
    case 'get_register':
        $class = trim((string) ($_GET['class'] ?? ''));
        $date  = trim((string) ($_GET['date'] ?? date('Y-m-d')));
        if ($class === '' || $date === '') { echo json_encode(['submitted' => false, 'records' => []]); break; }

        $stmt = $conn->prepare(
            "SELECT a.student_id, a.status, a.notes,
                    CONCAT(s.first_name, ' ', s.last_name) AS full_name
             FROM attendance a
             INNER JOIN students s ON s.id = a.student_id
             WHERE a.class_name = ? AND a.attendance_date = ?
             ORDER BY s.first_name, s.last_name"
        );
        $stmt->bind_param('ss', $class, $date);
        $stmt->execute();
        $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        echo json_encode(['submitted' => count($rows) > 0, 'records' => $rows]);
        break;

    // ── SAVE REGISTER ─────────────────────────────────────────────────
    case 'save_register':
        $class   = trim((string) ($_POST['class'] ?? ''));
        $date    = trim((string) ($_POST['date'] ?? date('Y-m-d')));
        $records = $_POST['records'] ?? [];   // array of {id, status, notes}

        if ($class === '' || $date === '' || !is_array($records) || count($records) === 0) {
            echo json_encode(['success' => false, 'message' => 'Missing class, date, or records']); break;
        }

        // Validate date (must not be in future)
        if ($date > date('Y-m-d')) {
            echo json_encode(['success' => false, 'message' => 'Cannot record attendance for a future date']); break;
        }

        $allowed_statuses = ['present','absent','late','excused'];
        $stmt = $conn->prepare(
            "INSERT INTO attendance (student_id, class_name, attendance_date, status, recorded_by, notes)
             VALUES (?, ?, ?, ?, ?, ?)
             ON DUPLICATE KEY UPDATE status = VALUES(status), recorded_by = VALUES(recorded_by), notes = VALUES(notes)"
        );

        $saved = 0;
        foreach ($records as $rec) {
            $sid    = (int) ($rec['id'] ?? 0);
            $status = in_array($rec['status'] ?? '', $allowed_statuses) ? $rec['status'] : 'present';
            $notes  = strip_tags(trim(substr((string) ($rec['notes'] ?? ''), 0, 255)));
            if ($sid <= 0) continue;
            // student_id INT, class_name STR, date STR, status STR, recorded_by INT, notes STR
            $stmt->bind_param('isssis', $sid, $class, $date, $status, $userId, $notes);
            $stmt->execute();
            $saved++;
        }
        $stmt->close();
        echo json_encode(['success' => true, 'message' => "Attendance saved for {$saved} student(s)"]);
        break;

    // ── GET RECORDS (View Records tab — paginated/filtered) ───────────
    case 'get_records':
        $class  = trim((string) ($_GET['class']  ?? ''));
        $from   = trim((string) ($_GET['from']   ?? ''));
        $to     = trim((string) ($_GET['to']     ?? ''));
        $status = trim((string) ($_GET['status'] ?? ''));

        $where  = ['1=1'];
        $params = [];
        $types  = '';

        if ($class !== '')  { $where[] = 'a.class_name = ?';      $params[] = $class;  $types .= 's'; }
        if ($from  !== '')  { $where[] = 'a.attendance_date >= ?'; $params[] = $from;   $types .= 's'; }
        if ($to    !== '')  { $where[] = 'a.attendance_date <= ?'; $params[] = $to;     $types .= 's'; }
        if ($status !== '') { $where[] = 'a.status = ?';           $params[] = $status; $types .= 's'; }

        $w = implode(' AND ', $where);
        $sql = "SELECT a.id, a.attendance_date, a.status, a.notes,
                       CONCAT(s.first_name, ' ', s.last_name) AS full_name,
                       s.student_id AS student_id_number, a.class_name,
                       CONCAT(COALESCE(u.full_name,'')) AS recorded_by_name
                FROM attendance a
                INNER JOIN students s ON s.id = a.student_id
                LEFT JOIN users u ON u.id = a.recorded_by
                WHERE {$w}
                ORDER BY a.attendance_date DESC, s.first_name, s.last_name
                LIMIT 500";

        $stmt = $conn->prepare($sql);
        if ($types !== '') $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        echo json_encode($rows);
        break;

    // ── GET REPORT (summary stats per class / per student) ────────────
    case 'get_report':
        $class = trim((string) ($_GET['class'] ?? ''));
        $from  = trim((string) ($_GET['from']  ?? date('Y-m-01')));
        $to    = trim((string) ($_GET['to']    ?? date('Y-m-d')));

        if ($class === '') {
            // Class-level summary: all classes
            $stmt = $conn->prepare(
                "SELECT a.class_name,
                        COUNT(DISTINCT a.attendance_date) AS school_days,
                        COUNT(DISTINCT a.student_id) AS total_students,
                        SUM(a.status = 'present') AS present_count,
                        SUM(a.status = 'absent')  AS absent_count,
                        SUM(a.status = 'late')    AS late_count,
                        SUM(a.status = 'excused') AS excused_count
                 FROM attendance a
                 WHERE a.attendance_date BETWEEN ? AND ?
                 GROUP BY a.class_name
                 ORDER BY a.class_name"
            );
            $stmt->bind_param('ss', $from, $to);
            $stmt->execute();
            $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            echo json_encode(['type' => 'all_classes', 'from' => $from, 'to' => $to, 'rows' => $rows]);
        } else {
            // Per-student summary within one class
            $stmt = $conn->prepare(
                "SELECT CONCAT(s.first_name, ' ', s.last_name) AS full_name,
                        s.student_id AS student_id_number,
                        COUNT(a.id) AS total_days,
                        SUM(a.status = 'present') AS present_count,
                        SUM(a.status = 'absent')  AS absent_count,
                        SUM(a.status = 'late')    AS late_count,
                        SUM(a.status = 'excused') AS excused_count
                 FROM students s
                 LEFT JOIN attendance a
                   ON a.student_id = s.id
                   AND a.attendance_date BETWEEN ? AND ?
                   AND a.class_name = ?
                 WHERE s.class = ? AND s.status = 'active'
                 GROUP BY s.id
                 ORDER BY s.first_name, s.last_name"
            );
            $stmt->bind_param('ssss', $from, $to, $class, $class);
            $stmt->execute();
            $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            // Monthly calendar data: count of each status per day for this class
            $cal_stmt = $conn->prepare(
                "SELECT attendance_date,
                        SUM(status = 'present') AS present_count,
                        SUM(status = 'absent')  AS absent_count,
                        SUM(status = 'late')    AS late_count,
                        SUM(status = 'excused') AS excused_count
                 FROM attendance
                 WHERE class_name = ? AND attendance_date BETWEEN ? AND ?
                 GROUP BY attendance_date
                 ORDER BY attendance_date"
            );
            $cal_stmt->bind_param('sss', $class, $from, $to);
            $cal_stmt->execute();
            $calendar = $cal_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $cal_stmt->close();

            echo json_encode(['type' => 'class', 'class' => $class, 'from' => $from, 'to' => $to, 'rows' => $rows, 'calendar' => $calendar]);
        }
        break;

    // ── GET CLASSES (for dropdowns) ────────────────────────────────────
    case 'get_classes':
        // Primary: active classes from the classes table (same source as the rest of the app)
        $classes = [];
        $r = $conn->query(
            "SELECT class_name FROM classes WHERE is_active = 1 ORDER BY class_name"
        );
        if ($r) while ($row = $r->fetch_assoc()) $classes[] = $row['class_name'];

        // Fallback: add any student classes not already in the list
        $r2 = $conn->query(
            "SELECT DISTINCT class FROM students WHERE class IS NOT NULL AND class != '' AND status='active' ORDER BY class"
        );
        if ($r2) while ($row = $r2->fetch_assoc()) {
            if (!in_array($row['class'], $classes, true)) $classes[] = $row['class'];
        }
        sort($classes);
        echo json_encode($classes);
        break;

    // ── SMS ABSENTEES ─────────────────────────────────────────────────
    case 'sms_absentees':
        $class = trim((string) ($_POST['class']   ?? ''));
        $date  = trim((string) ($_POST['date']    ?? date('Y-m-d')));
        $msg   = strip_tags(trim((string) ($_POST['message'] ?? '')));

        if ($class === '' || $date === '') {
            echo json_encode(['success' => false, 'message' => 'Class and date are required']); break;
        }

        // Find absent students and their parent phone numbers
        $stmt = $conn->prepare(
            "SELECT CONCAT(s.first_name, ' ', s.last_name) AS full_name, s.id AS student_id,
                    pa.phone AS parent_phone, pa.parent_name
             FROM attendance a
             INNER JOIN students s ON s.id = a.student_id
             LEFT JOIN parent_student_link psl ON psl.student_id = s.id
             LEFT JOIN parent_accounts pa ON pa.id = psl.parent_id AND pa.is_active = 1
             WHERE a.class_name = ? AND a.attendance_date = ? AND a.status = 'absent'
             ORDER BY s.first_name, s.last_name"
        );
        $stmt->bind_param('ss', $class, $date);
        $stmt->execute();
        $absentees = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();

        if (count($absentees) === 0) {
            echo json_encode(['success' => true, 'sent' => 0, 'message' => 'No absent students found for this class and date']); break;
        }

        $sent  = 0;
        $fails = 0;
        $date_fmt = date('d M Y', strtotime($date));

        foreach ($absentees as $ab) {
            if (empty($ab['parent_phone'])) { $fails++; continue; }
            $default_msg = "Dear {$ab['parent_name']}, your child {$ab['full_name']} was marked absent from {$class} on {$date_fmt}. Please contact the school if this is an error.";
            $sms_text = $msg !== '' ? str_replace(
                ['{name}', '{class}', '{date}'],
                [$ab['full_name'], $class, $date_fmt],
                $msg
            ) : $default_msg;

            $ok = sendSMS($ab['parent_phone'], $sms_text);
            $ok ? $sent++ : $fails++;
        }

        echo json_encode([
            'success' => true,
            'sent'    => $sent,
            'failed'  => $fails,
            'total'   => count($absentees),
            'message' => "SMS sent to {$sent} parent(s). Failed: {$fails}."
        ]);
        break;

    // ── GET ABSENT LIST PREVIEW ────────────────────────────────────────
    case 'get_absentees':
        $class = trim((string) ($_GET['class'] ?? ''));
        $date  = trim((string) ($_GET['date']  ?? date('Y-m-d')));

        $stmt = $conn->prepare(
            "SELECT CONCAT(s.first_name, ' ', s.last_name) AS full_name,
                    s.student_id AS student_id_number,
                    pa.phone AS parent_phone, pa.parent_name
             FROM attendance a
             INNER JOIN students s ON s.id = a.student_id
             LEFT JOIN parent_student_link psl ON psl.student_id = s.id
             LEFT JOIN parent_accounts pa ON pa.id = psl.parent_id AND pa.is_active = 1
             WHERE a.class_name = ? AND a.attendance_date = ? AND a.status = 'absent'
             ORDER BY s.first_name, s.last_name"
        );
        $stmt->bind_param('ss', $class, $date);
        $stmt->execute();
        $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        echo json_encode($rows);
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Unknown action']);
}
