<?php
declare(strict_types=1);
session_start();
require_once '../config.php';
require_once __DIR__ . '/../includes/canteen_helpers.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);
$studentId = (int) ($_GET['id'] ?? ($children[0]['id'] ?? 0));
$student   = portalGetStudent($conn, $studentId, $parentId);
if (!$student) {
    header('Location: dashboard.php?error=unauthorized');
    exit;
}

// ── Live stats ─────────────────────────────────────────────────────────────
$feeBalance  = 0.0;
$avgGrade    = null;
$nextExam    = null;

// Fee outstanding balance
$feeStmt = $conn->prepare(
    "SELECT COALESCE(SUM(fs.amount),0) - COALESCE(SUM(p.amount_paid),0) AS balance
     FROM fee_structures fs
     LEFT JOIN payments p ON p.student_id = ? AND p.fee_structure_id = fs.id
     WHERE fs.class_name = ?
     LIMIT 1"
);
if ($feeStmt) {
    $cls = (string) ($student['class'] ?? '');
    $feeStmt->bind_param('is', $studentId, $cls);
    $feeStmt->execute();
    $feeRow = $feeStmt->get_result()->fetch_assoc();
    $feeStmt->close();
    $feeBalance = (float) ($feeRow['balance'] ?? 0);
}

// Last report avg grade (from scores — column is total_score)
$gradeStmt = $conn->prepare(
    "SELECT ROUND(AVG(total_score),1) AS avg_score FROM scores WHERE student_id = ?"
);
if ($gradeStmt) {
    $gradeStmt->bind_param('i', $studentId);
    $gradeStmt->execute();
    $gr = $gradeStmt->get_result()->fetch_assoc();
    $gradeStmt->close();
    $avgGrade = ($gr && $gr['avg_score'] !== null) ? (float) $gr['avg_score'] : null;
}

// Next upcoming exam
$examStmt = $conn->prepare(
    "SELECT ep.title, es.exam_date, s.subject_name
     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() AND es.status != 'cancelled'
     ORDER BY es.exam_date ASC LIMIT 1"
);
if ($examStmt) {
    $cls = (string) ($student['class'] ?? '');
    $examStmt->bind_param('s', $cls);
    $examStmt->execute();
    $nextExam = $examStmt->get_result()->fetch_assoc();
    $examStmt->close();
}

// Canteen — today's entitlements (only when module is active)
$canteenEntitlements = [];
if (canteen_is_active()) {
    $today = date('Y-m-d');
    $cetStmt = $conn->prepare(
        "SELECT ce.id, ce.qr_token, ce.status, ce.confirmed_at,
                cs.session_name, cs.start_time, cs.end_time, ce.qr_token_expires_at
         FROM canteen_entitlements ce
         JOIN canteen_sessions cs ON cs.id = ce.session_id
         WHERE ce.student_id = ? AND cs.session_date = ? AND cs.status != 'cancelled'
         ORDER BY cs.start_time ASC"
    );
    if ($cetStmt) {
        $cetStmt->bind_param('is', $studentId, $today);
        $cetStmt->execute();
        $cetResult = $cetStmt->get_result();
        while ($row = $cetResult->fetch_assoc()) $canteenEntitlements[] = $row;
        $cetStmt->close();
    }
}

// ── Homework visible to parents (active, due within next 14 days or overdue) ─
$homeworkList = [];
$hwStmt = $conn->prepare(
    "SELECT h.id, h.title, h.subject_name, h.description, h.due_date,
            h.max_score, h.assigned_date,
            COALESCE(hs.status, 'pending')   AS sub_status,
            COALESCE(hs.score, NULL)          AS score,
            hs.teacher_comment
       FROM homework h
       LEFT JOIN homework_submissions hs ON hs.homework_id = h.id AND hs.student_id = ?
      WHERE h.class_name = ?
        AND h.is_visible_to_parents = 1
        AND h.status = 'active'
        AND h.due_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
      ORDER BY h.due_date ASC
      LIMIT 10"
);
if ($hwStmt) {
    $studentClass = (string)($student['class'] ?? '');
    $hwStmt->bind_param('is', $studentId, $studentClass);
    $hwStmt->execute();
    $hwResult = $hwStmt->get_result();
    while ($row = $hwResult->fetch_assoc()) $homeworkList[] = $row;
    $hwStmt->close();
}

echo portalPageStart('Child Details', 'dashboard', 'Child Details');
?>
<?= portalChildSwitcher($children, $studentId, 'child.php') ?>
<div class="portal-card">
    <div class="portal-child-card">
        <img src="<?= htmlspecialchars(portalStudentPhoto($student)) ?>" alt="Child photo" class="portal-avatar">
        <div>
            <div class="h5 mb-1"><?= htmlspecialchars(portalStudentDisplayName($student)) ?></div>
            <div class="portal-muted"><?= htmlspecialchars((string) ($student['student_id'] ?? '')) ?> • <?= htmlspecialchars((string) ($student['class'] ?? '')) ?><?= !empty($student['section']) ? ' / ' . htmlspecialchars((string) $student['section']) : '' ?></div>
            <div class="mt-2"><span class="portal-badge <?= (($student['status'] ?? 'active') === 'active') ? 'active' : 'inactive' ?>"><?= htmlspecialchars(ucfirst((string) ($student['status'] ?? 'active'))) ?></span></div>
        </div>
    </div>
</div>

<!-- Live stats strip -->
<div class="portal-grid cols-3" style="gap:10px;margin-bottom:12px">
    <div class="portal-card text-center" style="padding:14px 10px">
        <div style="font-size:1.4rem;font-weight:700;color:<?= $feeBalance > 0 ? '#dc3545' : '#28a745' ?>">
            GHS <?= number_format(abs($feeBalance), 2) ?>
        </div>
        <div class="portal-muted" style="font-size:.78rem">
            <?= $feeBalance > 0 ? 'Fee Balance Due' : 'No Outstanding Fees' ?>
        </div>
    </div>
    <div class="portal-card text-center" style="padding:14px 10px">
        <div style="font-size:1.4rem;font-weight:700;color:#1a73e8">
            <?= $avgGrade !== null ? $avgGrade . '%' : '—' ?>
        </div>
        <div class="portal-muted" style="font-size:.78rem">Avg Score (All Terms)</div>
    </div>
    <div class="portal-card text-center" style="padding:14px 10px">
        <?php if ($nextExam): ?>
        <div style="font-size:1rem;font-weight:700;color:#f59e0b">
            <?= htmlspecialchars(date('d M', strtotime((string) $nextExam['exam_date']))) ?>
        </div>
        <div class="portal-muted" style="font-size:.78rem">
            Next: <?= htmlspecialchars((string) ($nextExam['subject_name'] ?? $nextExam['title'])) ?>
        </div>
        <?php else: ?>
        <div style="font-size:1rem;font-weight:700;color:#94a3b8">—</div>
        <div class="portal-muted" style="font-size:.78rem">No Upcoming Exams</div>
        <?php endif; ?>
    </div>
</div>

<div class="portal-grid cols-2">
    <div class="portal-card">
        <div class="portal-section-title">Personal Details</div>
        <div class="portal-kv">
            <div class="portal-kv-item"><div class="label">Date of Birth</div><div class="value"><?= htmlspecialchars((string) ($student['date_of_birth'] ?? $student['dob'] ?? 'Not available')) ?></div></div>
            <div class="portal-kv-item"><div class="label">Gender</div><div class="value"><?= htmlspecialchars((string) ($student['gender'] ?? 'Not available')) ?></div></div>
            <div class="portal-kv-item"><div class="label">Address</div><div class="value"><?= htmlspecialchars((string) ($student['address'] ?? 'Not available')) ?></div></div>
            <div class="portal-kv-item"><div class="label">Section</div><div class="value"><?= htmlspecialchars((string) ($student['section'] ?? 'Not available')) ?></div></div>
        </div>
    </div>
    <div class="portal-card">
        <div class="portal-section-title">Parent / Guardian Info</div>
        <div class="portal-kv">
            <div class="portal-kv-item"><div class="label">Father</div><div class="value"><?= htmlspecialchars((string) ($student['father_name'] ?? 'Not available')) ?><br><small><?= htmlspecialchars((string) ($student['father_phone'] ?? '')) ?></small></div></div>
            <div class="portal-kv-item"><div class="label">Mother</div><div class="value"><?= htmlspecialchars((string) ($student['mother_name'] ?? 'Not available')) ?><br><small><?= htmlspecialchars((string) ($student['mother_phone'] ?? '')) ?></small></div></div>
            <div class="portal-kv-item"><div class="label">Parent Name</div><div class="value"><?= htmlspecialchars((string) ($student['parent_name'] ?? $_SESSION['parent_name'])) ?></div></div>
            <div class="portal-kv-item"><div class="label">Parent Email</div><div class="value"><?= htmlspecialchars((string) ($student['email'] ?? 'Not available')) ?></div></div>
        </div>
    </div>
</div>

<div class="portal-card">
    <div class="portal-section-title">Quick Actions</div>
    <div class="d-grid gap-2">
        <a class="portal-btn-primary text-center" href="fees.php?child_id=<?= (int) $student['id'] ?>">View Fees</a>
        <a class="portal-btn-primary text-center" href="reports.php?child_id=<?= (int) $student['id'] ?>">View Reports</a>
        <?php if (function_exists('hasModule') && hasModule('progress_analytics')): ?>
        <a class="portal-btn-primary text-center" href="progress.php?child_id=<?= (int) $student['id'] ?>">View Progress</a>
        <?php endif; ?>
        <a class="portal-btn-primary text-center" href="timetable.php?child_id=<?= (int) $student['id'] ?>">View Timetable</a>
        <a class="portal-btn-primary text-center" href="exams.php?child_id=<?= (int) $student['id'] ?>">View Exams</a>
    </div>
</div>
<?php
// ── Card A — Student Identity QR (permanent, always visible) ─────────────
$identityToken = htmlspecialchars((string)($student['identity_qr_token'] ?? ''));
$studentName   = htmlspecialchars(portalStudentDisplayName($student));
$studentCode   = htmlspecialchars((string)($student['student_id'] ?? ''));
$studentClass  = htmlspecialchars((string)($student['class'] ?? ''));
$printUrl      = htmlspecialchars(rtrim(BASE_URL, '/') . '/parent-portal/print_id_card.php?id=' . $studentId);

if ($identityToken !== ''):
?>
<div class="portal-card" style="text-align:center">
    <div class="portal-section-title" style="margin-bottom:12px">
        <i class="fas fa-id-card me-1"></i>Fee Desk Pass
    </div>
    <p class="portal-muted" style="font-size:.82rem;margin-bottom:12px">
        Show this at the school fee collection window
    </p>
    <div id="qrIdentity" style="display:inline-block;padding:10px;background:#fff;border-radius:8px;border:1px solid #e5e7eb"></div>
    <div style="margin-top:10px;font-weight:600;font-size:.95rem"><?= $studentName ?></div>
    <div class="portal-muted" style="font-size:.8rem"><?= $studentCode ?> &bull; <?= $studentClass ?></div>
    <div style="margin-top:12px">
        <a href="<?= $printUrl ?>" target="_blank"
           style="display:inline-flex;align-items:center;gap:6px;background:#1a73e8;color:#fff;
                  padding:8px 16px;border-radius:20px;font-size:.85rem;text-decoration:none;font-weight:600">
            <i class="fas fa-print"></i> Print ID Card
        </a>
    </div>
</div>
<?php endif; ?>

<?php
// ── Card B — Daily Canteen Session Pass ───────────────────────────────────
if (canteen_is_active() && !empty($canteenEntitlements)):
    foreach ($canteenEntitlements as $ent):
        $sessName    = htmlspecialchars((string)($ent['session_name'] ?? ''));
        $expAt       = (string)($ent['qr_token_expires_at'] ?? '');
        $expTs       = $expAt ? (int)strtotime($expAt) : 0;
        $sessToken   = htmlspecialchars((string)($ent['qr_token'] ?? ''));
        $entStatus   = (string)($ent['status'] ?? 'pending');
        $confirmedAt = $ent['confirmed_at'] ? date('H:i', strtotime((string)$ent['confirmed_at'])) : '';
        $entId       = (int)$ent['id'];
?>
<div class="portal-card" style="text-align:center" data-canteen-ent="<?= $entId ?>">
    <div class="portal-section-title" style="margin-bottom:8px">
        <i class="fas fa-utensils me-1 text-success"></i>
        Canteen Pass &mdash; <?= $sessName ?> &bull; Today
    </div>

    <?php if ($entStatus === 'confirmed'): ?>
        <div style="padding:24px 0;font-size:3rem">✅</div>
        <div style="font-size:1.1rem;font-weight:700;color:#16a34a">Meal confirmed at <?= $confirmedAt ?></div>
        <div class="portal-muted" style="font-size:.8rem;margin-top:4px"><?= $sessName ?> — <?= date('d M Y') ?></div>

    <?php elseif ($entStatus === 'absent'): ?>
        <div style="padding:24px 0;font-size:2.5rem">—</div>
        <div class="portal-muted">Marked absent today</div>

    <?php elseif ($entStatus === 'cancelled'): ?>
        <div style="padding:24px 0;font-size:2.5rem text-danger">✗</div>
        <div class="portal-muted">This session was cancelled</div>

    <?php else: /* pending */ ?>
        <div id="qrSession_<?= $entId ?>"
             style="display:inline-block;padding:10px;background:#fff;border-radius:8px;border:1px solid #e5e7eb"
             data-token="<?= $sessToken ?>"></div>
        <div style="margin-top:10px;font-size:.85rem;color:#6b7280"
             id="qrCountdown_<?= $entId ?>"
             data-expires="<?= $expTs ?>">
            <?php
            $remaining = $expTs - time();
            if ($remaining > 0) {
                $h = floor($remaining / 3600);
                $m = floor(($remaining % 3600) / 60);
                echo "Expires in {$h}h {$m}m";
            } else {
                echo "Expired";
            }
            ?>
        </div>
    <?php endif; ?>
</div>
<?php
    endforeach;
endif;
?>

<!-- qrcode.js — render QR codes client-side -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<script>
(function () {
    'use strict';

    // Card A — Identity QR
    var identityEl = document.getElementById('qrIdentity');
    <?php if ($identityToken !== ''): ?>
    if (identityEl && typeof QRCode !== 'undefined') {
        new QRCode(identityEl, {
            text:          <?= json_encode($identityToken) ?>,
            width:         180,
            height:        180,
            colorDark:     '#000',
            colorLight:    '#fff',
            correctLevel:  QRCode.CorrectLevel.M
        });
    }
    <?php endif; ?>

    // Card B — Session pass QR(s)
    <?php foreach ($canteenEntitlements as $ent):
        if (($ent['status'] ?? '') !== 'pending') continue;
        $entId = (int)$ent['id'];
    ?>
    (function () {
        var el = document.getElementById('qrSession_<?= $entId ?>');
        if (el && typeof QRCode !== 'undefined') {
            new QRCode(el, {
                text:         el.dataset.token,
                width:        200,
                height:       200,
                colorDark:    '#000',
                colorLight:   '#fff',
                correctLevel: QRCode.CorrectLevel.M
            });
        }
    })();
    <?php endforeach; ?>

    // Expiry countdowns — update every minute
    function updateCountdowns() {
        var els = document.querySelectorAll('[data-expires]');
        var now = Math.floor(Date.now() / 1000);
        els.forEach(function (el) {
            var exp = parseInt(el.dataset.expires, 10);
            var remaining = exp - now;
            if (remaining <= 0) {
                el.textContent = 'Expired';
                el.style.color = '#dc2626';
            } else {
                var h = Math.floor(remaining / 3600);
                var m = Math.floor((remaining % 3600) / 60);
                el.textContent = 'Expires in ' + h + 'h ' + m + 'm';
                el.style.color = remaining < 3600 ? '#f59e0b' : '#6b7280';
            }
        });
    }
    updateCountdowns();
    setInterval(updateCountdowns, 60000);
})();
</script>

<?php if (!empty($homeworkList)): ?>
<div class="portal-card" style="margin-bottom:12px">
    <div class="portal-section-title">
        <i class="fas fa-tasks me-1"></i>Homework
        <span style="font-size:.72rem;font-weight:400;color:#6b7280;margin-left:6px;"><?= count($homeworkList) ?> assignment<?= count($homeworkList)>1?'s':'' ?></span>
    </div>
    <?php foreach ($homeworkList as $hw):
        $dueTs    = strtotime((string)$hw['due_date']);
        $isOverdue = $dueTs < strtotime('today') && $hw['sub_status'] !== 'submitted';
        $dueFmt   = date('d M', $dueTs);
        $statusColor = match($hw['sub_status']) {
            'submitted' => '#16a34a',
            'missing'   => '#dc2626',
            'excused'   => '#d97706',
            default     => $isOverdue ? '#dc2626' : '#6b7280',
        };
        $statusLabel = match($hw['sub_status']) {
            'submitted' => '✓ Submitted',
            'missing'   => 'Missing',
            'excused'   => 'Excused',
            default     => $isOverdue ? 'Overdue' : 'Pending',
        };
    ?>
    <div style="padding:.55rem 0;border-bottom:1px solid #f1f5f9;">
        <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:.5rem;">
            <div style="flex:1;">
                <div style="font-weight:600;font-size:.9rem;"><?= htmlspecialchars((string)$hw['title']) ?></div>
                <div style="font-size:.78rem;color:#6b7280;"><?= htmlspecialchars((string)$hw['subject_name']) ?> · Due <?= $dueFmt ?></div>
                <?php if (!empty($hw['description'])): ?>
                <div style="font-size:.78rem;color:#374151;margin-top:3px;"><?= htmlspecialchars(mb_substr((string)$hw['description'], 0, 100)) ?><?= mb_strlen((string)$hw['description'])>100?'…':'' ?></div>
                <?php endif; ?>
                <?php if ($hw['sub_status']==='submitted' && $hw['score']!==null): ?>
                <div style="font-size:.78rem;margin-top:3px;color:#1a73e8;font-weight:600;">
                    Score: <?= htmlspecialchars((string)$hw['score']) ?>/<?= (int)$hw['max_score'] ?>
                </div>
                <?php endif; ?>
                <?php if (!empty($hw['teacher_comment']) && $hw['sub_status']==='submitted'): ?>
                <div style="font-size:.75rem;color:#6b7280;margin-top:2px;font-style:italic;">
                    "<?= htmlspecialchars(mb_substr((string)$hw['teacher_comment'],0,80)) ?>"
                </div>
                <?php endif; ?>
            </div>
            <span style="font-size:.72rem;font-weight:600;color:<?= $statusColor ?>;white-space:nowrap;padding-top:2px;"><?= $statusLabel ?></span>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<?php
// ── Teacher intervention notes visible to parents ──────────────────────────
$teacherNotes = [];
$notesStmt = $conn->prepare(
    "SELECT si.type, si.note, si.follow_up_date, si.status, si.created_at,
            st.full_name AS teacher_name
       FROM student_interventions si
       LEFT JOIN staff st ON st.id = si.teacher_id
      WHERE si.student_id = ? AND si.visible_to_parent = 1
      ORDER BY si.created_at DESC
      LIMIT 5"
);
if ($notesStmt) {
    $notesStmt->bind_param('i', $studentId);
    $notesStmt->execute();
    $teacherNotes = $notesStmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $notesStmt->close();
}
?>

<?php if (!empty($teacherNotes)): ?>
<div class="portal-card" style="margin-bottom:12px">
    <div class="portal-section-title">
        <i class="fas fa-comment-dots me-1"></i>Teacher Notes
        <span style="font-size:.72rem;font-weight:400;color:#6b7280;margin-left:6px;"><?= count($teacherNotes) ?> note<?= count($teacherNotes)>1?'s':'' ?></span>
    </div>
    <?php
    $typeColors = ['academic'=>'#3b82f6','attendance'=>'#d97706','behaviour'=>'#dc2626','general'=>'#6b7280'];
    $statusLabel = ['open'=>'Open','monitoring'=>'In Progress','resolved'=>'Resolved'];
    foreach ($teacherNotes as $tn):
        $color = $typeColors[$tn['type']] ?? '#6b7280';
        $sLabel = $statusLabel[$tn['status']] ?? ucfirst((string)$tn['status']);
        $dateFmt = date('d M Y', strtotime((string)$tn['created_at']));
    ?>
    <div style="padding:.6rem 0;border-bottom:1px solid #f1f5f9;border-left:3px solid <?= $color ?>;padding-left:.65rem;margin-bottom:.4rem;">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:3px;">
            <span style="font-size:.72rem;font-weight:700;color:<?= $color ?>;text-transform:capitalize;"><?= htmlspecialchars((string)$tn['type']) ?></span>
            <span style="font-size:.68rem;color:#9ca3af;"><?= $dateFmt ?></span>
        </div>
        <div style="font-size:.87rem;color:#374151;line-height:1.45;"><?= htmlspecialchars((string)$tn['note']) ?></div>
        <?php if (!empty($tn['follow_up_date'])): ?>
        <div style="font-size:.72rem;color:#6366f1;margin-top:3px;"><i class="fas fa-calendar-alt" style="margin-right:3px;"></i>Follow-up: <?= date('d M Y', strtotime((string)$tn['follow_up_date'])) ?></div>
        <?php endif; ?>
        <?php if (!empty($tn['teacher_name'])): ?>
        <div style="font-size:.70rem;color:#9ca3af;margin-top:2px;"><?= htmlspecialchars((string)$tn['teacher_name']) ?></div>
        <?php endif; ?>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<?= portalPageEnd('dashboard') ?>
