<?php
require_once __DIR__ . '/Includes.php';
check_login('parent');

$pdo->exec("CREATE TABLE IF NOT EXISTS classes (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(150) NOT NULL UNIQUE,
  password_hash VARCHAR(255) NOT NULL,
  role ENUM('admin', 'teacher', 'hop', 'accountant', 'parent') NOT NULL DEFAULT 'teacher',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

try {
  $pdo->exec("ALTER TABLE users MODIFY role ENUM('admin', 'teacher', 'hop', 'accountant', 'parent') NOT NULL DEFAULT 'teacher'");
} catch (PDOException $e) {
  // Keep idempotent.
}

$pdo->exec("CREATE TABLE IF NOT EXISTS subjects (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  class_id INT NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_subjects_class FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE CASCADE
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS learners (
  reg_number VARCHAR(30) NOT NULL PRIMARY KEY,
  id INT NOT NULL AUTO_INCREMENT UNIQUE,
  class_id INT NOT NULL,
  date_of_admission DATE NULL,
  surname VARCHAR(100) NULL,
  christian_names VARCHAR(150) NULL,
  full_name VARCHAR(150) NOT NULL,
  date_of_birth_info VARCHAR(40) NULL,
  birth_certificate_number VARCHAR(80) NULL,
  religious_denomination VARCHAR(120) NULL,
  gender ENUM('Male', 'Female', 'Other') NOT NULL DEFAULT 'Other',
  guardian_name VARCHAR(120) NULL,
  guardian_national_id VARCHAR(60) NULL,
  guardian_address VARCHAR(255) NULL,
  guardian_phone VARCHAR(40) NULL,
  student_photo_path VARCHAR(255) NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_learners_class FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE CASCADE
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS parent_learner_links (
  id INT AUTO_INCREMENT PRIMARY KEY,
  parent_user_id INT NOT NULL,
  learner_id INT NOT NULL UNIQUE,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_pl_parent FOREIGN KEY (parent_user_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_pl_learner FOREIGN KEY (learner_id) REFERENCES learners(id) ON DELETE CASCADE
)");

try {
  $pdo->exec("ALTER TABLE parent_learner_links DROP INDEX parent_user_id");
} catch (PDOException $e) {
  // Ignore when index name differs or is already removed.
}

try {
  $pdo->exec("ALTER TABLE parent_learner_links ADD INDEX idx_pl_parent_user (parent_user_id)");
} catch (PDOException $e) {
  // Ignore duplicate index errors.
}

try {
  $pdo->exec("ALTER TABLE parent_learner_links ADD UNIQUE KEY uq_pl_parent_learner (parent_user_id, learner_id)");
} catch (PDOException $e) {
  // Ignore duplicate index errors.
}

$pdo->exec("CREATE TABLE IF NOT EXISTS elearning_posts (
  id INT AUTO_INCREMENT PRIMARY KEY,
  teacher_id INT NOT NULL,
  class_id INT NOT NULL,
  subject_id INT NULL,
  content_type ENUM('assignment','exercise','note','video') NOT NULL DEFAULT 'assignment',
  title VARCHAR(180) NOT NULL,
  instructions TEXT NULL,
  resource_url VARCHAR(255) NULL,
  due_date DATE NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_ep_teacher FOREIGN KEY (teacher_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_ep_class FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE CASCADE,
  CONSTRAINT fk_ep_subject FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE SET NULL,
  INDEX idx_ep_class (class_id)
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS elearning_submissions (
  id INT AUTO_INCREMENT PRIMARY KEY,
  post_id INT NOT NULL,
  learner_id INT NOT NULL,
  response_text TEXT NULL,
  response_link VARCHAR(255) NULL,
  attachment_name VARCHAR(255) NULL,
  attachment_path VARCHAR(255) NULL,
  attachment_type VARCHAR(120) NULL,
  attachment_size INT NULL,
  submitted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  status ENUM('submitted','graded','returned') NOT NULL DEFAULT 'submitted',
  score DECIMAL(6,2) NULL,
  teacher_comment TEXT NULL,
  graded_at DATETIME NULL,
  CONSTRAINT fk_es_post FOREIGN KEY (post_id) REFERENCES elearning_posts(id) ON DELETE CASCADE,
  CONSTRAINT fk_es_learner FOREIGN KEY (learner_id) REFERENCES learners(id) ON DELETE CASCADE,
  UNIQUE KEY uq_es_post_learner (post_id, learner_id),
  INDEX idx_es_post (post_id),
  INDEX idx_es_learner (learner_id)
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS learner_marks (
  id INT AUTO_INCREMENT PRIMARY KEY,
  learner_id INT NOT NULL,
  teacher_id INT NOT NULL,
  class_id INT NOT NULL,
  subject_id INT NOT NULL,
  assessment_type ENUM(
    'daily_exercise',
    'weekly_test',
    'end_of_month_test',
    'end_of_term_exam',
    'midyear_exam',
    'end_of_year_exam'
  ) NOT NULL,
  term_name VARCHAR(30) NOT NULL,
  assessment_date DATE NOT NULL,
  score DECIMAL(6,2) NOT NULL,
  max_score DECIMAL(6,2) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_marks_learner FOREIGN KEY (learner_id) REFERENCES learners(id) ON DELETE CASCADE,
  CONSTRAINT fk_marks_teacher FOREIGN KEY (teacher_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_marks_class FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE CASCADE,
  CONSTRAINT fk_marks_subject FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE CASCADE,
  INDEX idx_marks_type (assessment_type)
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS fee_invoices (
  id INT AUTO_INCREMENT PRIMARY KEY,
  invoice_number VARCHAR(40) NOT NULL UNIQUE,
  learner_id INT NOT NULL,
  class_id INT NOT NULL,
  description VARCHAR(255) NOT NULL,
  amount_due DECIMAL(10,2) NOT NULL,
  fee_gpf DECIMAL(10,2) NOT NULL DEFAULT 0,
  fee_ssf DECIMAL(10,2) NOT NULL DEFAULT 0,
  fee_sdc DECIMAL(10,2) NOT NULL DEFAULT 0,
  fee_registration DECIMAL(10,2) NOT NULL DEFAULT 0,
  fee_zimsec DECIMAL(10,2) NOT NULL DEFAULT 0,
  due_date DATE NULL,
  status ENUM('unpaid', 'partially_paid', 'paid') NOT NULL DEFAULT 'unpaid',
  created_by INT NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  CONSTRAINT fk_fee_invoices_learner FOREIGN KEY (learner_id) REFERENCES learners(id) ON DELETE CASCADE,
  CONSTRAINT fk_fee_invoices_class FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE CASCADE,
  CONSTRAINT fk_fee_invoices_user FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE CASCADE
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS fee_payments (
  id INT AUTO_INCREMENT PRIMARY KEY,
  invoice_id INT NULL,
  learner_id INT NOT NULL,
  amount_paid DECIMAL(10,2) NOT NULL,
  currency_code ENUM('USD','ZIG','RAND') NOT NULL DEFAULT 'USD',
  fx_rate_to_usd DECIMAL(18,8) NOT NULL DEFAULT 1,
  amount_paid_usd DECIMAL(12,2) NOT NULL DEFAULT 0,
  payment_date DATE NOT NULL,
  fee_component VARCHAR(10) NOT NULL DEFAULT 'GPF',
  payment_method ENUM('cash','ecocash','bank_transfer','pos','other') NOT NULL DEFAULT 'cash',
  reference_no VARCHAR(80) NULL,
  note VARCHAR(255) NULL,
  received_by INT NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_fee_payments_invoice FOREIGN KEY (invoice_id) REFERENCES fee_invoices(id) ON DELETE SET NULL,
  CONSTRAINT fk_fee_payments_learner FOREIGN KEY (learner_id) REFERENCES learners(id) ON DELETE CASCADE,
  CONSTRAINT fk_fee_payments_user FOREIGN KEY (received_by) REFERENCES users(id) ON DELETE CASCADE
)");

$parentInvoiceColumnsToEnsure = [
  "fee_gpf DECIMAL(10,2) NOT NULL DEFAULT 0",
  "fee_ssf DECIMAL(10,2) NOT NULL DEFAULT 0",
  "fee_sdc DECIMAL(10,2) NOT NULL DEFAULT 0",
  "fee_registration DECIMAL(10,2) NOT NULL DEFAULT 0",
  "fee_zimsec DECIMAL(10,2) NOT NULL DEFAULT 0"
];
foreach ($parentInvoiceColumnsToEnsure as $columnSql) {
  try {
    $pdo->exec("ALTER TABLE fee_invoices ADD COLUMN " . $columnSql);
  } catch (PDOException $e) {
    // Ignore duplicate column errors for idempotent upgrades.
  }
}

$parentPaymentColumnsToEnsure = [
  "currency_code ENUM('USD','ZIG','RAND') NOT NULL DEFAULT 'USD'",
  "fx_rate_to_usd DECIMAL(18,8) NOT NULL DEFAULT 1",
  "amount_paid_usd DECIMAL(12,2) NOT NULL DEFAULT 0",
  "fee_component VARCHAR(10) NOT NULL DEFAULT 'GPF'"
];
foreach ($parentPaymentColumnsToEnsure as $columnSql) {
  try {
    $pdo->exec("ALTER TABLE fee_payments ADD COLUMN " . $columnSql);
  } catch (PDOException $e) {
    // Ignore duplicate column errors for idempotent upgrades.
  }
}

$pdo->exec("CREATE TABLE IF NOT EXISTS library_resources (
  id INT AUTO_INCREMENT PRIMARY KEY,
  teacher_id INT NOT NULL,
  class_id INT NOT NULL,
  subject_id INT NULL,
  document_type VARCHAR(40) NOT NULL DEFAULT 'other',
  title VARCHAR(180) NOT NULL,
  description TEXT NULL,
  original_name VARCHAR(255) NOT NULL,
  file_path VARCHAR(255) NOT NULL,
  mime_type VARCHAR(120) NULL,
  file_size BIGINT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  is_active TINYINT(1) NOT NULL DEFAULT 1,
  CONSTRAINT fk_lr_teacher FOREIGN KEY (teacher_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_lr_class FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE CASCADE,
  CONSTRAINT fk_lr_subject FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE SET NULL,
  INDEX idx_lr_class (class_id)
)");

$pdo->exec("CREATE TABLE IF NOT EXISTS announcements (
  id INT AUTO_INCREMENT PRIMARY KEY,
  sender_id INT NOT NULL,
  sender_role ENUM('admin','teacher') NOT NULL,
  audience ENUM('teacher','learner','parent') NOT NULL,
  target_class_id INT NULL,
  target_learner_id INT NULL,
  title VARCHAR(180) NOT NULL,
  body TEXT NOT NULL,
  status ENUM('published','pending_admin_review','rejected') NOT NULL DEFAULT 'published',
  admin_review_comment TEXT NULL,
  reviewed_by INT NULL,
  reviewed_at DATETIME NULL,
  published_at DATETIME NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_ann_sender FOREIGN KEY (sender_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_ann_reviewer FOREIGN KEY (reviewed_by) REFERENCES users(id) ON DELETE SET NULL,
  CONSTRAINT fk_ann_target_class FOREIGN KEY (target_class_id) REFERENCES classes(id) ON DELETE SET NULL,
  CONSTRAINT fk_ann_target_learner FOREIGN KEY (target_learner_id) REFERENCES learners(id) ON DELETE SET NULL,
  INDEX idx_ann_audience_status_created (audience, status, created_at)
)");

$announcementColumnsToEnsure = [
  "target_class_id INT NULL",
  "target_learner_id INT NULL"
];
foreach ($announcementColumnsToEnsure as $columnSql) {
  try {
    $pdo->exec("ALTER TABLE announcements ADD COLUMN " . $columnSql);
  } catch (PDOException $e) {
    // Ignore duplicate column errors to keep migration idempotent.
  }
}

$parentUserId = (int)($_SESSION['user_id'] ?? 0);
$parentProfileStmt = $pdo->prepare("SELECT id, name, email, password_hash FROM users WHERE id = ? AND role = 'parent' LIMIT 1");
$parentProfileStmt->execute([$parentUserId]);
$parentProfile = $parentProfileStmt->fetch();

if (!$parentProfile) {
  logout_user();
  header('Location: index.php');
  exit;
}

$linkedLearnersStmt = $pdo->prepare("SELECT l.id, l.reg_number, l.full_name, l.surname, l.christian_names,
  l.class_id, c.name AS class_name, l.date_of_admission, l.date_of_birth_info, l.birth_certificate_number,
    l.gender, l.guardian_name, l.guardian_phone, l.guardian_address, l.student_photo_path
  FROM parent_learner_links pll
  JOIN learners l ON l.id = pll.learner_id
  JOIN classes c ON c.id = l.class_id
  WHERE pll.parent_user_id = ?
  ORDER BY c.id, l.surname, l.christian_names, l.full_name");
$linkedLearnersStmt->execute([$parentUserId]);
$linkedLearners = $linkedLearnersStmt->fetchAll();

$selectedLearnerId = (int)($_GET['learner_id'] ?? 0);
$linkedLearner = null;
if (!empty($linkedLearners)) {
  if ($selectedLearnerId > 0) {
    foreach ($linkedLearners as $candidateLearner) {
      if ((int)$candidateLearner['id'] === $selectedLearnerId) {
        $linkedLearner = $candidateLearner;
        break;
      }
    }
  }

  if (!$linkedLearner) {
    $linkedLearner = $linkedLearners[0];
    $selectedLearnerId = (int)$linkedLearner['id'];
  }
}

if (empty($linkedLearners) || !$linkedLearner) {
  $fallbackSchoolName = trim(get_app_setting($pdo, 'school_name', 'MAVELA GOVERNMENT HIGH SCHOOL'));
  if ($fallbackSchoolName === '') {
    $fallbackSchoolName = 'MAVELA GOVERNMENT HIGH SCHOOL';
  }
  $fallbackPalette = get_school_theme_palette($pdo);
  $fallbackBgCream = (string)($fallbackPalette['bg_cream'] ?? '#F7FBF7');
  $fallbackBgSand = (string)($fallbackPalette['bg_sand'] ?? '#E5F0E6');
  $fallbackInk = (string)($fallbackPalette['ink'] ?? '#173122');
  $fallbackMuted = (string)($fallbackPalette['muted'] ?? '#4F6656');
  $fallbackBrandNavy = (string)($fallbackPalette['brand_navy'] ?? '#2E8B45');
  $fallbackBrandNavyDeep = (string)($fallbackPalette['brand_navy_deep'] ?? '#1D6A33');
  $fallbackPatchSky = (string)($fallbackPalette['patch_sky'] ?? '#7CC9FF');
  $fallbackPatchSkySoft = (string)($fallbackPalette['patch_sky_soft'] ?? '#D6EEFF');
  ?>
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Parent Desk | <?= h($fallbackSchoolName) ?></title>
    <style>
      body {
        font-family: 'Outfit', sans-serif;
        margin: 0;
        padding: 24px;
        background:
          radial-gradient(circle at 15% 18%, rgba(248, 180, 0, 0.2) 0, rgba(248, 180, 0, 0) 40%),
          radial-gradient(circle at 80% 20%, rgba(124, 201, 255, 0.24) 0, rgba(124, 201, 255, 0) 38%),
          linear-gradient(170deg, <?= h($fallbackBgCream) ?> 0%, <?= h($fallbackBgSand) ?> 100%);
        color: <?= h($fallbackInk) ?>;
      }
      .card {
        max-width: 760px;
        margin: 28px auto;
        background: #fff;
        border: 1px solid <?= h($fallbackPatchSkySoft) ?>;
        border-radius: 14px;
        padding: 20px;
        box-shadow: 0 18px 45px rgba(10, 47, 99, 0.14);
      }
      h1 {
        margin: 0 0 10px;
        color: <?= h($fallbackBrandNavyDeep) ?>;
        font-family: 'Plus Jakarta Sans', sans-serif;
      }
      p {
        color: <?= h($fallbackMuted) ?>;
      }
      a {
        color: <?= h($fallbackBrandNavy) ?>;
        font-weight: 700;
        text-decoration: none;
      }
      a:hover {
        background-color: #dff4ff;
        border-color: #7cc9ff;
        color: #083b78;
        text-decoration: underline;
      }
    </style>
  </head>
  <body>
    <div class="card">
      <h1>Parent Desk</h1>
      <p>Your parent account is active, but no learner has been linked yet.</p>
      <p>Please contact the school admin to link your learner profile.</p>
      <p><a href="logout.php">Logout</a></p>
    </div>
  </body>
  </html>
  <?php
  exit;
}

$learnerId = (int)$linkedLearner['id'];
$classId = (int)$linkedLearner['class_id'];
$alerts = [];

if (isset($_POST['save_parent_profile'])) {
  $profileName = trim((string)($_POST['profile_name'] ?? ''));
  $profileEmail = trim((string)($_POST['profile_email'] ?? ''));

  if ($profileName === '' || $profileEmail === '') {
    $alerts[] = ['type' => 'error', 'text' => 'Profile name and email are required.'];
  } elseif (!filter_var($profileEmail, FILTER_VALIDATE_EMAIL)) {
    $alerts[] = ['type' => 'error', 'text' => 'Please provide a valid email address.'];
  } else {
    $emailExistsStmt = $pdo->prepare("SELECT id FROM users WHERE LOWER(email) = LOWER(?) AND id <> ? LIMIT 1");
    $emailExistsStmt->execute([$profileEmail, $parentUserId]);
    if ($emailExistsStmt->fetch()) {
      $alerts[] = ['type' => 'error', 'text' => 'That email is already used by another account.'];
    } else {
      $updateProfileStmt = $pdo->prepare("UPDATE users SET name = ?, email = ? WHERE id = ? AND role = 'parent' LIMIT 1");
      $updateProfileStmt->execute([$profileName, $profileEmail, $parentUserId]);
      $_SESSION['name'] = $profileName;
      $parentProfile['name'] = $profileName;
      $parentProfile['email'] = $profileEmail;
      $alerts[] = ['type' => 'success', 'text' => 'Parent profile updated successfully.'];
    }
  }
}

if (isset($_POST['change_parent_password'])) {
  $currentPassword = (string)($_POST['current_password'] ?? '');
  $newPassword = (string)($_POST['new_password'] ?? '');
  $confirmPassword = (string)($_POST['confirm_password'] ?? '');

  if ($currentPassword === '' || $newPassword === '' || $confirmPassword === '') {
    $alerts[] = ['type' => 'error', 'text' => 'Current password, new password, and confirmation are required.'];
  } elseif (!password_verify($currentPassword, (string)$parentProfile['password_hash'])) {
    $alerts[] = ['type' => 'error', 'text' => 'Current password is incorrect.'];
  } elseif (!mavela_password_is_strong($newPassword)) {
    $alerts[] = ['type' => 'error', 'text' => 'Use at least 10 characters with uppercase, lowercase, and a number.'];
  } elseif ($newPassword !== $confirmPassword) {
    $alerts[] = ['type' => 'error', 'text' => 'New password and confirmation do not match.'];
  } else {
    $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
    $updatePasswordStmt = $pdo->prepare("UPDATE users SET password_hash = ?, must_change_password = 0 WHERE id = ? AND role = 'parent' LIMIT 1");
    $updatePasswordStmt->execute([$newHash, $parentUserId]);
    $_SESSION['must_change_password'] = false;
    $parentProfile['password_hash'] = $newHash;
    $alerts[] = ['type' => 'success', 'text' => 'Parent password changed successfully.'];
  }
}

if (isset($_POST['submit_transfer_request'])) {
  $destinationSchool = trim((string)($_POST['destination_school'] ?? ''));
  $transferReason = trim((string)($_POST['transfer_reason'] ?? ''));

  if ($destinationSchool === '' || $transferReason === '') {
    $alerts[] = ['type' => 'error', 'text' => 'Destination school and transfer reason are required.'];
  } else {
    $pendingCheckStmt = $pdo->prepare("SELECT id FROM transfer_requests
      WHERE parent_user_id = ? AND learner_id = ? AND status IN ('pending_admin', 'clearance_requested', 'approved')
      LIMIT 1");
    $pendingCheckStmt->execute([$parentUserId, $learnerId]);

    if ($pendingCheckStmt->fetch()) {
      $alerts[] = ['type' => 'error', 'text' => 'There is already an active transfer request for this learner.'];
    } else {
      $insertTransferStmt = $pdo->prepare("INSERT INTO transfer_requests
        (parent_user_id, learner_id, destination_school, reason, status, requested_at)
        VALUES (?, ?, ?, ?, 'pending_admin', NOW())");
      $insertTransferStmt->execute([$parentUserId, $learnerId, $destinationSchool, $transferReason]);
      $alerts[] = ['type' => 'success', 'text' => 'Transfer request submitted for admin review.'];
    }
  }
}

function report_grade_from_percent(float $percent): array {
  if ($percent >= 80) {
    return ['grade' => 'A', 'status' => 'PASS'];
  }
  if ($percent >= 70) {
    return ['grade' => 'B', 'status' => 'PASS'];
  }
  if ($percent >= 60) {
    return ['grade' => 'C', 'status' => 'PASS'];
  }
  if ($percent >= 50) {
    return ['grade' => 'D', 'status' => 'PASS'];
  }
  if ($percent >= 40) {
    return ['grade' => 'E', 'status' => 'FAIL'];
  }
  return ['grade' => 'U', 'status' => 'FAIL'];
}

$majorAssessmentTypes = ['end_of_term_exam', 'midyear_exam', 'end_of_year_exam'];
$placeholders = implode(',', array_fill(0, count($majorAssessmentTypes), '?'));
$majorReportStmt = $pdo->prepare("SELECT lm.assessment_type, lm.term_name, s.name AS subject_name,
    SUM(lm.score) AS total_score, SUM(lm.max_score) AS total_max
  FROM learner_marks lm
  JOIN subjects s ON s.id = lm.subject_id
  WHERE lm.learner_id = ? AND lm.assessment_type IN ($placeholders)
  GROUP BY lm.assessment_type, lm.term_name, s.name
  ORDER BY lm.assessment_type, s.name");
$params = array_merge([$learnerId], $majorAssessmentTypes);
$majorReportStmt->execute($params);
$majorReportRows = $majorReportStmt->fetchAll();

$examLabels = [
  'end_of_term_exam' => 'End of Term Exam',
  'midyear_exam' => 'Midyear Exam',
  'end_of_year_exam' => 'End of Year Exam'
];

$learnerInvoicesStmt = $pdo->prepare("SELECT fi.id, fi.invoice_number, fi.description, fi.amount_due,
  fi.fee_gpf, fi.fee_ssf, fi.fee_sdc, fi.fee_registration, fi.fee_zimsec, fi.due_date,
  fi.status, fi.created_at, COALESCE(SUM(COALESCE(fp.amount_paid_usd, fp.amount_paid)), 0) AS paid_total
  FROM fee_invoices fi
  LEFT JOIN fee_payments fp ON fp.invoice_id = fi.id
  WHERE fi.learner_id = ?
  GROUP BY fi.id
  ORDER BY fi.created_at DESC");
$learnerInvoicesStmt->execute([$learnerId]);
$learnerInvoices = $learnerInvoicesStmt->fetchAll();

$learnerPaymentsStmt = $pdo->prepare("SELECT fp.id, fp.amount_paid, fp.currency_code, fp.fx_rate_to_usd, fp.amount_paid_usd,
  fp.fee_component,
  fp.payment_date, fp.payment_method, fp.reference_no, fp.note, fp.created_at, fi.invoice_number
  FROM fee_payments fp
  LEFT JOIN fee_invoices fi ON fi.id = fp.invoice_id
  WHERE fp.learner_id = ?
  ORDER BY fp.payment_date DESC, fp.created_at DESC
  LIMIT 120");
$learnerPaymentsStmt->execute([$learnerId]);
$learnerPayments = $learnerPaymentsStmt->fetchAll();

$totalInvoiced = 0.0;
$totalPaid = 0.0;
foreach ($learnerInvoices as $invoice) {
  $totalInvoiced += (float)$invoice['amount_due'];
}
foreach ($learnerPayments as $payment) {
  $paidUsd = (float)($payment['amount_paid_usd'] ?? 0);
  if ($paidUsd <= 0) {
    $paidUsd = (float)$payment['amount_paid'];
  }
  $totalPaid += $paidUsd;
}
$outstandingBalance = max(0, $totalInvoiced - $totalPaid);

$ledgerEntries = [];
foreach ($learnerInvoices as $invoice) {
  $ledgerEntries[] = [
    'entry_type' => 'invoice',
    'entry_date' => (string)($invoice['created_at'] ?: date('Y-m-d H:i:s')),
    'description' => 'Invoice ' . (string)$invoice['invoice_number'] . ' - ' . (string)$invoice['description'],
    'debit' => (float)$invoice['amount_due'],
    'credit' => 0.0,
    'reference' => (string)$invoice['invoice_number']
  ];
}

// Consolidate component-split rows (GPF/SSF/SDC) into one ledger payment line.
$paymentLedgerGroups = [];
foreach ($learnerPayments as $payment) {
  $creditUsd = (float)($payment['amount_paid_usd'] ?? 0);
  if ($creditUsd <= 0) {
    $creditUsd = (float)$payment['amount_paid'];
  }

  $entryDate = (string)($payment['payment_date'] ?: $payment['created_at'] ?: date('Y-m-d H:i:s'));
  $reference = (string)($payment['reference_no'] ?: ($payment['invoice_number'] ?: '-'));
  $invoiceNo = (string)($payment['invoice_number'] ?: '-');
  $method = strtoupper(str_replace('_', ' ', (string)$payment['payment_method']));
  $currency = strtoupper((string)($payment['currency_code'] ?? 'USD'));
  $paymentId = (int)($payment['id'] ?? 0);
  $groupKey = $reference !== ''
    ? implode('|', ['R', $entryDate, $reference, $invoiceNo, $method, $currency])
    : implode('|', ['I', (string)$paymentId]);

  if (!isset($paymentLedgerGroups[$groupKey])) {
    $paymentLedgerGroups[$groupKey] = [
      'entry_date' => $entryDate,
      'method' => $method,
      'currency' => $currency,
      'reference' => $reference,
      'credit' => 0.0,
      'components' => []
    ];
  }

  $component = strtoupper((string)($payment['fee_component'] ?? 'GENERAL'));
  if ($component !== '' && !in_array($component, $paymentLedgerGroups[$groupKey]['components'], true)) {
    $paymentLedgerGroups[$groupKey]['components'][] = $component;
  }
  $paymentLedgerGroups[$groupKey]['credit'] += $creditUsd;
}

foreach ($paymentLedgerGroups as $group) {
  $componentLabel = !empty($group['components']) ? implode('/', $group['components']) : 'GENERAL';
  $ledgerEntries[] = [
    'entry_type' => 'payment',
    'entry_date' => (string)$group['entry_date'],
    'description' => 'Payment received - ' . $componentLabel
      . ' / ' . (string)$group['method']
      . ' (' . (string)$group['currency'] . ')',
    'debit' => 0.0,
    'credit' => (float)$group['credit'],
    'reference' => (string)$group['reference']
  ];
}

usort($ledgerEntries, static function (array $a, array $b): int {
  return strcmp((string)$a['entry_date'], (string)$b['entry_date']);
});

$runningBalance = 0.0;
foreach ($ledgerEntries as $idx => $entry) {
  $runningBalance += (float)$entry['debit'];
  $runningBalance -= (float)$entry['credit'];
  $ledgerEntries[$idx]['balance'] = round($runningBalance, 2);
}

$reportCardExamOptions = [
  'end_of_term_exam_term1' => 'End of Term 1',
  'midyear_exam' => 'Midyear',
  'end_of_year_exam' => 'End of Year'
];

$learnerMajorMarksStmt = $pdo->prepare("SELECT lm.learner_id, lm.assessment_type, lm.term_name, lm.assessment_date,
    lm.score, lm.max_score, s.name AS subject_name
  FROM learner_marks lm
  JOIN subjects s ON s.id = lm.subject_id
  WHERE lm.learner_id = ?
    AND lm.class_id = ?
    AND lm.assessment_type IN ('end_of_term_exam', 'midyear_exam', 'end_of_year_exam')
  ORDER BY s.name, lm.assessment_date");
$learnerMajorMarksStmt->execute([$learnerId, $classId]);
$learnerMajorMarks = $learnerMajorMarksStmt->fetchAll();

$classMajorMarksStmt = $pdo->prepare("SELECT lm.learner_id, lm.assessment_type, lm.term_name, lm.score, lm.max_score
  FROM learner_marks lm
  WHERE lm.class_id = ?
    AND lm.assessment_type IN ('end_of_term_exam', 'midyear_exam', 'end_of_year_exam')");
$classMajorMarksStmt->execute([$classId]);
$classMajorMarks = $classMajorMarksStmt->fetchAll();

$reportCardDataset = [];
foreach ($reportCardExamOptions as $examKey => $examLabel) {
  $subjectBuckets = [];

  foreach ($learnerMajorMarks as $markRow) {
    $type = (string)$markRow['assessment_type'];
    $termName = strtolower(trim((string)$markRow['term_name']));
    $isMatch = false;

    if ($examKey === 'end_of_term_exam_term1') {
      $isMatch = $type === 'end_of_term_exam' && $termName === 'term 1';
    } elseif ($examKey === 'midyear_exam') {
      $isMatch = $type === 'midyear_exam';
    } elseif ($examKey === 'end_of_year_exam') {
      $isMatch = $type === 'end_of_year_exam';
    }

    if (!$isMatch) {
      continue;
    }

    $subjectName = (string)$markRow['subject_name'];
    if (!isset($subjectBuckets[$subjectName])) {
      $subjectBuckets[$subjectName] = ['obtained' => 0.0, 'total' => 0.0];
    }

    $subjectBuckets[$subjectName]['obtained'] += (float)$markRow['score'];
    $subjectBuckets[$subjectName]['total'] += (float)$markRow['max_score'];
  }

  ksort($subjectBuckets);
  $subjectRows = [];
  $totalObtained = 0.0;
  $totalPossible = 0.0;
  foreach ($subjectBuckets as $subjectName => $totals) {
    $obtained = (float)$totals['obtained'];
    $possible = (float)$totals['total'];
    $percent = $possible > 0 ? ($obtained / $possible) * 100 : 0.0;
    $gradeInfo = report_grade_from_percent($percent);
    $subjectRows[] = [
      'subject' => $subjectName,
      'obtained' => round($obtained, 1),
      'total' => round($possible, 1),
      'percent' => round($percent, 1),
      'grade' => $gradeInfo['grade'],
      'status' => $gradeInfo['status']
    ];
    $totalObtained += $obtained;
    $totalPossible += $possible;
  }

  $overallPercent = $totalPossible > 0 ? ($totalObtained / $totalPossible) * 100 : 0.0;
  $overallGrade = report_grade_from_percent($overallPercent);

  $classTotalsByLearner = [];
  foreach ($classMajorMarks as $classRow) {
    $type = (string)$classRow['assessment_type'];
    $termName = strtolower(trim((string)$classRow['term_name']));
    $isMatch = false;

    if ($examKey === 'end_of_term_exam_term1') {
      $isMatch = $type === 'end_of_term_exam' && $termName === 'term 1';
    } elseif ($examKey === 'midyear_exam') {
      $isMatch = $type === 'midyear_exam';
    } elseif ($examKey === 'end_of_year_exam') {
      $isMatch = $type === 'end_of_year_exam';
    }

    if (!$isMatch) {
      continue;
    }

    $rowLearnerId = (int)$classRow['learner_id'];
    if (!isset($classTotalsByLearner[$rowLearnerId])) {
      $classTotalsByLearner[$rowLearnerId] = ['obtained' => 0.0, 'total' => 0.0];
    }
    $classTotalsByLearner[$rowLearnerId]['obtained'] += (float)$classRow['score'];
    $classTotalsByLearner[$rowLearnerId]['total'] += (float)$classRow['max_score'];
  }

  $classPercents = [];
  foreach ($classTotalsByLearner as $rowLearnerId => $totals) {
    $possible = (float)$totals['total'];
    $percent = $possible > 0 ? ((float)$totals['obtained'] / $possible) * 100 : 0.0;
    $classPercents[] = ['learner_id' => (int)$rowLearnerId, 'percent' => $percent];
  }

  usort($classPercents, static function (array $a, array $b): int {
    return $b['percent'] <=> $a['percent'];
  });

  $classStrength = count($classPercents);
  $classAverage = 0.0;
  $classMax = 0.0;
  $classMin = 0.0;
  $position = '-';
  if ($classStrength > 0) {
    $sum = 0.0;
    foreach ($classPercents as $idx => $row) {
      $sum += (float)$row['percent'];
      if ((int)$row['learner_id'] === $learnerId && $position === '-') {
        $position = (string)($idx + 1);
      }
    }
    $classAverage = $sum / $classStrength;
    $classMax = (float)$classPercents[0]['percent'];
    $classMin = (float)$classPercents[$classStrength - 1]['percent'];
  }

  $reportCardDataset[$examKey] = [
    'exam_label' => $examLabel,
    'subject_rows' => $subjectRows,
    'total_obtained' => round($totalObtained, 1),
    'total_possible' => round($totalPossible, 1),
    'overall_percent' => round($overallPercent, 1),
    'overall_grade' => $overallGrade['grade'],
    'overall_status' => $overallGrade['status'],
    'class_strength' => $classStrength,
    'class_average' => round($classAverage, 1),
    'class_max' => round($classMax, 1),
    'class_min' => round($classMin, 1),
    'position' => $position
  ];
}

$elearningItemsStmt = $pdo->prepare("SELECT ep.title, ep.content_type, ep.instructions, ep.due_date, ep.created_at,
    u.name AS teacher_name, s.name AS subject_name,
    es.status AS submission_status, es.score, es.teacher_comment, es.submitted_at
  FROM elearning_posts ep
  JOIN users u ON u.id = ep.teacher_id
  LEFT JOIN subjects s ON s.id = ep.subject_id
  LEFT JOIN elearning_submissions es ON es.post_id = ep.id AND es.learner_id = ?
  WHERE ep.class_id = ?
  ORDER BY ep.created_at DESC
  LIMIT 150");
$elearningItemsStmt->execute([$learnerId, $classId]);
$elearningItems = $elearningItemsStmt->fetchAll();

$libraryItemsStmt = $pdo->prepare("SELECT lr.title, lr.description, lr.original_name, lr.file_path,
    lr.document_type, lr.created_at, u.name AS teacher_name, s.name AS subject_name
  FROM library_resources lr
  JOIN users u ON u.id = lr.teacher_id
  LEFT JOIN subjects s ON s.id = lr.subject_id
  WHERE lr.class_id = ? AND lr.is_active = 1
  ORDER BY lr.created_at DESC
  LIMIT 200");
$libraryItemsStmt->execute([$classId]);
$libraryItems = $libraryItemsStmt->fetchAll();

$parentAnnouncementsStmt = $pdo->prepare("SELECT a.title, a.body, a.created_at, a.published_at,
    a.sender_role, a.target_class_id, a.target_learner_id,
    u.name AS sender_name
  FROM announcements a
  JOIN users u ON u.id = a.sender_id
  WHERE a.audience = 'parent'
    AND a.status = 'published'
    AND (a.target_class_id IS NULL OR a.target_class_id = ?)
    AND (a.target_learner_id IS NULL OR a.target_learner_id = ?)
  ORDER BY COALESCE(a.published_at, a.created_at) DESC
  LIMIT 200");
$parentAnnouncementsStmt->execute([$classId, $learnerId]);
$parentAnnouncements = $parentAnnouncementsStmt->fetchAll();

$parentTransferRequestsStmt = $pdo->prepare("SELECT tr.id, tr.destination_school, tr.reason, tr.status, tr.requested_at,
    tr.teacher_status, tr.teacher_comment, tr.teacher_reviewed_at,
    tr.accountant_status, tr.accountant_comment, tr.accountant_reviewed_at,
    tr.admin_comment, tr.reviewed_at_admin,
    tl.id AS letter_id, tl.letter_html, tl.generated_at
  FROM transfer_requests tr
  LEFT JOIN transfer_letters tl ON tl.transfer_request_id = tr.id
  WHERE tr.parent_user_id = ? AND tr.learner_id = ?
  ORDER BY tr.requested_at DESC
  LIMIT 120");
$parentTransferRequestsStmt->execute([$parentUserId, $learnerId]);
$parentTransferRequests = $parentTransferRequestsStmt->fetchAll();

$learnerDisplayName = trim((string)($linkedLearner['full_name'] ?? ''));
if ($learnerDisplayName === '') {
  $learnerDisplayName = trim((string)($linkedLearner['christian_names'] ?? '') . ' ' . (string)($linkedLearner['surname'] ?? ''));
}
if ($learnerDisplayName === '') {
  $learnerDisplayName = 'Learner';
}

$learnerPhotoPath = trim((string)($linkedLearner['student_photo_path'] ?? ''));
$learnerPhotoExists = $learnerPhotoPath !== '' && is_file(__DIR__ . '/' . ltrim($learnerPhotoPath, '/\\'));
$learnerInitials = '';
foreach (preg_split('/\s+/', $learnerDisplayName) as $namePart) {
  if ($namePart !== '') {
    $learnerInitials .= strtoupper(substr($namePart, 0, 1));
  }
  if (strlen($learnerInitials) >= 2) {
    break;
  }
}
if ($learnerInitials === '') {
  $learnerInitials = 'L';
}

$defaultSchoolName = 'MAVELA GOVERNMENT HIGH SCHOOL';
$defaultSchoolAddress = 'P.O.Box 12 Tsholotsho';
$defaultSchoolContact = 'Phone: +263 77 000 0000 | Email: admin@mavelahigh.org';
$defaultSchoolMotto = 'Education for all';
$defaultSchoolLogoPath = 'Uploads/Mavela_Logo.png';

$schoolName = trim(get_app_setting($pdo, 'school_name', $defaultSchoolName));
$schoolAddress = trim(get_app_setting($pdo, 'school_address', $defaultSchoolAddress));
$schoolContact = trim(get_app_setting($pdo, 'school_contact', $defaultSchoolContact));
$schoolMotto = trim(get_app_setting($pdo, 'school_motto', $defaultSchoolMotto));
$schoolLogoPath = trim(get_app_setting($pdo, 'school_logo_path', $defaultSchoolLogoPath));

if ($schoolName === '') {
  $schoolName = $defaultSchoolName;
}
if ($schoolAddress === '') {
  $schoolAddress = $defaultSchoolAddress;
}
if ($schoolContact === '') {
  $schoolContact = $defaultSchoolContact;
}
if ($schoolMotto === '') {
  $schoolMotto = $defaultSchoolMotto;
}
if ($schoolLogoPath === '' || !is_file(__DIR__ . '/' . ltrim($schoolLogoPath, '/\\'))) {
  $schoolLogoPath = $defaultSchoolLogoPath;
}

$themePalette = get_school_theme_palette($pdo);
$paletteBgCream = (string)($themePalette['bg_cream'] ?? '#F7FBF7');
$paletteBgSand = (string)($themePalette['bg_sand'] ?? '#E5F0E6');
$paletteInk = (string)($themePalette['ink'] ?? '#173122');
$paletteMuted = (string)($themePalette['muted'] ?? '#4F6656');
$paletteBrandNavy = (string)($themePalette['brand_navy'] ?? '#2E8B45');
$paletteBrandNavyDeep = (string)($themePalette['brand_navy_deep'] ?? '#1D6A33');
$paletteBrandIce = (string)($themePalette['brand_ice'] ?? '#EEF7EF');
$palettePatchSky = (string)($themePalette['patch_sky'] ?? '#7CC9FF');
$palettePatchSkySoft = (string)($themePalette['patch_sky_soft'] ?? '#D6EEFF');
$palettePatchYellow = (string)($themePalette['patch_yellow'] ?? '#FFD447');

$schoolLogoDataUri = '';
$learnerReportLogoPath = __DIR__ . '/' . ltrim($schoolLogoPath, '/\\');
if (is_file($learnerReportLogoPath)) {
  $learnerReportLogoBytes = @file_get_contents($learnerReportLogoPath);
  if ($learnerReportLogoBytes !== false) {
    $schoolLogoMime = mime_content_type($learnerReportLogoPath) ?: 'image/jpeg';
    $schoolLogoDataUri = 'data:' . $schoolLogoMime . ';base64,' . base64_encode($learnerReportLogoBytes);
  }
}

$reportMeta = [
  'school_name' => $schoolName,
  'school_address' => $schoolAddress,
  'school_contact' => $schoolContact,
  'school_motto' => $schoolMotto,
  'palette' => [
    'bg_cream' => $paletteBgCream,
    'bg_sand' => $paletteBgSand,
    'ink' => $paletteInk,
    'muted' => $paletteMuted,
    'brand_navy' => $paletteBrandNavy,
    'brand_navy_deep' => $paletteBrandNavyDeep,
    'brand_ice' => $paletteBrandIce,
    'patch_sky' => $palettePatchSky,
    'patch_sky_soft' => $palettePatchSkySoft,
    'patch_yellow' => $palettePatchYellow
  ],
  'prepared_by' => 'Parent Desk'
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Parent Desk | <?= h($schoolName) ?></title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Plus+Jakarta+Sans:wght@500;600;700;800&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg-cream: <?= h($paletteBgCream) ?>;
      --bg-sand: <?= h($paletteBgSand) ?>;
      --ink: <?= h($paletteInk) ?>;
      --muted: <?= h($paletteMuted) ?>;
      --brand-navy: <?= h($paletteBrandNavy) ?>;
      --brand-navy-deep: <?= h($paletteBrandNavyDeep) ?>;
      --line: <?= h($palettePatchSkySoft) ?>;
      --brand-ice: <?= h($paletteBrandIce) ?>;
      --patch-sky: <?= h($palettePatchSky) ?>;
      --patch-yellow: <?= h($palettePatchYellow) ?>;
      --panel: #ffffff;
      --shadow: 0 18px 45px rgba(10, 47, 99, 0.14);
    }
    * { box-sizing: border-box; }
    body {
      margin: 0;
      min-height: 100vh;
      font-family: 'Outfit', sans-serif;
      color: var(--ink);
      background:
        radial-gradient(circle at 15% 18%, rgba(248, 180, 0, 0.2) 0, rgba(248, 180, 0, 0) 40%),
        radial-gradient(circle at 80% 20%, rgba(124, 201, 255, 0.24) 0, rgba(124, 201, 255, 0) 38%),
        linear-gradient(170deg, var(--bg-cream) 0%, var(--bg-sand) 100%);
      padding: 14px;
    }
    .shell { max-width: 1320px; margin: 0 auto; display: grid; gap: 12px; }
    .header {
      border-radius: 16px;
      padding: 16px;
      background: linear-gradient(122deg, var(--brand-navy-deep), var(--brand-navy) 55%, var(--patch-sky));
      color: #fff;
      box-shadow: var(--shadow);
      display: flex;
      justify-content: space-between;
      gap: 10px;
      flex-wrap: wrap;
      align-items: center;
    }
    .chip { border: 1px solid #f8b400; background: #ffd447; color: #12386d; border-radius: 999px; padding: 8px 12px; text-decoration: none; font-weight: 700; }
    .desk-layout { display: grid; grid-template-columns: 240px minmax(0, 1fr); gap: 12px; }
    .sidebar { background: #fff; border: 1px solid var(--line); border-radius: 14px; box-shadow: var(--shadow); padding: 10px; }
    .side-btn { width: 100%; text-align: left; border: 1px solid #d8def0; background: #f8fbff; color: #12386d; border-radius: 10px; padding: 8px 10px; margin-bottom: 6px; font-family: 'Plus Jakarta Sans', sans-serif; font-weight: 700; font-size: 0.84rem; cursor: pointer; }
    .side-btn.active { background: linear-gradient(115deg, var(--brand-navy), var(--brand-navy-deep)); color: #fff; }
    .main { display: grid; gap: 10px; }
    .view {
      display: none !important;
      visibility: hidden;
      height: 0;
      overflow: hidden;
    }
    .view.active {
      display: grid !important;
      gap: 12px;
      visibility: visible;
      height: auto;
      overflow: visible;
    }
    .panel { background: #fff; border: 1px solid var(--line); border-radius: 14px; box-shadow: var(--shadow); padding: 14px; }
    .stats { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: 10px; }
    .stat { background: #fff; border: 1px solid #d8def0; border-radius: 12px; padding: 12px; }
    .stat small { color: var(--muted); display: block; }
    .stat strong { font-size: 1.2rem; }
    .muted { color: var(--muted); font-size: 0.92rem; }
    .badge { display: inline-block; border: 1px solid #bfd4f4; background: var(--brand-ice); color: var(--brand-navy-deep); border-radius: 999px; padding: 3px 8px; font-weight: 700; font-size: 0.77rem; }
    .item { border: 1px solid #d8def0; border-radius: 12px; padding: 11px; margin-bottom: 10px; background: #f9fcff; }
    .table-wrap { overflow-x: auto; }
    table { width: 100%; border-collapse: collapse; }
    th, td { border: 1px solid #d8def0; padding: 8px; text-align: left; vertical-align: top; }
    th { background: #f0f5ff; }
    .alert { border-radius: 10px; padding: 10px 12px; border: 1px solid; margin-bottom: 10px; }
    .alert.success { background: #ecfdf3; border-color: #9de0b7; color: #14532d; }
    .alert.error { background: #fff1f2; border-color: #f5b9c0; color: #9f1239; }
    .ledger-balance-banner {
      margin: 2px 0 10px;
      padding: 12px 14px;
      border-radius: 12px;
      border: 1px solid #fecaca;
      background: linear-gradient(120deg, #fff1f2 0%, #ffe4e6 100%);
      color: #991b1b;
      font-weight: 900;
      font-size: 1.15rem;
      letter-spacing: 0.2px;
    }
    .ledger-stream { display: grid; gap: 10px; }
    .ledger-row {
      border: 1px solid #d8def0;
      border-radius: 12px;
      background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
      padding: 10px;
      display: grid;
      gap: 8px;
      box-shadow: 0 4px 14px rgba(8, 34, 78, 0.05);
    }
    .ledger-row-head { display: flex; justify-content: space-between; gap: 8px; flex-wrap: wrap; align-items: center; }
    .ledger-row-date { font-weight: 800; color: #12386d; font-size: 0.9rem; }
    .ledger-row-ref {
      border: 1px solid #bfdbfe;
      background: #eff6ff;
      color: #1d4ed8;
      border-radius: 999px;
      padding: 3px 8px;
      font-size: 0.74rem;
      font-weight: 700;
    }
    .ledger-row-desc { color: #334155; font-size: 0.9rem; }
    .ledger-money-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
    .ledger-money-card { border: 1px solid #e2e8f0; background: #ffffff; border-radius: 10px; padding: 8px; }
    .ledger-money-card small {
      display: block;
      color: #64748b;
      font-size: 0.74rem;
      margin-bottom: 4px;
      text-transform: uppercase;
      letter-spacing: 0.4px;
      font-weight: 700;
    }
    .ledger-money-card strong { font-size: 0.95rem; }
    .ledger-money-card.debit strong { color: #b45309; }
    .ledger-money-card.credit strong { color: #065f46; }
    .ledger-money-card.balance strong { color: #991b1b; font-weight: 900; }

    a:hover,
    button:hover,
    input:hover,
    select:hover,
    textarea:hover,
    [role="button"]:hover,
    .button:hover,
    .btn:hover,
    .submit:hover,
    .chip:hover,
    .meta-chip:hover,
    .side-btn:hover,
    .desk-nav-btn:not(.active):hover,
    .menu button:hover,
    table tbody tr:hover td,
    table tbody tr:hover th,
    .card:hover,
    .panel:hover,
    .item:hover,
    .metric:hover,
    .stat:hover {
      background-color: #dff4ff !important;
      border-color: #7cc9ff !important;
      color: #083b78 !important;
    }

    @media (max-width: 900px) {
      .desk-layout { grid-template-columns: 1fr; }
      .stats { grid-template-columns: 1fr; }
    }

    @media (max-width: 560px) {
      body { padding: 10px; }
      .header { padding: 12px; }
      .panel { padding: 12px; }
      th, td { padding: 7px; }

      input,
      select,
      textarea {
        font-size: 16px;
      }

      .side-btn,
      .chip {
        min-height: 44px;
      }
    }

    @media (max-width: 760px) {
      .ledger-money-grid { grid-template-columns: 1fr; }
    }
  </style>
</head>
<body>
  <div class="shell">
    <header class="header">
      <div>
        <h1 style="margin:0;">Parent Desk</h1>
        <div>Welcome <?= h($parentProfile['name']) ?>. Selected learner: <?= h($learnerDisplayName) ?> (<?= h($linkedLearner['reg_number']) ?>)</div>
      </div>
      <div style="display:flex; gap:8px; flex-wrap:wrap;">
        <span class="chip" id="parentDeskProgressChip">Step 1 of 7</span>
        <form method="GET" style="display:flex; gap:6px; align-items:center;">
          <label for="parentLearnerSwitch" style="font-size:12px; text-transform:none; color:#fff; letter-spacing:0; font-weight:600;">Child</label>
          <select id="parentLearnerSwitch" name="learner_id" onchange="this.form.submit()" style="padding:8px;border-radius:8px;border:1px solid rgba(255,255,255,0.35);background:#fff;color:#12386d;min-width:220px;">
            <?php foreach ($linkedLearners as $learnerOption): ?>
              <option value="<?= h($learnerOption['id']) ?>" <?= (int)$learnerOption['id'] === $selectedLearnerId ? 'selected' : '' ?>>
                <?= h($learnerOption['reg_number']) ?> - <?= h($learnerOption['full_name']) ?> (<?= h($learnerOption['class_name']) ?>)
              </option>
            <?php endforeach; ?>
          </select>
        </form>
        <span class="chip"><?= h($linkedLearner['class_name']) ?></span>
        <a class="chip" href="logout.php">Logout</a>
      </div>
    </header>

    <?php foreach ($alerts as $alert): ?>
      <div class="alert <?= $alert['type'] === 'success' ? 'success' : 'error' ?>"><?= h($alert['text']) ?></div>
    <?php endforeach; ?>

    <div class="desk-layout">
      <aside class="sidebar">
        <button type="button" class="side-btn active" data-target="parentHomeView">Summary</button>
        <button type="button" class="side-btn" data-target="parentProfileView">My Profile</button>
        <button type="button" class="side-btn" data-target="parentReportCardView">Report Card</button>
        <button type="button" class="side-btn" data-target="parentAccountView">Student Account</button>
        <button type="button" class="side-btn" data-target="parentTransfersView">Transfer Requests</button>
        <button type="button" class="side-btn" data-target="parentLearningView">E-learning and Library</button>
        <button type="button" class="side-btn" data-target="parentAnnouncementsView">Announcements</button>
      </aside>

      <main class="main">
        <section id="parentProfileView" class="view">
          <section class="panel">
            <h2 style="margin:0 0 8px;">My Parent Profile</h2>
            <p class="muted">Update your contact details and change your account password.</p>

            <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(260px, 1fr)); gap:10px;">
              <article class="panel" style="margin:0;">
                <h3 style="margin:0 0 8px;">Account Details</h3>
                <form method="POST" autocomplete="off">
                  <div class="field">
                    <label for="parent_profile_name">Full Name</label>
                    <input id="parent_profile_name" name="profile_name" value="<?= h((string)$parentProfile['name']) ?>" required>
                  </div>
                  <div class="field">
                    <label for="parent_profile_email">Email Address</label>
                    <input id="parent_profile_email" type="email" name="profile_email" value="<?= h((string)$parentProfile['email']) ?>" required>
                  </div>
                  <button class="side-btn" style="margin:0; width:auto;" type="submit" name="save_parent_profile">Save Profile</button>
                </form>
              </article>

              <article class="panel" style="margin:0;">
                <h3 style="margin:0 0 8px;">Change Password</h3>
                <form method="POST" autocomplete="off">
                  <div class="field">
                    <label for="parent_current_password">Current Password</label>
                    <input id="parent_current_password" type="password" name="current_password" required>
                  </div>
                  <div class="field">
                    <label for="parent_new_password">New Password</label>
                    <input id="parent_new_password" type="password" name="new_password" minlength="10" autocomplete="new-password" required>
                  </div>
                  <div class="field">
                    <label for="parent_confirm_password">Confirm New Password</label>
                    <input id="parent_confirm_password" type="password" name="confirm_password" minlength="10" autocomplete="new-password" required>
                  </div>
                  <button class="side-btn" style="margin:0; width:auto;" type="submit" name="change_parent_password">Change Password</button>
                </form>
              </article>
            </div>
          </section>
        </section>

        <section id="parentHomeView" class="view active">
          <section class="panel">
            <h2 style="margin:0 0 8px;">Learner Profile (View Only)</h2>
            <div style="display:flex; gap:8px; flex-wrap:wrap; margin-bottom:10px;">
              <button type="button" class="side-btn" id="printFullStudentInfoBtn" style="margin:0; width:auto;">Print Full Student Information</button>
              <button type="button" class="side-btn" id="downloadFullStudentInfoBtn" style="margin:0; width:auto;">Download Full Student Information</button>
            </div>
            <div class="stats">
              <article class="stat"><small>Learner</small><strong><?= h($learnerDisplayName) ?></strong></article>
              <article class="stat"><small>Reg Number</small><strong><?= h($linkedLearner['reg_number']) ?></strong></article>
              <article class="stat"><small>Birth Certificate No.</small><strong><?= h($linkedLearner['birth_certificate_number'] ?: '-') ?></strong></article>
              <article class="stat"><small>Class</small><strong><?= h($linkedLearner['class_name']) ?></strong></article>
              <article class="stat"><small>Date of Admission</small><strong><?= h($linkedLearner['date_of_admission'] ?: '-') ?></strong></article>
              <article class="stat"><small>Date of Birth</small><strong><?= h($linkedLearner['date_of_birth_info'] ?: '-') ?></strong></article>
              <article class="stat"><small>Guardian Phone</small><strong><?= h($linkedLearner['guardian_phone'] ?: '-') ?></strong></article>
            </div>
            <p class="muted" style="margin-top:8px;">Parents Desk is view-only. Updates are managed by teacher, accountant, and admin desks.</p>
          </section>
        </section>

        <section id="parentReportCardView" class="view">
          <section class="panel">
            <h2 style="margin:0 0 8px;">Student Report Card (View Only)</h2>
            <div style="display:flex; gap:8px; margin-bottom:10px; flex-wrap:wrap; align-items:end;">
              <div class="field" style="margin:0; min-width:240px;">
                <label for="parentReportExamType">Exam Period</label>
                <select id="parentReportExamType">
                  <?php foreach ($reportCardExamOptions as $examKey => $examLabel): ?>
                    <option value="<?= h($examKey) ?>"><?= h($examLabel) ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <button class="side-btn" type="button" id="printParentReportCardBtn" style="margin:0; width:auto;">Print Report Card</button>
            </div>
            <div id="parentReportCardCanvas" style="margin-bottom:12px;"></div>
            <div class="table-wrap">
              <table>
                <thead>
                  <tr>
                    <th>Exam</th>
                    <th>Term</th>
                    <th>Subject</th>
                    <th>Score</th>
                    <th>Percent</th>
                  </tr>
                </thead>
                <tbody>
                  <?php if (empty($majorReportRows)): ?>
                    <tr><td colspan="5">No major exam results available yet.</td></tr>
                  <?php else: ?>
                    <?php foreach ($majorReportRows as $row): ?>
                      <?php $percent = (float)$row['total_max'] > 0 ? (((float)$row['total_score'] / (float)$row['total_max']) * 100) : 0; ?>
                      <tr>
                        <td><?= h($examLabels[$row['assessment_type']] ?? $row['assessment_type']) ?></td>
                        <td><?= h($row['term_name']) ?></td>
                        <td><?= h($row['subject_name']) ?></td>
                        <td><?= h(number_format((float)$row['total_score'], 1)) ?>/<?= h(number_format((float)$row['total_max'], 1)) ?></td>
                        <td><?= h(number_format($percent, 1)) ?>%</td>
                      </tr>
                    <?php endforeach; ?>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>
          </section>
        </section>

        <section id="parentAccountView" class="view">
          <section class="panel">
            <h2 style="margin:0 0 8px;">Student Account (View Only)</h2>
            <p class="muted">Ledger, financial statement, and payment receipt reports are available below.</p>
            <section class="stats" style="margin-bottom:10px;">
              <article class="stat"><small>Total Invoiced</small><strong>$<?= h(number_format($totalInvoiced, 2)) ?></strong></article>
              <article class="stat"><small>Total Paid (USD Base)</small><strong>$<?= h(number_format($totalPaid, 2)) ?></strong></article>
              <article class="stat"><small>Outstanding Balance</small><strong>$<?= h(number_format($outstandingBalance, 2)) ?></strong></article>
            </section>

            <div style="display:flex; gap:8px; margin-bottom:10px; flex-wrap:wrap; align-items:end;">
              <button class="side-btn" type="button" id="printParentLedgerBtn" style="margin:0; width:auto;">Print Student Ledger</button>
              <button class="side-btn" type="button" id="printParentFinancialStatementBtn" style="margin:0; width:auto;">Print Financial Statement</button>
              <div class="field" style="margin:0; min-width:280px;">
                <label for="parentReceiptPaymentSelect">Paid Transaction Receipt</label>
                <select id="parentReceiptPaymentSelect">
                  <option value="">Choose payment transaction</option>
                  <?php foreach ($learnerPayments as $payment): ?>
                    <option value="<?= h($payment['id']) ?>">
                      <?= h($payment['payment_date']) ?> - <?= h((string)$payment['currency_code']) ?> <?= h(number_format((float)$payment['amount_paid'], 2)) ?> (USD $<?= h(number_format((float)($payment['amount_paid_usd'] ?: $payment['amount_paid']), 2)) ?>) - <?= h(strtoupper((string)($payment['fee_component'] ?? '-'))) ?> - <?= h(strtoupper(str_replace('_', ' ', (string)$payment['payment_method']))) ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>
              <button class="side-btn" type="button" id="printParentReceiptBtn" style="margin:0; width:auto;">Print Receipt</button>
            </div>

            <h3 style="margin:8px 0;">Invoice Register</h3>
            <div class="table-wrap" style="margin-bottom:10px;">
              <table>
                <thead>
                  <tr>
                    <th>Invoice #</th>
                    <th>Description</th>
                    <th>Amount Due</th>
                    <th>GPF</th>
                    <th>SSF</th>
                    <th>SDC</th>
                    <th>Registration Fees</th>
                    <th>ZIMSEC</th>
                    <th>Paid</th>
                    <th>Outstanding</th>
                    <th>Status</th>
                  </tr>
                </thead>
                <tbody>
                  <?php if (empty($learnerInvoices)): ?>
                    <tr><td colspan="11">No invoices available.</td></tr>
                  <?php else: ?>
                    <?php foreach ($learnerInvoices as $invoice): ?>
                      <?php $outstanding = max(0, (float)$invoice['amount_due'] - (float)$invoice['paid_total']); ?>
                      <tr>
                        <td><?= h($invoice['invoice_number']) ?></td>
                        <td><?= h($invoice['description']) ?></td>
                        <td>$<?= h(number_format((float)$invoice['amount_due'], 2)) ?></td>
                        <td>$<?= h(number_format((float)($invoice['fee_gpf'] ?? 0), 2)) ?></td>
                        <td>$<?= h(number_format((float)($invoice['fee_ssf'] ?? 0), 2)) ?></td>
                        <td>$<?= h(number_format((float)($invoice['fee_sdc'] ?? 0), 2)) ?></td>
                        <td>$<?= h(number_format((float)($invoice['fee_registration'] ?? 0), 2)) ?></td>
                        <td>$<?= h(number_format((float)($invoice['fee_zimsec'] ?? 0), 2)) ?></td>
                        <td>$<?= h(number_format((float)$invoice['paid_total'], 2)) ?></td>
                        <td>$<?= h(number_format($outstanding, 2)) ?></td>
                        <td><?= h(strtoupper(str_replace('_', ' ', (string)$invoice['status']))) ?></td>
                      </tr>
                    <?php endforeach; ?>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>

            <h3 style="margin:8px 0;">Payments</h3>
            <div class="table-wrap">
              <table>
                <thead>
                  <tr>
                    <th>Date</th>
                    <th>Amount</th>
                    <th>Fee Type</th>
                    <th>Method</th>
                    <th>Reference</th>
                    <th>Invoice</th>
                  </tr>
                </thead>
                <tbody>
                  <?php if (empty($learnerPayments)): ?>
                    <tr><td colspan="6">No payments recorded yet.</td></tr>
                  <?php else: ?>
                    <?php foreach ($learnerPayments as $payment): ?>
                      <tr>
                        <td><?= h($payment['payment_date']) ?></td>
                        <td>$<?= h(number_format((float)$payment['amount_paid'], 2)) ?></td>
                        <td><?= h(strtoupper((string)($payment['fee_component'] ?? '-'))) ?></td>
                        <td><?= h(strtoupper(str_replace('_', ' ', (string)$payment['payment_method']))) ?></td>
                        <td><?= h($payment['reference_no'] ?: '-') ?></td>
                        <td><?= h($payment['invoice_number'] ?: '-') ?></td>
                      </tr>
                    <?php endforeach; ?>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>

            <h3 style="margin:8px 0;">Student Ledger (View Only)</h3>
            <div class="ledger-balance-banner">
              Total Money Owed: $<?= h(number_format($outstandingBalance, 2)) ?>
            </div>
            <div class="ledger-stream" id="parentStudentLedgerTable">
              <?php if (empty($ledgerEntries)): ?>
                <article class="ledger-row">
                  <div class="ledger-row-desc">No ledger transactions available.</div>
                </article>
              <?php else: ?>
                <?php foreach ($ledgerEntries as $entry): ?>
                  <article class="ledger-row">
                    <div class="ledger-row-head">
                      <div class="ledger-row-date"><?= h(substr((string)$entry['entry_date'], 0, 10)) ?></div>
                      <div class="ledger-row-ref">Ref: <?= h($entry['reference']) ?></div>
                    </div>
                    <div class="ledger-row-desc"><?= h($entry['description']) ?></div>
                    <div class="ledger-money-grid">
                      <div class="ledger-money-card debit">
                        <small>Debit</small>
                        <strong>$<?= h(number_format((float)$entry['debit'], 2)) ?></strong>
                      </div>
                      <div class="ledger-money-card credit">
                        <small>Credit</small>
                        <strong>$<?= h(number_format((float)$entry['credit'], 2)) ?></strong>
                      </div>
                      <div class="ledger-money-card balance">
                        <small>Balance</small>
                        <strong>$<?= h(number_format((float)$entry['balance'], 2)) ?></strong>
                      </div>
                    </div>
                  </article>
                <?php endforeach; ?>
              <?php endif; ?>
            </div>
          </section>
        </section>

        <section id="parentTransfersView" class="view">
          <section class="panel">
            <h2 style="margin:0 0 8px;">Learner Transfer Request</h2>
            <p class="muted">Submit a transfer request for admin processing. Clearance is requested from teacher and accountant before final letter generation.</p>

            <form method="POST" style="display:grid; gap:8px; margin-bottom:14px;">
              <div class="field" style="margin:0;">
                <label for="destination_school">Destination School</label>
                <input id="destination_school" name="destination_school" placeholder="School learner is transferring to" required>
              </div>
              <div class="field" style="margin:0;">
                <label for="transfer_reason">Reason for Transfer</label>
                <textarea id="transfer_reason" name="transfer_reason" required placeholder="Provide transfer reason"></textarea>
              </div>
              <button class="side-btn" type="submit" name="submit_transfer_request" style="margin:0; width:auto;">Submit Transfer Request</button>
            </form>

            <h3 style="margin:10px 0 8px;">Transfer Request History</h3>
            <div class="table-wrap">
              <table>
                <thead>
                  <tr>
                    <th>Requested</th>
                    <th>Destination</th>
                    <th>Reason</th>
                    <th>Teacher</th>
                    <th>Accountant</th>
                    <th>Overall Status</th>
                    <th>Letter</th>
                  </tr>
                </thead>
                <tbody>
                  <?php if (empty($parentTransferRequests)): ?>
                    <tr><td colspan="7">No transfer requests submitted for this learner yet.</td></tr>
                  <?php else: ?>
                    <?php foreach ($parentTransferRequests as $transfer): ?>
                      <tr>
                        <td><?= h($transfer['requested_at']) ?></td>
                        <td><?= h($transfer['destination_school']) ?></td>
                        <td><?= h($transfer['reason']) ?></td>
                        <td>
                          <?= h(ucfirst((string)$transfer['teacher_status'])) ?>
                          <?php if (!empty($transfer['teacher_comment'])): ?><br><small><?= h($transfer['teacher_comment']) ?></small><?php endif; ?>
                        </td>
                        <td>
                          <?= h(ucfirst((string)$transfer['accountant_status'])) ?>
                          <?php if (!empty($transfer['accountant_comment'])): ?><br><small><?= h($transfer['accountant_comment']) ?></small><?php endif; ?>
                        </td>
                        <td>
                          <?= h(ucfirst(str_replace('_', ' ', (string)$transfer['status']))) ?>
                          <?php if (!empty($transfer['admin_comment'])): ?><br><small><?= h($transfer['admin_comment']) ?></small><?php endif; ?>
                        </td>
                        <td>
                          <?php if (!empty($transfer['letter_html'])): ?>
                            <button type="button" class="side-btn parent-transfer-letter-btn" style="margin:0; width:auto;" data-letter='<?= h($transfer['letter_html']) ?>'>View / Print</button>
                          <?php else: ?>
                            <span class="muted">Letter not available yet.</span>
                          <?php endif; ?>
                        </td>
                      </tr>
                    <?php endforeach; ?>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>
          </section>
        </section>

        <section id="parentLearningView" class="view">
          <section class="panel">
            <h2 style="margin:0 0 8px;">E-learning Overview (View Only)</h2>
            <?php if (empty($elearningItems)): ?>
              <p class="muted">No e-learning items available for this class yet.</p>
            <?php else: ?>
              <?php foreach ($elearningItems as $item): ?>
                <article class="item">
                  <h3><?= h($item['title']) ?></h3>
                  <div class="muted" style="margin-bottom:6px;">
                    <span class="badge"><?= h(ucfirst((string)$item['content_type'])) ?></span>
                    <span style="margin-left:8px;">Teacher: <?= h($item['teacher_name']) ?></span>
                    <span style="margin-left:8px;">Subject: <?= h($item['subject_name'] ?: 'General') ?></span>
                  </div>
                  <?php if (!empty($item['instructions'])): ?><div class="muted" style="margin-bottom:6px;"><?= nl2br(h($item['instructions'])) ?></div><?php endif; ?>
                  <div class="muted">Submission Status: <span class="badge"><?= h(ucfirst((string)($item['submission_status'] ?: 'not submitted'))) ?></span></div>
                  <?php if ($item['score'] !== null): ?><div class="muted">Score: <strong><?= h($item['score']) ?></strong></div><?php endif; ?>
                  <?php if (!empty($item['teacher_comment'])): ?><div class="muted">Teacher Comment: <?= h($item['teacher_comment']) ?></div><?php endif; ?>
                </article>
              <?php endforeach; ?>
            <?php endif; ?>

            <h2 style="margin:14px 0 8px;">E-Library Resources (View Only)</h2>
            <div class="table-wrap">
              <table>
                <thead>
                  <tr>
                    <th>Uploaded</th>
                    <th>Title</th>
                    <th>Subject</th>
                    <th>Teacher</th>
                    <th>Type</th>
                    <th>File</th>
                  </tr>
                </thead>
                <tbody>
                  <?php if (empty($libraryItems)): ?>
                    <tr><td colspan="6">No e-library resources for this class yet.</td></tr>
                  <?php else: ?>
                    <?php foreach ($libraryItems as $resource): ?>
                      <tr>
                        <td><?= h($resource['created_at']) ?></td>
                        <td>
                          <strong><?= h($resource['title']) ?></strong>
                          <?php if (!empty($resource['description'])): ?><br><small><?= h($resource['description']) ?></small><?php endif; ?>
                        </td>
                        <td><?= h($resource['subject_name'] ?: 'General') ?></td>
                        <td><?= h($resource['teacher_name']) ?></td>
                        <td><?= h($resource['document_type']) ?></td>
                        <td><a href="<?= h($resource['file_path']) ?>" target="_blank" rel="noopener"><?= h($resource['original_name']) ?></a></td>
                      </tr>
                    <?php endforeach; ?>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>
          </section>
        </section>

        <section id="parentAnnouncementsView" class="view">
          <section class="panel">
            <h2 style="margin:0 0 8px;">Announcements for Parents</h2>
            <p class="muted">Only published and admin-approved parent announcements appear here.</p>
            <?php if (empty($parentAnnouncements)): ?>
              <p class="muted">No parent announcements posted yet.</p>
            <?php else: ?>
              <?php foreach ($parentAnnouncements as $announcement): ?>
                <article class="item">
                  <h3><?= h($announcement['title']) ?></h3>
                  <div class="muted" style="margin-bottom:6px;">
                    <span class="badge">From: <?= h(ucfirst((string)$announcement['sender_role'])) ?> - <?= h($announcement['sender_name']) ?></span>
                    <span style="margin-left:8px;">Posted: <?= h($announcement['published_at'] ?: $announcement['created_at']) ?></span>
                  </div>
                  <div class="muted"><?= nl2br(h($announcement['body'])) ?></div>
                </article>
              <?php endforeach; ?>
            <?php endif; ?>
          </section>
        </section>
      </main>
    </div>
  </div>

  <script>
    const parentReportMeta = <?= json_encode($reportMeta, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
    const parentReportPalette = {
      ink: String(parentReportMeta?.palette?.ink || '#173122'),
      muted: String(parentReportMeta?.palette?.muted || '#4F6656'),
      brandNavy: String(parentReportMeta?.palette?.brand_navy || '#2E8B45'),
      brandNavyDeep: String(parentReportMeta?.palette?.brand_navy_deep || '#1D6A33'),
      brandIce: String(parentReportMeta?.palette?.brand_ice || '#EEF7EF'),
      line: String(parentReportMeta?.palette?.patch_sky_soft || '#D6EEFF')
    };
    const parentSelectedLearner = <?= json_encode([
      'name' => $learnerDisplayName,
      'reg_number' => $linkedLearner['reg_number'],
      'birth_certificate_number' => $linkedLearner['birth_certificate_number'] ?? '-',
      'class_name' => $linkedLearner['class_name'],
      'date_of_admission' => $linkedLearner['date_of_admission'] ?? '-',
      'date_of_birth_info' => $linkedLearner['date_of_birth_info'] ?? '-',
      'gender' => $linkedLearner['gender'] ?? '-',
      'guardian_name' => $linkedLearner['guardian_name'] ?? '-',
      'guardian_phone' => $linkedLearner['guardian_phone'] ?? '-',
      'guardian_address' => $linkedLearner['guardian_address'] ?? '-'
    ], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
    const parentReportCardMeta = {
      schoolName: parentReportMeta.school_name,
      schoolAddress: parentReportMeta.school_address,
      learnerName: parentSelectedLearner.name,
      logoDataUri: <?= json_encode($schoolLogoDataUri, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>,
      logoPath: <?= json_encode($schoolLogoPath, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>,
      regNumber: parentSelectedLearner.reg_number,
      birthCertificateNo: parentSelectedLearner.birth_certificate_number || '',
      className: parentSelectedLearner.class_name,
      gender: parentSelectedLearner.gender || '',
      admissionDate: parentSelectedLearner.date_of_admission || '',
      dateOfBirth: parentSelectedLearner.date_of_birth_info || '',
      learnerPhotoPath: <?= json_encode($learnerPhotoExists ? $learnerPhotoPath : '', JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>,
      learnerInitials: <?= json_encode($learnerInitials, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>
    };
    const parentMajorReportRows = <?= json_encode($majorReportRows, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
    const parentInvoices = <?= json_encode($learnerInvoices, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
    const parentPayments = <?= json_encode($learnerPayments, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
    const parentElearningItems = <?= json_encode($elearningItems, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
    const parentLibraryItems = <?= json_encode($libraryItems, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
    const parentLedgerData = <?= json_encode($ledgerEntries, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
    const parentReportCardDataset = <?= json_encode($reportCardDataset, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
    const parentStatementTotals = {
      totalInvoiced: <?= json_encode(round($totalInvoiced, 2), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>,
      totalPaid: <?= json_encode(round($totalPaid, 2), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>,
      outstanding: <?= json_encode(round($outstandingBalance, 2), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>
    };

    const parentNavBtns = Array.from(document.querySelectorAll('.side-btn'));
    const parentViews = Array.from(document.querySelectorAll('.view'));
    const parentDeskProgressChip = document.getElementById('parentDeskProgressChip');
    const printFullStudentInfoBtn = document.getElementById('printFullStudentInfoBtn');
    const downloadFullStudentInfoBtn = document.getElementById('downloadFullStudentInfoBtn');
    const parentReportExamType = document.getElementById('parentReportExamType');
    const parentReportCardCanvas = document.getElementById('parentReportCardCanvas');
    const printParentReportCardBtn = document.getElementById('printParentReportCardBtn');
    const printParentLedgerBtn = document.getElementById('printParentLedgerBtn');
    const printParentFinancialStatementBtn = document.getElementById('printParentFinancialStatementBtn');
    const parentReceiptPaymentSelect = document.getElementById('parentReceiptPaymentSelect');
    const printParentReceiptBtn = document.getElementById('printParentReceiptBtn');
    const parentTransferLetterBtns = Array.from(document.querySelectorAll('.parent-transfer-letter-btn'));

    function escapeHtml(value) {
      return String(value ?? '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
    }

    function formatMoney(value) {
      const num = Number(value || 0);
      return '$' + num.toFixed(2);
    }

    function buildSimpleRows(rows, mapFn) {
      if (!rows.length) {
        return '<tr><td colspan="8">No records found.</td></tr>';
      }
      return rows.map(mapFn).join('');
    }

    function buildFullStudentInformationHtml(modeLabel) {
      const learner = parentSelectedLearner;
      const generatedAt = new Date().toLocaleString();

      const majorRowsHtml = buildSimpleRows(parentMajorReportRows, row => {
        const totalScore = Number(row.total_score || 0);
        const totalMax = Number(row.total_max || 0);
        const percent = totalMax > 0 ? ((totalScore / totalMax) * 100).toFixed(1) + '%' : '0.0%';
        return `<tr>
          <td>${escapeHtml(row.assessment_type)}</td>
          <td>${escapeHtml(row.term_name)}</td>
          <td>${escapeHtml(row.subject_name)}</td>
          <td>${escapeHtml(totalScore.toFixed(1))}/${escapeHtml(totalMax.toFixed(1))}</td>
          <td>${escapeHtml(percent)}</td>
        </tr>`;
      });

      const invoiceRowsHtml = buildSimpleRows(parentInvoices, row => {
        const amountDue = Number(row.amount_due || 0);
        const paidTotal = Number(row.paid_total || 0);
        const outstanding = Math.max(0, amountDue - paidTotal);
        const gpf = Number(row.fee_gpf || 0);
        const ssf = Number(row.fee_ssf || 0);
        const sdc = Number(row.fee_sdc || 0);
        const registration = Number(row.fee_registration || 0);
        const zimsec = Number(row.fee_zimsec || 0);
        return `<tr>
          <td>${escapeHtml(row.invoice_number)}</td>
          <td>${escapeHtml(row.description)}</td>
          <td>${escapeHtml(formatMoney(amountDue))}</td>
          <td>${escapeHtml(formatMoney(gpf))}</td>
          <td>${escapeHtml(formatMoney(ssf))}</td>
          <td>${escapeHtml(formatMoney(sdc))}</td>
          <td>${escapeHtml(formatMoney(registration))}</td>
          <td>${escapeHtml(formatMoney(zimsec))}</td>
          <td>${escapeHtml(formatMoney(paidTotal))}</td>
          <td>${escapeHtml(formatMoney(outstanding))}</td>
          <td>${escapeHtml(row.status)}</td>
        </tr>`;
      });

      const paymentRowsHtml = buildSimpleRows(parentPayments, row => {
        return `<tr>
          <td>${escapeHtml(row.payment_date)}</td>
          <td>${escapeHtml(formatMoney(row.amount_paid || 0))}</td>
          <td>${escapeHtml(String(row.fee_component || '-').toUpperCase())}</td>
          <td>${escapeHtml(row.payment_method)}</td>
          <td>${escapeHtml(row.reference_no || '-')}</td>
          <td>${escapeHtml(row.invoice_number || '-')}</td>
        </tr>`;
      });

      const elearningRowsHtml = buildSimpleRows(parentElearningItems, row => {
        return `<tr>
          <td>${escapeHtml(row.title)}</td>
          <td>${escapeHtml(row.content_type)}</td>
          <td>${escapeHtml(row.subject_name || 'General')}</td>
          <td>${escapeHtml(row.teacher_name)}</td>
          <td>${escapeHtml(row.submission_status || 'not submitted')}</td>
          <td>${escapeHtml(row.score ?? '-')}</td>
          <td>${escapeHtml(row.teacher_comment || '-')}</td>
        </tr>`;
      });

      const libraryRowsHtml = buildSimpleRows(parentLibraryItems, row => {
        return `<tr>
          <td>${escapeHtml(row.created_at)}</td>
          <td>${escapeHtml(row.title)}</td>
          <td>${escapeHtml(row.subject_name || 'General')}</td>
          <td>${escapeHtml(row.teacher_name)}</td>
          <td>${escapeHtml(row.document_type)}</td>
          <td>${escapeHtml(row.original_name)}</td>
        </tr>`;
      });

      return `
      <html>
      <head>
        <title>${escapeHtml(parentReportMeta.school_name)} - Full Student Information</title>
        <style>
          body { font-family: Arial, sans-serif; color: ${parentReportPalette.ink}; padding: 18px; }
          h1 { margin: 0 0 6px; color: ${parentReportPalette.brandNavyDeep}; }
          h2 { margin: 18px 0 8px; color: ${parentReportPalette.brandNavy}; }
          .meta { margin-bottom: 10px; font-size: 12px; }
          .profile { border: 1px solid ${parentReportPalette.line}; border-radius: 8px; padding: 10px; background: ${parentReportPalette.brandIce}; }
          .profile-row { margin-bottom: 4px; font-size: 13px; }
          table { width: 100%; border-collapse: collapse; font-size: 12px; margin-top: 6px; }
          th, td { border: 1px solid ${parentReportPalette.line}; padding: 7px; text-align: left; vertical-align: top; }
          th { background: ${parentReportPalette.brandIce}; color: ${parentReportPalette.brandNavyDeep}; }
        </style>
      </head>
      <body>
        <h1>${escapeHtml(parentReportMeta.school_name)}</h1>
        <div class="meta">${escapeHtml(parentReportMeta.school_address)} | ${escapeHtml(parentReportMeta.school_contact)}</div>
        <div class="meta">Report: ${escapeHtml(modeLabel)} | Prepared By: ${escapeHtml(parentReportMeta.prepared_by)} | Generated: ${escapeHtml(generatedAt)}</div>

        <h2>Learner Profile</h2>
        <div class="profile">
          <div class="profile-row"><strong>Name:</strong> ${escapeHtml(learner.name)}</div>
          <div class="profile-row"><strong>Reg Number:</strong> ${escapeHtml(learner.reg_number)}</div>
          <div class="profile-row"><strong>Birth Certificate No.:</strong> ${escapeHtml(learner.birth_certificate_number)}</div>
          <div class="profile-row"><strong>Class:</strong> ${escapeHtml(learner.class_name)}</div>
          <div class="profile-row"><strong>Date of Admission:</strong> ${escapeHtml(learner.date_of_admission)}</div>
          <div class="profile-row"><strong>Date of Birth:</strong> ${escapeHtml(learner.date_of_birth_info)}</div>
          <div class="profile-row"><strong>Gender:</strong> ${escapeHtml(learner.gender)}</div>
          <div class="profile-row"><strong>Guardian Name:</strong> ${escapeHtml(learner.guardian_name)}</div>
          <div class="profile-row"><strong>Guardian Phone:</strong> ${escapeHtml(learner.guardian_phone)}</div>
          <div class="profile-row"><strong>Guardian Address:</strong> ${escapeHtml(learner.guardian_address)}</div>
        </div>

        <h2>Major Exam Report Summary</h2>
        <table>
          <thead><tr><th>Assessment</th><th>Term</th><th>Subject</th><th>Score</th><th>Percent</th></tr></thead>
          <tbody>${majorRowsHtml}</tbody>
        </table>

        <h2>Invoice Register</h2>
        <table>
          <thead><tr><th>Invoice #</th><th>Description</th><th>Amount Due</th><th>GPF</th><th>SSF</th><th>SDC</th><th>Registration Fees</th><th>ZIMSEC</th><th>Paid</th><th>Outstanding</th><th>Status</th></tr></thead>
          <tbody>${invoiceRowsHtml}</tbody>
        </table>

        <h2>Payments</h2>
        <table>
          <thead><tr><th>Date</th><th>Amount</th><th>Fee Type</th><th>Method</th><th>Reference</th><th>Invoice</th></tr></thead>
          <tbody>${paymentRowsHtml}</tbody>
        </table>

        <h2>E-learning Overview</h2>
        <table>
          <thead><tr><th>Title</th><th>Type</th><th>Subject</th><th>Teacher</th><th>Submission</th><th>Score</th><th>Comment</th></tr></thead>
          <tbody>${elearningRowsHtml}</tbody>
        </table>

        <h2>E-Library Resources</h2>
        <table>
          <thead><tr><th>Uploaded</th><th>Title</th><th>Subject</th><th>Teacher</th><th>Type</th><th>File</th></tr></thead>
          <tbody>${libraryRowsHtml}</tbody>
        </table>
      </body>
      </html>`;
    }

    function printFullStudentInformation() {
      const reportWindow = window.open('', '_blank');
      if (!reportWindow) {
        window.alert('Popup blocked. Please allow popups and try again.');
        return;
      }
      reportWindow.document.write(buildFullStudentInformationHtml('Full Student Information Report'));
      reportWindow.document.close();
      reportWindow.focus();
      reportWindow.print();
    }

    function downloadFullStudentInformation() {
      const html = buildFullStudentInformationHtml('Full Student Information Download');
      const blob = new Blob([html], { type: 'text/html;charset=utf-8' });
      const url = URL.createObjectURL(blob);
      const anchor = document.createElement('a');
      anchor.href = url;
      anchor.download = (String(parentSelectedLearner.reg_number || 'student_report') + '_full_information_report.html').replace(/\s+/g, '_');
      document.body.appendChild(anchor);
      anchor.click();
      anchor.remove();
      URL.revokeObjectURL(url);
    }

    function rcEscape(value) {
      return String(value ?? '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
    }

    function buildParentReportCardMarkup(examData) {
      const rowsHtml = (examData.subject_rows || []).length > 0
        ? examData.subject_rows.map(row => `
            <tr>
              <td>${rcEscape(String(row.subject || '').toUpperCase())}</td>
              <td>${rcEscape(row.obtained)}</td>
              <td>${rcEscape(row.total)}</td>
              <td>${rcEscape(row.percent)}%</td>
              <td>${rcEscape(row.grade)}</td>
              <td>${rcEscape(row.status)}</td>
              <td></td>
            </tr>
          `).join('')
        : '<tr><td colspan="7">No marks have been recorded for this examination.</td></tr>';

      const photoHtml = parentReportCardMeta.learnerPhotoPath
        ? `<img src="${rcEscape(parentReportCardMeta.learnerPhotoPath)}" alt="Learner photo" style="width:56px;height:56px;border-radius:50%;object-fit:cover;border:1px solid #8c8c8c;">`
        : `<div style="width:56px;height:56px;border-radius:50%;display:flex;align-items:center;justify-content:center;border:1px solid #8c8c8c;background:#efefef;font-weight:700;font-size:11px;">${rcEscape(parentReportCardMeta.learnerInitials)}</div>`;
      const logoSrc = parentReportCardMeta.logoDataUri && parentReportCardMeta.logoDataUri !== ''
        ? parentReportCardMeta.logoDataUri
        : parentReportCardMeta.logoPath;

      return `
        <article class="report-card-sheet" style="font-family:Arial,sans-serif;background:#fff;border:1px solid ${parentReportPalette.line};border-radius:16px;padding:8mm;max-width:190mm;width:100%;margin:0 auto;color:${parentReportPalette.ink};">
          <div style="text-align:center;">
            <div style="margin-bottom:2px;"><img src="${rcEscape(logoSrc)}" alt="School logo" style="width:22mm;height:22mm;object-fit:contain;"></div>
            <div style="font-weight:700;font-size:19px;color:${parentReportPalette.brandNavyDeep};">${rcEscape(parentReportCardMeta.schoolName)}</div>
            <div style="font-size:11px;color:${parentReportPalette.muted};">${rcEscape(parentReportMeta.school_motto || 'Education for Self Reliance')}</div>
            <div style="font-size:11px;color:${parentReportPalette.muted};">Zimbabwe</div>
            <div style="font-weight:700;font-size:16px;margin-top:3px;">Student Report Card</div>
          </div>

          <div style="border:1px solid ${parentReportPalette.line};border-radius:12px;margin-top:8px;overflow:hidden;">
            <div style="display:grid;grid-template-columns:64px 1fr 1fr 1fr;gap:8px;padding:8px;font-size:11px;align-items:center;">
              <div style="display:flex;justify-content:center;">${photoHtml}</div>
              <div>
                <div><strong>REGISTRATION</strong> ${rcEscape(parentReportCardMeta.regNumber)}</div>
                <div><strong>NAME</strong> ${rcEscape(parentReportCardMeta.learnerName)}</div>
                <div><strong>CLASS</strong> ${rcEscape(parentReportCardMeta.className)}</div>
              </div>
              <div>
                <div><strong>DATE OF BIRTH</strong> ${rcEscape(parentReportCardMeta.dateOfBirth || 'N/A')}</div>
                <div><strong>BIRTH CERTIFICATE NO</strong> ${rcEscape(parentReportCardMeta.birthCertificateNo || 'N/A')}</div>
                <div><strong>GENDER</strong> ${rcEscape(parentReportCardMeta.gender || '-')}</div>
                <div><strong>ADMISSION DATE</strong> ${rcEscape(parentReportCardMeta.admissionDate || '-')}</div>
              </div>
              <div>
                <div><strong>EXAM</strong> ${rcEscape(examData.exam_label || '-')}</div>
                <div><strong>ATTENDANCE</strong> 0%</div>
                <div><strong>ABSENTS</strong> 0</div>
              </div>
            </div>
          </div>

          <div style="border:1px solid ${parentReportPalette.line};border-radius:12px;margin-top:8px;overflow:hidden;">
            <div style="background:${parentReportPalette.brandIce};border-bottom:1px solid ${parentReportPalette.line};font-size:11px;font-weight:700;padding:4px 6px;color:${parentReportPalette.brandNavyDeep};">COGNITIVE DOMAIN - ${rcEscape(String(examData.exam_label || '').toUpperCase())}</div>
            <table style="width:100%;border-collapse:collapse;font-size:11px;">
              <thead>
                <tr>
                  <th style="border:1px solid ${parentReportPalette.line};padding:4px 6px;text-align:left;">ASSESSMENTS / SUBJECT</th>
                  <th style="border:1px solid ${parentReportPalette.line};padding:4px 6px;text-align:left;">OBTAINED</th>
                  <th style="border:1px solid ${parentReportPalette.line};padding:4px 6px;text-align:left;">TOTAL</th>
                  <th style="border:1px solid ${parentReportPalette.line};padding:4px 6px;text-align:left;">%</th>
                  <th style="border:1px solid ${parentReportPalette.line};padding:4px 6px;text-align:left;">GRADE</th>
                  <th style="border:1px solid ${parentReportPalette.line};padding:4px 6px;text-align:left;">STATUS</th>
                  <th style="border:1px solid ${parentReportPalette.line};padding:4px 6px;text-align:left;">TEACHER'S COMMENT</th>
                </tr>
              </thead>
              <tbody>${rowsHtml}</tbody>
            </table>

            <table style="width:100%;border-collapse:collapse;font-size:11px;">
              <tbody>
                <tr>
                  <td style="border:1px solid ${parentReportPalette.line};padding:4px 6px;"><strong>TOTAL MARKS</strong><br>${rcEscape(examData.total_obtained)}</td>
                  <td style="border:1px solid ${parentReportPalette.line};padding:4px 6px;"><strong>TOTAL SCORE</strong><br>${rcEscape(examData.total_obtained)} / ${rcEscape(examData.total_possible)}</td>
                  <td style="border:1px solid ${parentReportPalette.line};padding:4px 6px;"><strong>PERCENTAGE</strong><br>${rcEscape(examData.overall_percent)}%</td>
                  <td style="border:1px solid ${parentReportPalette.line};padding:4px 6px;"><strong>GRADE</strong><br>${rcEscape(examData.overall_grade)}</td>
                  <td style="border:1px solid ${parentReportPalette.line};padding:4px 6px;"><strong>STATUS</strong><br>${rcEscape(examData.overall_status)}</td>
                </tr>
              </tbody>
            </table>

            <table style="width:100%;border-collapse:collapse;font-size:10px;">
              <tbody>
                <tr>
                  <td style="border:1px solid ${parentReportPalette.line};padding:4px 6px;">COMPARISON WITH CLASS</td>
                  <td style="border:1px solid ${parentReportPalette.line};padding:4px 6px;">CLASS STRENGTH<br><strong>${rcEscape(examData.class_strength)} STUDENTS</strong></td>
                  <td style="border:1px solid ${parentReportPalette.line};padding:4px 6px;">CLASS AVERAGE<br><strong>${rcEscape(examData.class_average)}%</strong></td>
                  <td style="border:1px solid ${parentReportPalette.line};padding:4px 6px;">CLASS MAX AVERAGE<br><strong>${rcEscape(examData.class_max)}%</strong></td>
                  <td style="border:1px solid ${parentReportPalette.line};padding:4px 6px;">CLASS MIN AVERAGE<br><strong>${rcEscape(examData.class_min)}%</strong></td>
                  <td style="border:1px solid ${parentReportPalette.line};padding:4px 6px;">STUDENT POSITION<br><strong>${rcEscape(examData.position)}</strong></td>
                </tr>
              </tbody>
            </table>
          </div>

          <div style="border:1px solid ${parentReportPalette.line};border-radius:12px;margin-top:8px;padding:6px;">
            <div style="font-size:11px;font-weight:700;margin-bottom:4px;">CLASS TEACHER'S OVERALL OBSERVATION</div>
            <div style="border-bottom:1px solid #bbb;height:16px;"></div>
            <div style="border-bottom:1px solid #bbb;height:16px;"></div>
            <div style="border-bottom:1px solid #bbb;height:16px;"></div>
          </div>

          <div style="border:1px solid ${parentReportPalette.line};border-radius:12px;margin-top:8px;padding:6px;">
            <div style="font-size:11px;font-weight:700;margin-bottom:4px;">HEAD TEACHER'S / PRINCIPAL'S COMMENT</div>
            <div style="border-bottom:1px solid #bbb;height:16px;"></div>
            <div style="border-bottom:1px solid #bbb;height:16px;"></div>
            <div style="border-bottom:1px solid #bbb;height:16px;"></div>
          </div>

          <div style="border:1px solid ${parentReportPalette.line};border-radius:12px;margin-top:8px;overflow:hidden;">
            <div style="font-size:11px;font-weight:700;padding:4px 6px;border-bottom:1px solid ${parentReportPalette.line};background:${parentReportPalette.brandIce};color:${parentReportPalette.brandNavyDeep};">NEXT TERM INFORMATION</div>
            <div style="font-size:11px;padding:4px 6px;"><strong>Next Term Opens:</strong> __ / __ / ____ &nbsp;&nbsp; <strong>Promotion Status:</strong> PROMOTED / REPEAT &nbsp;&nbsp; <strong>Next Class:</strong> __________</div>
          </div>

          <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:8px;text-align:center;font-size:10px;margin-top:12px;">
            <div style="border-top:1px solid #777;padding-top:3px;">DATE</div>
            <div style="border-top:1px solid #777;padding-top:3px;">SIGNATURE</div>
            <div style="border-top:1px solid #777;padding-top:3px;">STAMP</div>
            <div style="border-top:1px solid #777;padding-top:3px;">${rcEscape(examData.exam_label || '')}</div>
          </div>
        </article>
      `;
    }

    function renderParentReportCard() {
      if (!parentReportCardCanvas) {
        return;
      }

      const examKey = String(parentReportExamType?.value || 'end_of_term_exam_term1');
      const examData = parentReportCardDataset[examKey] || null;
      if (!examData) {
        parentReportCardCanvas.innerHTML = '<p class="muted">Report card data not available.</p>';
        return;
      }

      parentReportCardCanvas.innerHTML = buildParentReportCardMarkup(examData);
    }

    function buildParentPrintDoc(title, bodyHtml) {
      return `
        <html>
          <head>
            <title>${rcEscape(parentReportMeta.school_name)} - ${rcEscape(title)}</title>
            <style>
              @page { size: A4 portrait; margin: 10mm; }
              body {
                font-family: 'Segoe UI', Arial, sans-serif;
                margin: 0;
                padding: 0;
                color: ${parentReportPalette.ink};
                background: linear-gradient(180deg, #f8fafc 0%, #ffffff 100%);
              }
              .page-frame {
                position: fixed;
                inset: 2mm;
                border: 0.8px solid ${parentReportPalette.line};
                border-radius: 8px;
                pointer-events: none;
                z-index: 0;
              }
              .sheet {
                max-width: 190mm;
                margin: 0 auto;
                border: 1px solid ${parentReportPalette.line};
                border-radius: 12px;
                padding: 8mm;
                background: #fff;
                box-shadow: 0 10px 24px rgba(15, 23, 42, 0.08);
                position: relative;
                z-index: 1;
              }
              .head { text-align:center; margin-bottom:10px; position: relative; padding-top: 6px; }
              .head::before {
                content: '';
                display: block;
                height: 4px;
                border-radius: 999px;
                margin-bottom: 8px;
                background: linear-gradient(90deg, ${parentReportPalette.brandNavyDeep}, #d1a95a 50%, ${parentReportPalette.brandNavyDeep});
              }
              .head h1 { margin:3px 0; font-size:19px; color:${parentReportPalette.brandNavyDeep}; }
              .head .sub { font-size:11px; color:${parentReportPalette.muted}; margin:0; }
              .meta { display:grid; grid-template-columns: repeat(2, minmax(0,1fr)); gap:6px; margin:8px 0; font-size:12px; }
              table { width:100%; border-collapse: collapse; font-size:12px; margin-top:8px; }
              th, td { border:1px solid ${parentReportPalette.line}; padding:6px; text-align:left; }
              th { background:${parentReportPalette.brandIce}; color:${parentReportPalette.brandNavyDeep}; }
              .right { text-align:right; }
              .section-title {
                margin: 10px 0 6px;
                font-family: Georgia, 'Times New Roman', serif;
                color: ${parentReportPalette.brandNavyDeep};
                font-size: 16px;
                letter-spacing: 0.3px;
              }
              .debt-banner {
                margin: 4px 0 10px;
                padding: 9px 11px;
                border-radius: 10px;
                border: 1px solid #fecaca;
                background: linear-gradient(120deg, #fff1f2 0%, #ffe4e6 100%);
                color: #991b1b;
                font-size: 14px;
                font-weight: 900;
              }
              .ledger-grid { display: grid; gap: 8px; }
              .ledger-item {
                border: 1px solid ${parentReportPalette.line};
                border-radius: 10px;
                padding: 8px;
                background: linear-gradient(145deg, #ffffff 0%, #f8fbff 100%);
              }
              .ledger-head {
                display: flex;
                justify-content: space-between;
                align-items: center;
                gap: 8px;
                margin-bottom: 5px;
              }
              .ledger-date { font-weight: 800; color: ${parentReportPalette.brandNavyDeep}; }
              .ledger-ref {
                border: 1px solid #bfdbfe;
                background: #eff6ff;
                color: #1d4ed8;
                border-radius: 999px;
                font-size: 10px;
                padding: 2px 7px;
                font-weight: 700;
              }
              .ledger-desc { font-size: 12px; color: #334155; margin-bottom: 6px; }
              .ledger-money {
                display: grid;
                grid-template-columns: repeat(3, minmax(0, 1fr));
                gap: 6px;
              }
              .ledger-money div {
                border: 1px solid #e2e8f0;
                border-radius: 8px;
                padding: 5px;
                background: #fff;
              }
              .ledger-money small {
                display: block;
                color: #64748b;
                font-size: 9px;
                text-transform: uppercase;
                letter-spacing: 0.3px;
              }
              .ledger-money strong { font-size: 11px; }
              .ledger-money .debit strong { color: #b45309; }
              .ledger-money .credit strong { color: #065f46; }
              .ledger-money .balance strong { color: #991b1b; font-weight: 900; }
            </style>
          </head>
          <body>
            <div class="page-frame"></div>
            <article class="sheet">
              <div class="head">
                <h1>${rcEscape(parentReportMeta.school_name)}</h1>
                <p class="sub">${rcEscape(parentReportMeta.school_address)}</p>
                <p class="sub"><strong>${rcEscape(title)}</strong></p>
              </div>
              ${bodyHtml}
            </article>
            <script>window.onload = function(){ window.print(); }<\/script>
          </body>
        </html>
      `;
    }

    function printParentReportCard() {
      const examKey = String(parentReportExamType?.value || 'end_of_term_exam_term1');
      const examData = parentReportCardDataset[examKey] || null;
      if (!examData) {
        window.alert('No report card data available for selected exam.');
        return;
      }

      const bodyHtml = buildParentReportCardMarkup(examData);
      const win = window.open('', '_blank');
      if (!win) {
        window.alert('Popup blocked. Please allow popups and try again.');
        return;
      }

      win.document.write(`
        <html>
          <head>
            <title>${rcEscape(parentReportCardMeta.schoolName)} - ${rcEscape(examData.exam_label)}</title>
            <style>
              @page { size: A4 portrait; margin: 8mm; }
              body { font-family: Arial, sans-serif; margin: 0; padding: 0; background: #fff; color: ${parentReportPalette.ink}; }
              .page-frame {
                position: fixed;
                inset: 2mm;
                border: 0.8px solid ${parentReportPalette.line};
                border-radius: 8px;
                pointer-events: none;
                z-index: 0;
              }
              .report-card-sheet { page-break-inside: avoid; }
              @media print {
                body { padding: 0; }
                .report-card-sheet {
                  width: 194mm !important;
                  max-width: 194mm !important;
                  border-radius: 0 !important;
                  margin: 0 auto !important;
                }
              }
            </style>
          </head>
          <body>
            <div class="page-frame"></div>
            ${bodyHtml}
            <script>window.onload = function(){ window.print(); }<\/script>
          </body>
        </html>
      `);
      win.document.close();
    }

    function printParentStudentLedger() {
      const rowsHtml = parentLedgerData.length > 0
        ? parentLedgerData.map(entry => `
            <article class="ledger-item">
              <div class="ledger-head">
                <div class="ledger-date">${rcEscape(String(entry.entry_date || '').slice(0, 10))}</div>
                <div class="ledger-ref">Ref: ${rcEscape(entry.reference || '-')}</div>
              </div>
              <div class="ledger-desc">${rcEscape(entry.description || '')}</div>
              <div class="ledger-money">
                <div class="debit"><small>Debit</small><strong>$${Number(entry.debit || 0).toFixed(2)}</strong></div>
                <div class="credit"><small>Credit</small><strong>$${Number(entry.credit || 0).toFixed(2)}</strong></div>
                <div class="balance"><small>Balance</small><strong>$${Number(entry.balance || 0).toFixed(2)}</strong></div>
              </div>
            </article>
          `).join('')
        : '<article class="ledger-item"><div class="ledger-desc">No ledger transactions available.</div></article>';

      const bodyHtml = `
        <div class="meta">
          <div><strong>Learner:</strong> ${rcEscape(parentSelectedLearner.name)}</div>
          <div><strong>Reg Number:</strong> ${rcEscape(parentSelectedLearner.reg_number)}</div>
          <div><strong>Birth Certificate No.:</strong> ${rcEscape(parentSelectedLearner.birth_certificate_number || '-')}</div>
          <div><strong>Class:</strong> ${rcEscape(parentSelectedLearner.class_name)}</div>
          <div><strong>Generated:</strong> ${rcEscape(new Date().toLocaleString())}</div>
        </div>
        <div class="section-title">Student Ledger</div>
        <div class="debt-banner">
          Total Money Owed: $${Number(parentStatementTotals.outstanding || 0).toFixed(2)}
        </div>
        <div class="ledger-grid">${rowsHtml}</div>
      `;

      const win = window.open('', '_blank');
      if (!win) {
        window.alert('Popup blocked. Please allow popups and try again.');
        return;
      }
      win.document.write(buildParentPrintDoc('Student Ledger', bodyHtml));
      win.document.close();
    }

    function printParentFinancialStatement() {
      const bodyHtml = `
        <div class="meta">
          <div><strong>Learner:</strong> ${rcEscape(parentSelectedLearner.name)}</div>
          <div><strong>Reg Number:</strong> ${rcEscape(parentSelectedLearner.reg_number)}</div>
          <div><strong>Birth Certificate No.:</strong> ${rcEscape(parentSelectedLearner.birth_certificate_number || '-')}</div>
          <div><strong>Class:</strong> ${rcEscape(parentSelectedLearner.class_name)}</div>
          <div><strong>Statement Date:</strong> ${rcEscape(new Date().toLocaleDateString())}</div>
        </div>
        <table>
          <tbody>
            <tr><th>Total Invoiced</th><td class="right">$${Number(parentStatementTotals.totalInvoiced || 0).toFixed(2)}</td></tr>
            <tr><th>Total Paid (USD Base)</th><td class="right">$${Number(parentStatementTotals.totalPaid || 0).toFixed(2)}</td></tr>
            <tr><th>Outstanding Balance</th><td class="right">$${Number(parentStatementTotals.outstanding || 0).toFixed(2)}</td></tr>
          </tbody>
        </table>
      `;

      const win = window.open('', '_blank');
      if (!win) {
        window.alert('Popup blocked. Please allow popups and try again.');
        return;
      }
      win.document.write(buildParentPrintDoc('Student Financial Statement', bodyHtml));
      win.document.close();
    }

    function printParentReceipt() {
      const paymentId = Number(parentReceiptPaymentSelect?.value || 0);
      if (paymentId <= 0) {
        window.alert('Choose a paid transaction first.');
        return;
      }

      const payment = parentPayments.find(row => Number(row.id || 0) === paymentId);
      if (!payment) {
        window.alert('Selected payment transaction not found.');
        return;
      }

      const bodyHtml = `
        <div class="meta">
          <div><strong>Learner:</strong> ${rcEscape(parentSelectedLearner.name)}</div>
          <div><strong>Reg Number:</strong> ${rcEscape(parentSelectedLearner.reg_number)}</div>
          <div><strong>Birth Certificate No.:</strong> ${rcEscape(parentSelectedLearner.birth_certificate_number || '-')}</div>
          <div><strong>Class:</strong> ${rcEscape(parentSelectedLearner.class_name)}</div>
          <div><strong>Receipt Date:</strong> ${rcEscape(String(payment.payment_date || '').slice(0, 10))}</div>
        </div>
        <div class="section-title">Payment Receipt</div>
        <div class="ledger-grid">
          <article class="ledger-item">
            <div class="ledger-head">
              <div class="ledger-date">Receipt # ${rcEscape(payment.reference_no || '-')}</div>
              <div class="ledger-ref">Invoice: ${rcEscape(payment.invoice_number || '-')}</div>
            </div>
            <div class="ledger-money">
              <div class="debit"><small>Amount (Original)</small><strong>${rcEscape(String(payment.currency_code || 'USD'))} ${Number(payment.amount_paid || 0).toFixed(2)}</strong></div>
              <div class="credit"><small>Rate to USD</small><strong>${Number(payment.fx_rate_to_usd || 1).toFixed(8)}</strong></div>
              <div class="balance"><small>Amount (USD)</small><strong>$${Number(payment.amount_paid_usd || payment.amount_paid || 0).toFixed(2)}</strong></div>
            </div>
          </article>
          <article class="ledger-item">
            <div class="ledger-desc"><strong>Fee Type:</strong> ${rcEscape(String(payment.fee_component || '-').toUpperCase())}</div>
            <div class="ledger-desc"><strong>Payment Method:</strong> ${rcEscape(String(payment.payment_method || '').toUpperCase().replace(/_/g, ' '))}</div>
            <div class="ledger-desc"><strong>Receipt Number:</strong> ${rcEscape(payment.reference_no || '-')}</div>
            <div class="ledger-desc"><strong>Note:</strong> ${rcEscape(payment.note || '-')}</div>
          </article>
        </div>
      `;

      const win = window.open('', '_blank');
      if (!win) {
        window.alert('Popup blocked. Please allow popups and try again.');
        return;
      }
      win.document.write(buildParentPrintDoc('Student Payment Receipt', bodyHtml));
      win.document.close();
    }

    function openParentView(viewId) {
      // Explicitly remove active class from ALL views
      parentViews.forEach(view => {
        view.classList.remove('active');
      });
      
      // Explicitly add active class to target view
      if (viewId) {
        const targetView = document.getElementById(viewId);
        if (targetView) {
          targetView.classList.add('active');
        }
      }
      
      // Explicitly remove active class from ALL buttons
      parentNavBtns.forEach(btn => {
        btn.classList.remove('active');
      });
      
      // Explicitly add active class to matching button
      if (viewId) {
        const matchingBtn = parentNavBtns.find(btn => btn.dataset.target === viewId);
        if (matchingBtn) {
          matchingBtn.classList.add('active');
        }
      }

      const activeIndex = parentNavBtns.findIndex(btn => btn.classList.contains('active'));
      if (parentDeskProgressChip && activeIndex >= 0) {
        const activeBtn = parentNavBtns[activeIndex] || null;
        const activeLabel = String(activeBtn?.childNodes?.[0]?.textContent || activeBtn?.textContent || 'Current Section').trim().replace(/\s+/g, ' ');
        parentDeskProgressChip.textContent = `Step ${activeIndex + 1} of ${parentNavBtns.length} | ${activeLabel}`;
      }
    }

    parentNavBtns.forEach(btn => {
      btn.addEventListener('click', function () {
        const target = this.dataset.target || '';
        if (target !== '') {
          openParentView(target);
        }
      });
    });

    parentTransferLetterBtns.forEach(btn => {
      btn.addEventListener('click', function () {
        const letterHtml = this.getAttribute('data-letter') || '';
        if (letterHtml.trim() === '') {
          window.alert('Transfer letter is not available yet.');
          return;
        }
        const win = window.open('', '_blank');
        if (!win) {
          window.alert('Popup blocked. Please allow popups and try again.');
          return;
        }
        win.document.write(`
          <html>
            <head>
              <title>${rcEscape(parentReportMeta.school_name)} - Transfer Letter</title>
              <style>
                body { font-family: Arial, sans-serif; margin: 18px; color: ${parentReportPalette.ink}; }
              </style>
            </head>
            <body>${letterHtml}</body>
          </html>
        `);
        win.document.close();
        win.focus();
        win.print();
      });
    });

    if (printFullStudentInfoBtn) {
      printFullStudentInfoBtn.addEventListener('click', printFullStudentInformation);
    }

    if (downloadFullStudentInfoBtn) {
      downloadFullStudentInfoBtn.addEventListener('click', downloadFullStudentInformation);
    }

    if (parentReportExamType) {
      parentReportExamType.addEventListener('change', renderParentReportCard);
    }

    if (printParentReportCardBtn) {
      printParentReportCardBtn.addEventListener('click', printParentReportCard);
    }

    if (printParentLedgerBtn) {
      printParentLedgerBtn.addEventListener('click', printParentStudentLedger);
    }

    if (printParentFinancialStatementBtn) {
      printParentFinancialStatementBtn.addEventListener('click', printParentFinancialStatement);
    }

    if (printParentReceiptBtn) {
      printParentReceiptBtn.addEventListener('click', printParentReceipt);
    }

    renderParentReportCard();

    openParentView('parentHomeView');
  </script>
  <?php output_auto_capitalize_script(); ?>
  <?php output_select_search_script(); ?>
  <footer style="text-align:center;padding:14px 0 10px;font-size:0.8rem;color:#8a9ab0;opacity:0.7;">Developed by Ngwenya Jonas &copy; 2026</footer>
</body>
</html>
