<?php
declare(strict_types=1);
session_start();
require_once '../config.php';
require_once __DIR__ . '/helpers.php';
if (!isset($_SESSION['parent_id'])) { header('Location: login.php'); exit; }

$conn = portalGetConnection();
if (!$conn instanceof mysqli) { http_response_code(500); exit('Database connection failed.'); }

$parentId = (int) $_SESSION['parent_id'];
$children = portalGetChildren($conn, $parentId);
$year = portalCurrentYear($conn);
$notifications = [];
$upcomingExams = [];
$feeSummary = [];

$notifStmt = $conn->prepare(
    "SELECT * FROM parent_notifications
     WHERE parent_id = ?
     ORDER BY created_at DESC
     LIMIT 5"
);
$notifStmt->bind_param('i', $parentId);
$notifStmt->execute();
$notifResult = $notifStmt->get_result();
while ($row = $notifResult->fetch_assoc()) { $notifications[] = $row; }
$notifStmt->close();

foreach ($children as $child) {
    $studentId = (int) $child['id'];
    $className = (string) ($child['class'] ?? '');

    $feeStmt = $conn->prepare(
        "SELECT
            COALESCE(SUM(fs.amount), 0) AS total_fees,
            COALESCE(SUM(paid.total_paid), 0) AS total_paid
         FROM fee_structures fs
         LEFT JOIN (
             SELECT fee_structure_id, SUM(amount_paid) AS total_paid
             FROM payments
             WHERE student_id = ?
             GROUP BY fee_structure_id
         ) paid ON paid.fee_structure_id = fs.id
         WHERE fs.class_name = ? AND fs.academic_year = ?"
    );
    $feeStmt->bind_param('iss', $studentId, $className, $year);
    $feeStmt->execute();
    $summary = $feeStmt->get_result()->fetch_assoc() ?: ['total_fees' => 0, 'total_paid' => 0];
    $feeStmt->close();
    $summary['outstanding'] = (float) $summary['total_fees'] - (float) $summary['total_paid'];
    $feeSummary[$studentId] = $summary;

    $examStmt = $conn->prepare(
        "SELECT ep.title, s.subject_name, es.exam_date, es.start_time, es.end_time
         FROM exam_schedules es
         INNER JOIN exam_papers ep ON ep.id = es.paper_id
         LEFT JOIN subjects s ON s.id = ep.subject_id
         WHERE es.class_name = ? AND es.exam_date >= CURDATE()
         ORDER BY es.exam_date ASC, es.start_time ASC
         LIMIT 3"
    );
    $examStmt->bind_param('s', $className);
    $examStmt->execute();
    $result = $examStmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $upcomingExams[$studentId][] = $row;
    }
    $examStmt->close();
}

echo portalPageStart('Parent Portal', 'dashboard', 'Parent Portal');
?>
<div class="portal-pull-hint">Pull down to refresh portal updates</div>
<div class="portal-card">
    <h2 class="h5 mb-1">Hello, <?= htmlspecialchars((string) $_SESSION['parent_name']) ?></h2>
    <div class="portal-muted">Manage your children, fees, results and school updates from one place.</div>
</div>

<div class="portal-grid">
    <?php foreach ($children as $child): $studentId = (int) $child['id']; ?>
        <div class="portal-card">
            <div class="portal-child-card">
                <img src="<?= htmlspecialchars(portalStudentPhoto($child)) ?>" alt="Child photo" class="portal-avatar">
                <div>
                    <div class="fw-bold"><?= htmlspecialchars(portalStudentDisplayName($child)) ?></div>
                    <div class="portal-muted small"><?= htmlspecialchars((string) ($child['class'] ?? '')) ?><?= !empty($child['section']) ? ' • ' . htmlspecialchars((string) $child['section']) : '' ?></div>
                    <div class="portal-muted small">Student ID: <?= htmlspecialchars((string) ($child['student_id'] ?? '')) ?></div>
                </div>
            </div>
            <div class="d-flex justify-content-between align-items-center mt-3">
                <span class="portal-badge <?= (($child['status'] ?? 'active') === 'active') ? 'active' : 'inactive' ?>">
                    <?= htmlspecialchars(ucfirst((string) ($child['status'] ?? 'active'))) ?>
                </span>
                <a href="child.php?id=<?= $studentId ?>" class="fw-semibold">View Details <i class="fas fa-arrow-right ms-1"></i></a>
            </div>
        </div>
    <?php endforeach; ?>
    <?php if (!$children): ?>
        <div class="portal-empty">No children are linked to this parent account yet.</div>
    <?php endif; ?>
</div>

<div class="portal-card">
    <div class="portal-section-title">Fee Summary</div>
    <div class="portal-grid">
        <?php foreach ($children as $child): $studentId = (int) $child['id']; $summary = $feeSummary[$studentId] ?? ['outstanding' => 0]; ?>
            <div class="d-flex justify-content-between align-items-center border rounded-3 p-3">
                <div>
                    <div class="fw-semibold"><?= htmlspecialchars(portalStudentDisplayName($child)) ?></div>
                    <div class="small text-danger">Outstanding: <?= portalFormatCurrency((float) ($summary['outstanding'] ?? 0)) ?></div>
                </div>
                <a href="fees.php?child_id=<?= $studentId ?>" class="portal-btn-primary">Pay Now</a>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<div class="portal-card">
    <div class="portal-section-title">Upcoming Exams</div>
    <div class="portal-grid">
        <?php foreach ($children as $child): $studentId = (int) $child['id']; $exams = $upcomingExams[$studentId] ?? []; ?>
            <div class="border rounded-3 p-3">
                <div class="fw-semibold mb-2"><?= htmlspecialchars(portalStudentDisplayName($child)) ?></div>
                <?php if ($exams): foreach ($exams as $exam): ?>
                    <div class="mb-2">
                        <div class="fw-semibold"><?= htmlspecialchars((string) ($exam['subject_name'] ?? $exam['title'])) ?></div>
                        <div class="portal-muted small"><?= htmlspecialchars((string) $exam['exam_date']) ?> • <?= htmlspecialchars(substr((string) $exam['start_time'], 0, 5)) ?></div>
                    </div>
                <?php endforeach; else: ?>
                    <div class="portal-muted small">No scheduled exams yet.</div>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<div class="portal-card" id="notifications">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div class="portal-section-title mb-0">Recent School Notifications</div>
        <button class="btn btn-sm btn-outline-primary" id="markAllNotificationsBtn">Mark all read</button>
    </div>
    <div class="portal-grid" id="notificationList">
        <?php foreach ($notifications as $notification): ?>
            <div class="portal-notification <?= (int) $notification['is_read'] === 0 ? 'unread' : '' ?> portal-card mb-0">
                <div class="fw-semibold"><?= htmlspecialchars((string) $notification['title']) ?></div>
                <div class="portal-muted small"><?= htmlspecialchars((string) $notification['created_at']) ?></div>
                <p class="mb-0 mt-2"><?= nl2br(htmlspecialchars((string) $notification['message'])) ?></p>
            </div>
        <?php endforeach; ?>
        <?php if (!$notifications): ?><div class="portal-empty">No notifications yet.</div><?php endif; ?>
    </div>
</div>
<script>
const _csrfToken = <?= json_encode(portalCsrfToken()) ?>;
document.getElementById('markAllNotificationsBtn')?.addEventListener('click', async function () {
    const response = await fetch('ajax/mark_notification_read.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'mark_all=1&_csrf=' + encodeURIComponent(_csrfToken)
    });
    const data = await response.json();
    if (data.success) {
        location.reload();
    }
});
</script>
<?= portalPageEnd('dashboard') ?>
