<?php
declare(strict_types=1);

function portalGetConnection(): ?mysqli
{
    $conn = getDBConnection();
    return $conn instanceof mysqli ? $conn : null;
}

function portalTerms(): array
{
    return ['First Term', 'Second Term', 'Third Term'];
}

function portalSettings(mysqli $conn): array
{
    $rows = [];
    $result = $conn->query("SELECT setting_key, setting_value FROM settings");
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $rows[(string) $row['setting_key']] = (string) $row['setting_value'];
        }
    }
    return $rows;
}

function portalCurrentYear(mysqli $conn): string
{
    $settings = portalSettings($conn);
    return trim((string) ($settings['academic_year'] ?? getAcademicYear() ?? date('Y')));
}

function portalCurrentTerm(mysqli $conn): string
{
    $settings = portalSettings($conn);
    $term = trim((string) ($settings['current_term'] ?? 'First Term'));
    return in_array($term, portalTerms(), true) ? $term : 'First Term';
}

function portalGetParent(mysqli $conn, int $parentId): ?array
{
    $stmt = $conn->prepare("SELECT * FROM parent_accounts WHERE id = ? LIMIT 1");
    $stmt->bind_param('i', $parentId);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $row ?: null;
}

function portalGetChildren(mysqli $conn, int $parentId): array
{
    $stmt = $conn->prepare(
        "SELECT s.*, psl.relationship
         FROM parent_student_link psl
         INNER JOIN students s ON s.id = psl.student_id
         WHERE psl.parent_id = ?
         ORDER BY s.first_name, s.last_name"
    );
    $stmt->bind_param('i', $parentId);
    $stmt->execute();
    $result = $stmt->get_result();
    $rows = [];
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    $stmt->close();
    return $rows;
}

function portalParentOwnsStudent(mysqli $conn, int $parentId, int $studentId): bool
{
    $stmt = $conn->prepare(
        "SELECT id FROM parent_student_link WHERE parent_id = ? AND student_id = ? LIMIT 1"
    );
    $stmt->bind_param('ii', $parentId, $studentId);
    $stmt->execute();
    $owns = $stmt->get_result()->num_rows > 0;
    $stmt->close();
    return $owns;
}

function portalGetStudent(mysqli $conn, int $studentId, int $parentId): ?array
{
    $stmt = $conn->prepare(
        "SELECT s.*, psl.relationship
         FROM parent_student_link psl
         INNER JOIN students s ON s.id = psl.student_id
         WHERE psl.parent_id = ? AND psl.student_id = ?
         LIMIT 1"
    );
    $stmt->bind_param('ii', $parentId, $studentId);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $row ?: null;
}

function portalStudentDisplayName(array $student): string
{
    return trim((string) (($student['first_name'] ?? '') . ' ' . ($student['last_name'] ?? '')));
}

function portalStudentPhoto(array $student): string
{
    $photo = trim((string) ($student['photo_path'] ?? ''));
    if ($photo === '') {
        return BASE_URL . '/assets/img/default-avatar.png';
    }
    if (preg_match('#^https?://#i', $photo)) {
        return $photo;
    }
    return rtrim(BASE_URL, '/') . '/' . ltrim($photo, '/');
}

function portalFormatCurrency(float $amount): string
{
    return 'GHS ' . number_format($amount, 2);
}

/**
 * Returns (and lazily creates) a per-session CSRF token for the parent portal.
 * Call inside a form page to embed the token in a hidden input.
 */
function portalCsrfToken(): string
{
    if (empty($_SESSION['portal_csrf'])) {
        $_SESSION['portal_csrf'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['portal_csrf'];
}

/**
 * Validates the _csrf POST field against the session token.
 * Outputs a 403 JSON error and exits if the token is missing or wrong.
 * Call this at the top of every AJAX endpoint that mutates data.
 */
function portalCsrfVerify(): void
{
    $token    = (string) ($_POST['_csrf'] ?? '');
    $expected = (string) ($_SESSION['portal_csrf'] ?? '');
    if ($token === '' || $expected === '' || !hash_equals($expected, $token)) {
        http_response_code(403);
        echo json_encode(['success' => false, 'message' => 'Invalid request token. Please reload the page.']);
        exit;
    }
}

function portalPageStart(string $title, string $active = 'dashboard', string $headerTitle = ''): string
{
    $header = $headerTitle !== '' ? $headerTitle : $title;
    $schoolName = htmlspecialchars((string) ($_SESSION['school_name'] ?? 'EduTrack'));
    $pageTitle = htmlspecialchars($title);
    $headerLabel = htmlspecialchars($header);
    $portalRoot = rtrim(BASE_URL, '/') . '/parent-portal';
    $bellUrl = $portalRoot . '/ajax/get_notifications.php';
    $base = $portalRoot;
    $links = [
        'dashboard' => $base . '/dashboard.php',
        'fees' => $base . '/fees.php',
        'reports' => $base . '/reports.php',
        'messages' => $base . '/messages.php',
        'settings' => $base . '/settings.php',
    ];
    $items = [
        'dashboard' => ['Home', 'fas fa-home'],
        'fees' => ['Fees', 'fas fa-wallet'],
        'reports' => ['Reports', 'fas fa-chart-line'],
        'messages' => ['Messages', 'fas fa-comments'],
        'settings' => ['Settings', 'fas fa-cog'],
    ];

    $navHtml = '';
    foreach ($items as $key => [$label, $icon]) {
        $activeClass = $key === $active ? ' active' : '';
        $navHtml .= '<a href="' . htmlspecialchars($links[$key]) . '" class="portal-nav-link' . $activeClass . '">'
            . '<i class="' . htmlspecialchars($icon) . '"></i><span>' . htmlspecialchars($label) . '</span></a>';
    }

    $manifestUrl = rtrim(BASE_URL, '/') . '/parent-portal/manifest.php';
    $swUrl       = rtrim(BASE_URL, '/') . '/parent-portal/sw.php';
    $swScope     = rtrim((string) parse_url(rtrim(BASE_URL, '/'), PHP_URL_PATH), '/') . '/parent-portal/';

    return <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{$pageTitle}</title>
    <!-- PWA -->
    <link rel="manifest" href="{$manifestUrl}">
    <meta name="theme-color" content="#16a34a">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="EduTrack Parents">
    <!-- /PWA -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="assets/css/portal.css">
</head>
<body data-notifications-url="{$bellUrl}">
    <div class="portal-shell">
        <header class="portal-header">
            <div class="portal-header-left">
                <img src="https://placehold.co/40x40/16a34a/ffffff?text=E" alt="School Logo" class="portal-logo">
            </div>
            <div class="portal-header-title">{$headerLabel}</div>
            <div class="portal-header-right">
                <button id="pwaInstallBtnPortal" type="button" title="Install App"
                    style="display:none;background:none;border:none;color:inherit;padding:4px 8px;cursor:pointer;font-size:1.1rem;">
                    <i class="fas fa-download"></i>
                </button>
                <a href="dashboard.php#notifications" class="portal-bell" aria-label="Notifications">
                    <i class="fas fa-bell"></i>
                    <span class="portal-bell-badge" id="portalUnreadBadge">0</span>
                </a>
            </div>
        </header>
        <main class="portal-main">
HTML;
}

/**
 * Renders a child-switcher dropdown strip for pages that support multiple children.
 *
 * @param array  $children     Array of children from portalGetChildren()
 * @param int    $activeChildId The currently selected child id
 * @param string $currentPage  Base filename of the current page (e.g. 'fees.php')
 * @return string  HTML snippet
 */
function portalChildSwitcher(array $children, int $activeChildId, string $currentPage): string
{
    if (count($children) <= 1) return '';

    $items = '';
    foreach ($children as $child) {
        $cid   = (int) $child['id'];
        $name  = htmlspecialchars(trim((string) (($child['first_name'] ?? '') . ' ' . ($child['last_name'] ?? ''))));
        $class = htmlspecialchars((string) ($child['class'] ?? ''));
        $url   = htmlspecialchars($currentPage . '?child_id=' . $cid);
        $active = $cid === $activeChildId ? 'selected' : '';
        $items .= "<option value=\"{$url}\" {$active}>{$name}" . ($class ? " — {$class}" : '') . "</option>";
    }

    return <<<HTML
<div class="portal-card portal-child-switcher" style="padding:10px 16px;display:flex;align-items:center;gap:10px;margin-bottom:12px">
    <i class="fas fa-exchange-alt" style="color:var(--portal-primary,#1a73e8)"></i>
    <label style="font-size:.83rem;font-weight:600;white-space:nowrap;margin:0">Viewing:</label>
    <select class="form-select form-select-sm" style="max-width:260px"
            onchange="location.href=this.value">
        {$items}
    </select>
</div>
HTML;
}

function portalPageEnd(string $active = 'dashboard'): string
{
    $portalRoot = rtrim(BASE_URL, '/') . '/parent-portal';
    $base = $portalRoot;
    $links = [
        'dashboard' => $base . '/dashboard.php',
        'fees' => $base . '/fees.php',
        'reports' => $base . '/reports.php',
        'messages' => $base . '/messages.php',
        'settings' => $base . '/settings.php',
    ];
    $items = [
        'dashboard' => ['Home', 'fas fa-home'],
        'fees' => ['Fees', 'fas fa-wallet'],
        'reports' => ['Reports', 'fas fa-chart-line'],
        'messages' => ['Messages', 'fas fa-comments'],
        'settings' => ['Settings', 'fas fa-cog'],
    ];

    $navHtml = '';
    foreach ($items as $key => [$label, $icon]) {
        $activeClass = $key === $active ? ' active' : '';
        $navHtml .= '<a href="' . htmlspecialchars($links[$key]) . '" class="portal-nav-link' . $activeClass . '">'
            . '<i class="' . htmlspecialchars($icon) . '"></i><span>' . htmlspecialchars($label) . '</span></a>';
    }

    $swUrl   = rtrim(BASE_URL, '/') . '/parent-portal/sw.php';
    $swScope = rtrim((string) parse_url(rtrim(BASE_URL, '/'), PHP_URL_PATH), '/') . '/parent-portal/';

    return <<<HTML
        </main>
        <nav class="portal-bottom-nav">
            {$navHtml}
        </nav>
    </div>
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/portal.js"></script>
    <script>
    /* EduTrack Parent Portal — PWA bootstrap */
    (function(){
    'use strict';

    // Register service worker
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', function(){
        navigator.serviceWorker.register('{$swUrl}', {scope: '{$swScope}'})
          .then(function(r){ console.log('[EduTrack Parent SW] Registered:', r.scope); })
          .catch(function(e){ console.warn('[EduTrack Parent SW] Failed:', e.message); });
      });
    }

    // Install prompt
    var _prompt = null;
    window.addEventListener('beforeinstallprompt', function(e){
      e.preventDefault(); _prompt = e;
      var b = document.getElementById('pwaInstallBtnPortal');
      if (b) b.style.display = 'inline-block';
    });
    window.addEventListener('appinstalled', function(){
      _prompt = null;
      var b = document.getElementById('pwaInstallBtnPortal');
      if (b) b.style.display = 'none';
    });
    var installBtn = document.getElementById('pwaInstallBtnPortal');
    if (installBtn) {
      installBtn.addEventListener('click', function(){
        if (!_prompt) return;
        _prompt.prompt();
        _prompt.userChoice.then(function(){
          _prompt = null;
          installBtn.style.display = 'none';
        });
      });
    }

    // iOS hint
    var isIOS      = /iphone|ipad|ipod/i.test(navigator.userAgent);
    var isSafari   = /safari/i.test(navigator.userAgent) && !/chrome|crios|fxios/i.test(navigator.userAgent);
    var standalone = window.navigator.standalone === true ||
                     window.matchMedia('(display-mode: standalone)').matches;
    if (isIOS && isSafari && !standalone && !sessionStorage.getItem('iosParentHintDone')) {
      var t = document.createElement('div');
      t.style.cssText = 'position:fixed;bottom:72px;left:50%;transform:translateX(-50%);'
        + 'background:#14532d;color:#fff;padding:12px 16px;border-radius:14px;'
        + 'font-size:13px;z-index:9999;max-width:300px;width:calc(100% - 32px);'
        + 'text-align:center;box-shadow:0 4px 20px rgba(0,0,0,.35);line-height:1.5;';
      t.innerHTML = '<i class="fas fa-info-circle" style="margin-right:5px;color:#86efac"></i>'
        + 'Install: tap <strong>Share &#x2197;</strong> → <strong>Add to Home Screen</strong>'
        + '<button onclick="this.closest(\'div\').remove();sessionStorage.setItem(\'iosParentHintDone\',1)" '
        + 'style="background:none;border:none;color:#86efac;margin-left:8px;cursor:pointer;font-size:13px;padding:0">'
        + '&#10005;</button>';
      document.body.appendChild(t);
      setTimeout(function(){ if (t.parentNode) t.remove(); }, 12000);
    }

    // Offline / online banner
    function offlineBanner(show){
      var el = document.getElementById('portalOfflineBanner');
      if (show && !el) {
        var bar = document.createElement('div');
        bar.id = 'portalOfflineBanner';
        bar.style.cssText = 'background:#fef3c7;color:#92400e;padding:6px 16px;'
          + 'font-size:13px;text-align:center;border-bottom:1px solid #fde68a;';
        bar.innerHTML = '<i class="fas fa-wifi" style="margin-right:5px"></i>'
          + 'You are offline — showing cached data.';
        var main = document.querySelector('.portal-main');
        if (main) main.insertBefore(bar, main.firstChild);
        else document.body.insertBefore(bar, document.body.firstChild);
      } else if (!show && el) {
        el.remove();
      }
    }
    offlineBanner(!navigator.onLine);
    window.addEventListener('offline', function(){ offlineBanner(true); });
    window.addEventListener('online',  function(){ offlineBanner(false); });
    })();
    </script>
</body>
</html>
HTML;
}
