<?php
// /elms/student/profile.php
declare(strict_types=1);

$PAGE_TITLE = 'My Profile';
$ACTIVE = 'profile';
$EMBEDDED_PROFILE = isset($_GET['embedded']);

require_once __DIR__ . '/../includes/student_auth.php';

$mysqli = $mysqli ?? ($conn ?? null);

if (!$mysqli instanceof mysqli) {
    http_response_code(500);
    exit('DB connection failed');
}

$mysqli->set_charset('utf8mb4');

if (!function_exists('table_exists')) {
    function table_exists(mysqli $db, string $table): bool {
        $table = $db->real_escape_string($table);
        $q = $db->query("SHOW TABLES LIKE '{$table}'");
        return $q && $q->num_rows > 0;
    }
}

if (!function_exists('col_exists')) {
    function col_exists(mysqli $db, string $table, string $col): bool {
        $table = $db->real_escape_string($table);
        $col = $db->real_escape_string($col);
        $q = $db->query("SHOW COLUMNS FROM `{$table}` LIKE '{$col}'");
        return $q && $q->num_rows > 0;
    }
}

if (!function_exists('flash')) {
    function flash(string $key, ?string $value = null) {
        if ($value === null) {
            $msg = $_SESSION['flash'][$key] ?? null;
            unset($_SESSION['flash'][$key]);
            return $msg;
        }

        $_SESSION['flash'][$key] = $value;
        return null;
    }
}

if (!function_exists('fmt_value')) {
    function fmt_value($value): string {
        $value = trim((string)$value);
        return $value !== '' ? $value : '—';
    }
}

if (!function_exists('h')) {
    function h($value): string {
        return htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

$student_id = (int)($GLOBALS['STUDENT_ID'] ?? ($_SESSION['student_id'] ?? 0));

if (!table_exists($mysqli, 'studentss')) {
    http_response_code(500);
    exit('studentss table not found');
}

/*
|--------------------------------------------------------------------------
| Student Details
|--------------------------------------------------------------------------
*/

$select = ['id'];
$possibleCols = [
    'full_name',
    'academic_email',
    'center_reg_no',
    'reference_no',
    'mobile',
    'gender',
    'nic',
    'nic_passport',
'photograph',
'address1',
'address2',
    'nic_no',
    'national_id',
    'address',
    'dob',
    'date_of_birth',
    'lms_status',
    'status',
    'course_id',
    'created_at',

    'photo',
    'photograph',
    'profile_photo',
    'image',
    'profile_image',
    'avatar'
];

foreach ($possibleCols as $col) {
    if (col_exists($mysqli, 'studentss', $col)) {
        $select[] = $col;
    }
}

$sql = "SELECT " . implode(', ', array_map(fn($c) => "`$c`", $select)) . " FROM studentss WHERE id=? LIMIT 1";

$st = $mysqli->prepare($sql);
$st->bind_param('i', $student_id);
$st->execute();
$student = $st->get_result()->fetch_assoc();
$st->close();

if (!$student) {
    session_destroy();
    header('Location: /elms/student/login.php');
    exit;
}

$_SESSION['student_name']   = $student['full_name'] ?? ($_SESSION['student_name'] ?? 'Student');
$_SESSION['academic_email'] = $student['academic_email'] ?? ($_SESSION['academic_email'] ?? '');
$_SESSION['center_reg_no']  = $student['center_reg_no'] ?? ($_SESSION['center_reg_no'] ?? '');

$GLOBALS['STUDENT_NAME'] = $_SESSION['student_name'];
$GLOBALS['STUDENT_EMAIL'] = $_SESSION['academic_email'];
$GLOBALS['STUDENT_REG_NO'] = $_SESSION['center_reg_no'];

$lms_status = strtolower(trim((string)($student['lms_status'] ?? 'active')));

if (in_array($lms_status, ['inactive', 'suspended'], true)) {
    session_destroy();
    header('Location: /elms/student/login.php');
    exit;
}

/*
|--------------------------------------------------------------------------
| Update Profile
|--------------------------------------------------------------------------
*/

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'profile') {
        $updates = [];
        $types = '';
        $params = [];

        if (col_exists($mysqli, 'studentss', 'mobile')) {
            $mobile = trim((string)($_POST['mobile'] ?? ''));
            $updates[] = 'mobile=?';
            $types .= 's';
            $params[] = $mobile;
        }

        if (col_exists($mysqli, 'studentss', 'address')) {
            $address = trim((string)($_POST['address'] ?? ''));
            $updates[] = 'address=?';
            $types .= 's';
            $params[] = $address;
        }

        if ($updates) {
            $params[] = $student_id;
            $types .= 'i';

            $stmt = $mysqli->prepare("UPDATE studentss SET " . implode(', ', $updates) . " WHERE id=? LIMIT 1");
            $stmt->bind_param($types, ...$params);

            if ($stmt->execute()) {
                flash('ok', 'Profile updated successfully.');
            } else {
                flash('err', 'Profile update failed.');
            }

            $stmt->close();
        } else {
            flash('err', 'No editable profile columns found.');
        }

        header('Location: /elms/student/profile.php');
        exit;
    }

    if ($action === 'password') {
        $current = (string)($_POST['current_password'] ?? '');
        $new = (string)($_POST['new_password'] ?? '');
        $confirm = (string)($_POST['confirm_password'] ?? '');

        if ($new === '' || strlen($new) < 6) {
            flash('err', 'New password must be at least 6 characters.');
            header('Location: /elms/student/profile.php');
            exit;
        }

        if ($new !== $confirm) {
            flash('err', 'Confirm password does not match.');
            header('Location: /elms/student/profile.php');
            exit;
        }

        $passwordOk = true;

        $hashCol = col_exists($mysqli, 'studentss', 'academic_password_hash') ? 'academic_password_hash' : null;
        $plainCol = col_exists($mysqli, 'studentss', 'academic_plain_password') ? 'academic_plain_password' : null;

        if ($hashCol || $plainCol) {
            $passwordOk = false;

            $currentHash = $hashCol ? trim((string)($student[$hashCol] ?? '')) : '';
            $currentPlain = $plainCol ? trim((string)($student[$plainCol] ?? '')) : '';

            if ($currentHash !== '') {
                $info = password_get_info($currentHash);

                if (($info['algoName'] ?? 'unknown') !== 'unknown') {
                    $passwordOk = password_verify($current, $currentHash);
                } else {
                    $passwordOk = hash_equals($currentHash, $current);
                }
            }

            if (!$passwordOk && $currentPlain !== '') {
                $passwordOk = hash_equals($currentPlain, $current);
            }
        }

        if (!$passwordOk) {
            flash('err', 'Current password is incorrect.');
            header('Location: /elms/student/profile.php');
            exit;
        }

        $updates = [];
        $types = '';
        $params = [];

        if (col_exists($mysqli, 'studentss', 'academic_password_hash')) {
            $updates[] = 'academic_password_hash=?';
            $types .= 's';
            $params[] = password_hash($new, PASSWORD_DEFAULT);
        }

        if (col_exists($mysqli, 'studentss', 'academic_plain_password')) {
            $updates[] = 'academic_plain_password=?';
            $types .= 's';
            $params[] = $new;
        }

        if (!$updates) {
            flash('err', 'Password columns not found.');
            header('Location: /elms/student/profile.php');
            exit;
        }

        $params[] = $student_id;
        $types .= 'i';

        $stmt = $mysqli->prepare("UPDATE studentss SET " . implode(', ', $updates) . " WHERE id=? LIMIT 1");
        $stmt->bind_param($types, ...$params);

        if ($stmt->execute()) {
            flash('ok', 'Password changed successfully.');
        } else {
            flash('err', 'Password change failed.');
        }

        $stmt->close();

        header('Location: /elms/student/profile.php');
        exit;
    }
}

/*
|--------------------------------------------------------------------------
| Course / Batch Details
|--------------------------------------------------------------------------
*/

$courses = [];
$batches = [];
$courseDetails = [];
$seen = [];

$courseNameCol = 'course_name';
if (table_exists($mysqli, 'courses')) {
    if (!col_exists($mysqli, 'courses', 'course_name')) {
        $courseNameCol = col_exists($mysqli, 'courses', 'name') ? 'name' : (col_exists($mysqli, 'courses', 'title') ? 'title' : 'id');
    }
}

$batchNameCol = 'batch_name';
if (table_exists($mysqli, 'batches')) {
    $batchNameCol = col_exists($mysqli, 'batches', 'batch_name') ? 'batch_name' : (col_exists($mysqli, 'batches', 'name') ? 'name' : (col_exists($mysqli, 'batches', 'batch_code') ? 'batch_code' : 'id'));
}

/*
|--------------------------------------------------------------------------
| Source 1: student_numbers table
|--------------------------------------------------------------------------
*/
if (table_exists($mysqli, 'student_numbers')) {
    $sql = "
        SELECT
            sn.course_id,
            sn.batch_id,
            sn.reference_no,
            sn.center_no,
            c.`{$courseNameCol}` AS course_name,
            b.`{$batchNameCol}` AS batch_name,
            " . (col_exists($mysqli, 'batches', 'batch_code') ? "b.batch_code" : "'' AS batch_code") . "
        FROM student_numbers sn
        LEFT JOIN courses c ON c.id = sn.course_id
        LEFT JOIN batches b ON b.id = sn.batch_id
        WHERE sn.student_id = ?
        ORDER BY sn.id ASC
    ";

    $st = $mysqli->prepare($sql);
    if ($st) {
        $st->bind_param('i', $student_id);
        $st->execute();
        $rs = $st->get_result();

        while ($row = $rs->fetch_assoc()) {
            $cid = (int)($row['course_id'] ?? 0);
            $bid = (int)($row['batch_id'] ?? 0);

            if ($cid <= 0 && $bid <= 0) {
                continue;
            }

            $key = $cid . '-' . $bid;
            if (isset($seen[$key])) {
                continue;
            }
            $seen[$key] = true;

            $courseName = trim((string)($row['course_name'] ?? ''));
            if ($courseName === '') {
                $courseName = $cid > 0 ? ('Course #' . $cid) : 'Course';
            }

            $batchName = trim((string)($row['batch_name'] ?? ''));
            $batchCode = trim((string)($row['batch_code'] ?? ''));

            if ($batchName === '') {
                $batchName = $batchCode !== '' ? $batchCode : ($bid > 0 ? ('Batch #' . $bid) : '—');
            }

            $ref = trim((string)($row['reference_no'] ?? ''));

            $courseDetails[] = [
                'course_id'    => $cid,
                'course_name'  => $courseName,
                'batch_id'     => $bid,
                'batch_name'   => $batchName,
                'batch_code'   => $batchCode,
                'reference_no' => $ref !== '' ? $ref : 'Not Assigned',
            ];

            if ($cid > 0) {
                $courses[$cid] = $courseName;
            }

            $batches[] = $batchName;
        }

        $st->close();
    }
}

/*
|--------------------------------------------------------------------------
| Source 2: enrollments table fallback
|--------------------------------------------------------------------------
*/
if (table_exists($mysqli, 'enrollments') && table_exists($mysqli, 'batches') && table_exists($mysqli, 'courses')) {
    $sql = "
        SELECT
            b.id AS batch_id,
            b.course_id,
            c.`{$courseNameCol}` AS course_name,
            b.`{$batchNameCol}` AS batch_name,
            " . (col_exists($mysqli, 'batches', 'batch_code') ? "b.batch_code" : "'' AS batch_code") . "
        FROM enrollments e
        INNER JOIN batches b ON b.id = e.batch_id
        LEFT JOIN courses c ON c.id = b.course_id
        WHERE e.student_id = ?
        ORDER BY b.id ASC
    ";

    $st = $mysqli->prepare($sql);
    if ($st) {
        $st->bind_param('i', $student_id);
        $st->execute();
        $rs = $st->get_result();

        while ($row = $rs->fetch_assoc()) {
            $cid = (int)($row['course_id'] ?? 0);
            $bid = (int)($row['batch_id'] ?? 0);

            if ($cid <= 0 || $bid <= 0) {
                continue;
            }

            $key = $cid . '-' . $bid;
            if (isset($seen[$key])) {
                continue;
            }
            $seen[$key] = true;

            $courseName = trim((string)($row['course_name'] ?? ''));
            if ($courseName === '') {
                $courseName = 'Course #' . $cid;
            }

            $batchName = trim((string)($row['batch_name'] ?? ''));
            $batchCode = trim((string)($row['batch_code'] ?? ''));

            if ($batchName === '') {
                $batchName = $batchCode !== '' ? $batchCode : ('Batch #' . $bid);
            }

            $courseDetails[] = [
                'course_id'    => $cid,
                'course_name'  => $courseName,
                'batch_id'     => $bid,
                'batch_name'   => $batchName,
                'batch_code'   => $batchCode,
                'reference_no' => 'Not Assigned',
            ];

            $courses[$cid] = $courseName;
            $batches[] = $batchName;
        }

        $st->close();
    }
}

/*
|--------------------------------------------------------------------------
| Assign course-wise refs from student_numbers reference_no / reference_no2
|--------------------------------------------------------------------------
*/

$studentNumberRefs = [];

if (table_exists($mysqli, 'student_numbers')) {
    $snCols = ['reference_no'];

    if (col_exists($mysqli, 'student_numbers', 'reference_no2')) {
        $snCols[] = 'reference_no2';
    }

    $snSelect = implode(', ', array_map(fn($c) => "`$c`", $snCols));

    $st = $mysqli->prepare("
        SELECT {$snSelect}
        FROM student_numbers
        WHERE student_id = ?
        ORDER BY id DESC
        LIMIT 1
    ");

    if ($st) {
        $st->bind_param('i', $student_id);
        $st->execute();
        $sn = $st->get_result()->fetch_assoc();
        $st->close();

        if ($sn) {
            foreach ($snCols as $col) {
                $ref = trim((string)($sn[$col] ?? ''));
                if ($ref !== '') {
                    $studentNumberRefs[] = $ref;
                }
            }
        }
    }
}

if ($studentNumberRefs && $courseDetails) {
    foreach ($courseDetails as $i => $cd) {
        if (
            empty($courseDetails[$i]['reference_no']) ||
            $courseDetails[$i]['reference_no'] === 'Not Assigned' ||
            $courseDetails[$i]['reference_no'] === '—'
        ) {
            $courseDetails[$i]['reference_no'] = $studentNumberRefs[$i] ?? 'Not Assigned';
        }
    }
}

$duePayments = [];
$paymentRows = [];

if (table_exists($mysqli, 'payment_schedule') && table_exists($mysqli, 'student_fee_plans')) {
    $sql = "
        SELECT
            sfp.id AS plan_id,
            MIN(ps.due_date) AS due_date,
            sfp.total_payable_lkr AS amount_due_lkr,
            COALESCE((
                SELECT SUM(p.amount)
                FROM payments p
                WHERE p.student_id = sfp.student_id
                  AND (
                        p.plan_id = sfp.id
                     OR (p.plan_id IS NULL AND p.course_id = sfp.course_id)
                     OR (p.plan_id = 0 AND p.course_id = sfp.course_id)
                  )
            ), 0) AS paid_lkr,
            COALESCE(NULLIF(c.code, ''), NULLIF(c.course_name, ''), CONCAT('Course #', sfp.course_id)) AS course_code
        FROM student_fee_plans sfp
        LEFT JOIN payment_schedule ps
            ON ps.plan_id = sfp.id
           AND ps.student_id = sfp.student_id
        LEFT JOIN courses c
            ON c.id = sfp.course_id
        WHERE sfp.student_id = ?
        GROUP BY sfp.id, sfp.student_id, sfp.course_id, sfp.total_payable_lkr, c.code, c.course_name
        HAVING amount_due_lkr > paid_lkr
        ORDER BY due_date ASC, sfp.id ASC
    ";

    $st = $mysqli->prepare($sql);
    if ($st) {
        $st->bind_param('i', $student_id);
        $st->execute();
        $duePayments = $st->get_result()->fetch_all(MYSQLI_ASSOC);
        $st->close();
    }
}

if (table_exists($mysqli, 'payments')) {
    $sql = "
        SELECT
            p.id,
            p.date_paid,
            p.amount,
            COALESCE(NULLIF(c.code, ''), NULLIF(c.course_name, ''), '—') AS course_code
        FROM payments p
        LEFT JOIN courses c ON c.id = p.course_id
        WHERE p.student_id = ?
        ORDER BY p.date_paid DESC, p.id DESC
        LIMIT 30
    ";

    $st = $mysqli->prepare($sql);
    if ($st) {
        $st->bind_param('i', $student_id);
        $st->execute();
        $paymentRows = $st->get_result()->fetch_all(MYSQLI_ASSOC);
        $st->close();
    }
}

if (table_exists($mysqli, 'payments')) {
    $sql = "
        SELECT
            p.id,
            p.date_paid,
            p.amount,
            COALESCE(NULLIF(c.code, ''), NULLIF(c.course_name, ''), '—') AS course_code
        FROM payments p
        LEFT JOIN courses c ON c.id = p.course_id
        WHERE p.student_id = ?
        ORDER BY p.date_paid DESC, p.id DESC
        LIMIT 30
    ";

    $st = $mysqli->prepare($sql);
    if ($st) {
        $st->bind_param('i', $student_id);
        $st->execute();
        $paymentRows = $st->get_result()->fetch_all(MYSQLI_ASSOC);
        $st->close();
    }
}

$statusText = fmt_value($student['lms_status'] ?? ($student['status'] ?? 'Active'));
$statusLower = strtolower((string)$statusText);

$studentNic =
    trim((string)($student['nic'] ?? '')) ?:
    trim((string)($student['nic_passport'] ?? '')) ?:
    trim((string)($student['nic_no'] ?? '')) ?:
    trim((string)($student['national_id'] ?? ''));
$studentPhoto =
    trim((string)($student['photograph'] ?? '')) ?:
    trim((string)($student['profile_photo'] ?? '')) ?:
    trim((string)($student['photo'] ?? '')) ?:
    trim((string)($student['image'] ?? ''));

if ($studentPhoto !== '') {
    if (!preg_match('~^https?://~i', $studentPhoto) && !str_starts_with($studentPhoto, '/')) {
        $studentPhoto = '/edenrms/uploads/' . $studentPhoto;
    }
}

$statusBadge = match ($statusLower) {
    'active' => 'success',
    'pending' => 'warning',
    'inactive', 'suspended' => 'secondary',
    default => 'primary',
};

if (!$EMBEDDED_PROFILE) {
    require_once __DIR__ . '/../includes/student_layout_top.php';
} else {
    ?>
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>My Profile</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    </head>
    <body style="background:#f7f8fb;">
    <?php
}
?>

<style>
    .profile-modal-wrap {
    max-width: 980px;
    margin: 0 auto;
}

body:has(.profile-modal-wrap) .student-page-head {
    display: none;
}
.student-page-head {
    display: none !important;
}

    .profile-modal-card {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 26px;
        box-shadow: 0 24px 70px rgba(15,23,42,.16);
        overflow: hidden;
    }

    .profile-modal-head {
        padding: 28px 32px;
        border-bottom: 1px solid #e5e7eb;
        background:
            radial-gradient(circle at top right, rgba(37,99,235,.14), transparent 28%),
            linear-gradient(180deg, #ffffff, #fafbff);
    }

    .profile-avatar-big {
        width: 96px;
        height: 96px;
        border-radius: 50%;
        background: #0f172a;
        color: #fff;
        display: grid;
        place-items: center;
        font-size: 2.2rem;
        font-weight: 950;
        flex: 0 0 auto;
    }

    .profile-name-main {
        margin: 0;
        color: #12386f;
        font-size: 1.75rem;
        font-weight: 950;
        letter-spacing: -.4px;
        line-height: 1.2;
    }

    .profile-role-main {
        color: #7b8190;
        font-size: 1rem;
        font-weight: 750;
        margin-top: 4px;
    }

    .profile-pill-row {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-top: 12px;
    }

    .profile-id-pill {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 7px 11px;
        border-radius: 999px;
        background: #eff6ff;
        color: #034ea2;
        font-size: .76rem;
        font-weight: 850;
    }

    .profile-status-pill {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 7px 11px;
        border-radius: 999px;
        font-size: .76rem;
        font-weight: 850;
    }

    .profile-tabs-line {
        display: flex;
        align-items: center;
        gap: 26px;
        padding: 0 32px;
        border-bottom: 1px solid #e5e7eb;
        background: #fff;
        overflow-x: auto;
    }

    .profile-tabs-line button {
    border: 0;
    background: transparent;
    color: #8a8f98;
    font-weight: 900;
    padding: 16px 0 14px;
    position: relative;
    white-space: nowrap;
}

.profile-tabs-line button.active {
    color: #034ea2;
}

.profile-tabs-line button.active::after {
    content: "";
    position: absolute;
    left: 0;
    right: 0;
    bottom: -1px;
    height: 3px;
    border-radius: 99px;
    background: #2563eb;
}

.profile-tab-panel {
    display: none;
}

.profile-tab-panel.active {
    display: block;
}

.profile-modal-wrap {
    max-width: 980px;
    margin: 0 auto;
}

.profile-modal-card {
    max-height: calc(100vh - 150px);
    overflow: hidden !important;
    display: flex;
    flex-direction: column;
}

.profile-modal-body {
    overflow-y: auto;
}

    .profile-modal-body {
        padding: 28px 32px 32px;
    }

    .profile-content-grid {
        display: grid;
        grid-template-columns: minmax(0, 1.05fr) minmax(360px, .7fr);
        gap: 24px;
        align-items: start;
    }

    .profile-section-card {
        border: 1px solid #e5e7eb;
        border-radius: 18px;
        background: #fff;
        overflow: hidden;
        margin-bottom: 22px;
    }

    .profile-section-head {
        padding: 18px 20px;
        border-bottom: 1px solid #e5e7eb;
        background: #fafbff;
    }

    .profile-section-title {
        margin: 0;
        color: #12386f;
        font-weight: 950;
        font-size: 1.05rem;
    }

    .profile-section-sub {
        color: #7b8190;
        font-size: .82rem;
        font-weight: 650;
        margin-top: 4px;
    }

    .profile-section-body {
        padding: 18px 20px;
    }

    .profile-info-row {
        display: grid;
        grid-template-columns: 170px minmax(0, 1fr);
        gap: 14px;
        padding: 13px 0;
        border-bottom: 1px solid #eef2f7;
        align-items: center;
    }

    .profile-info-row:last-child {
        border-bottom: 0;
    }

    .profile-info-label {
        color: #7b8190;
        font-size: .72rem;
        text-transform: uppercase;
        font-weight: 900;
        letter-spacing: .04em;
    }

    .profile-info-value {
        color: #263247;
        font-weight: 800;
        word-break: break-word;
    }

    .profile-course-list {
        display: grid;
        gap: 12px;
    }

    .profile-course-item {
        border: 1px solid #e5e7eb;
        background: #fff;
        border-radius: 16px;
        padding: 15px;
    }

    .profile-course-name {
        color: #263247;
        font-weight: 900;
        line-height: 1.35;
        margin-bottom: 9px;
    }

    .profile-course-meta {
        display: flex;
        flex-wrap: wrap;
        gap: 7px;
    }

    .course-meta-pill {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 6px 9px;
        border-radius: 999px;
        background: #f8fafc;
        color: #526071;
        border: 1px solid #e5e7eb;
        font-size: .73rem;
        font-weight: 800;
    }

    .course-ref-pill {
        background: #eff6ff;
        color: #034ea2;
        border-color: #bfdbfe;
    }

    .profile-password-card {
        border: 1px solid #e5e7eb;
        border-radius: 18px;
        background: #fff;
        overflow: hidden;
    }

    @media (max-width: 1050px) {
        .profile-content-grid {
            grid-template-columns: 1fr;
        }
    }

    @media (max-width: 576px) {
        .profile-modal-head,
        .profile-modal-body {
            padding: 20px;
        }

        .profile-tabs-line {
            padding: 0 20px;
        }

        .profile-avatar-big {
            width: 74px;
            height: 74px;
            font-size: 1.7rem;
        }

        .profile-name-main {
            font-size: 1.35rem;
        }

        .profile-info-row {
            grid-template-columns: 1fr;
            gap: 4px;
        }
    }
    .profile-modal-card {
    overflow: visible !important;
}

.profile-tabs-line {
    overflow-x: auto;
    overflow-y: hidden;
    scrollbar-width: none;
}

.profile-tabs-line::-webkit-scrollbar {
    display: none;
}

<?php if ($EMBEDDED_PROFILE): ?>

    html,
    body {
        background: #fff !important;
        overflow: hidden;
    }

    .profile-modal-wrap {
        max-width: 100% !important;
        margin: 0 !important;
        padding: 0 !important;
    }

    .profile-modal-card {
        border: 0 !important;
        border-radius: 0 !important;
        box-shadow: none !important;
        max-height: none !important;
        height: 100vh;
        overflow: hidden !important;
    }

    .profile-modal-head {
        border-radius: 0 !important;
    }

    .profile-modal-body {
        height: calc(100vh - 220px);
        overflow-y: auto;
    }
    .pay-dash-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 14px;
}

.pay-dash-card {
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 18px;
    padding: 16px;
    display: flex;
    align-items: center;
    gap: 13px;
    box-shadow: 0 8px 22px rgba(15,23,42,.04);
}

.pay-dash-icon {
    width: 42px;
    height: 42px;
    border-radius: 14px;
    background: #eff6ff;
    color: #034ea2;
    display: grid;
    place-items: center;
    font-size: 1.1rem;
    flex: 0 0 auto;
}

.pay-dash-value {
    font-size: 1.05rem;
    font-weight: 950;
    color: #111827;
    line-height: 1.2;
}

.pay-dash-label {
    font-size: .76rem;
    color: #7b8190;
    font-weight: 850;
    margin-top: 3px;
}

.pay-card-list {
    display: grid;
    gap: 10px;
}

.pay-item-card {
    border: 1px solid #e5e7eb;
    border-radius: 16px;
    padding: 14px 15px;
    background: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 14px;
}

.pay-item-title {
    color: #12386f;
    font-weight: 950;
    line-height: 1.25;
}

.pay-item-sub {
    color: #7b8190;
    font-size: .78rem;
    font-weight: 750;
    margin-top: 4px;
}

.pay-balance {
    color: #dc2626;
    font-weight: 950;
    white-space: nowrap;
}

.pay-paid {
    color: #15803d;
    font-weight: 950;
    white-space: nowrap;
}

.pay-empty {
    border: 1px dashed #cbd5e1;
    border-radius: 16px;
    padding: 24px;
    text-align: center;
    color: #7b8190;
}

.pay-empty i {
    display: block;
    font-size: 2rem;
    color: #cbd5e1;
    margin-bottom: 8px;
}

@media (max-width: 768px) {
    .pay-dash-grid {
        grid-template-columns: 1fr;
    }

    .pay-item-card {
        align-items: flex-start;
        flex-direction: column;
    }

    .pay-item-card .text-end {
        text-align: left !important;
    }
}
.profile-pay-table thead th {
    background: #f8fafc;
    color: #475569;
    font-size: 12px;
    font-weight: 950;
    text-transform: uppercase;
    letter-spacing: .05em;
    padding: 13px 14px;
    border-bottom: 1px solid #e5e7eb;
}

.profile-pay-table tbody td {
    padding: 14px;
    border-bottom: 1px solid #eef2f7;
    font-weight: 750;
    color: #263247;
}

.profile-pay-table tbody tr:last-child td {
    border-bottom: 0;
}

<?php endif; ?>
</style>

<div class="profile-modal-wrap">

    <?php if ($msg = flash('ok')): ?>
        <div class="alert alert-success rounded-4 border-0 shadow-sm">
            <i class="bi bi-check-circle me-1"></i>
            <?= h($msg) ?>
        </div>
    <?php endif; ?>

    <?php if ($msg = flash('err')): ?>
        <div class="alert alert-danger rounded-4 border-0 shadow-sm">
            <i class="bi bi-exclamation-triangle me-1"></i>
            <?= h($msg) ?>
        </div>
    <?php endif; ?>

    <div class="profile-modal-card">
        <div class="profile-modal-head">
            <div class="d-flex flex-column flex-lg-row justify-content-between align-items-lg-center gap-4">
                <div class="d-flex align-items-center gap-4">
                    <div class="profile-avatar-big">
    <?php if ($studentPhoto !== ''): ?>
        <img src="<?= h($studentPhoto) ?>"
             alt="Profile Photo"
             style="width:100%;height:100%;object-fit:cover;border-radius:50%;"
             onerror="this.style.display='none';this.parentNode.innerHTML='<?= h(strtoupper(substr((string)($_SESSION['student_name'] ?? 'S'), 0, 1))) ?>';">
    <?php else: ?>
        <?= h(strtoupper(substr((string)($_SESSION['student_name'] ?? 'S'), 0, 1))) ?>
    <?php endif; ?>
</div>

                    <div>
                        <h1 class="profile-name-main">
                            <?= h($_SESSION['student_name'] ?? 'Student') ?>
                        </h1>

                        <div class="profile-role-main">Student</div>

                        <div class="profile-pill-row">
                            <span class="profile-id-pill">
                                <i class="bi bi-person-badge"></i>
                                <?= h($student['center_reg_no'] ?? '—') ?>
                            </span>


                            <span class="profile-status-pill bg-<?= h($statusBadge) ?> text-white">
                                <i class="bi bi-check2-circle"></i>
                                <?= h($statusText) ?>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="profile-tabs-line">
    <button type="button" class="profile-tab-btn active" data-profile-tab="basic">Basic Info</button>
    <button type="button" class="profile-tab-btn" data-profile-tab="courses">Courses</button>
    <button type="button" class="profile-tab-btn" data-profile-tab="payments">Payments</button>
    <button type="button" class="profile-tab-btn" data-profile-tab="security">Security</button>
</div>

        <div class="profile-modal-body">

    <div class="profile-tab-panel active" data-profile-panel="basic">
        <div class="profile-section-card mb-0" id="basicInfo">
            <div class="profile-section-head">
                <h2 class="profile-section-title">Personal Information</h2>
                <div class="profile-section-sub">Your official registered student information.</div>
            </div>

            <div class="profile-section-body">
                <div class="profile-info-row">
                    <div class="profile-info-label">Full Name</div>
                    <div class="profile-info-value"><?= h(fmt_value($student['full_name'] ?? '')) ?></div>
                </div>

                <div class="profile-info-row">
                    <div class="profile-info-label">Academic Email</div>
                    <div class="profile-info-value"><?= h(fmt_value($student['academic_email'] ?? '')) ?></div>
                </div>

                <div class="profile-info-row">
                    <div class="profile-info-label">Mobile</div>
                    <div class="profile-info-value"><?= h(fmt_value($student['mobile'] ?? '')) ?></div>
                </div>

                <div class="profile-info-row">
                    <div class="profile-info-label">Gender</div>
                    <div class="profile-info-value"><?= h(fmt_value($student['gender'] ?? '')) ?></div>
                </div>

                <div class="profile-info-row">
                    <div class="profile-info-label">NIC</div>
                    <div class="profile-info-value"><?= h(fmt_value($studentNic)) ?></div>
                </div>

                <div class="profile-info-row">
                    <div class="profile-info-label">Date of Birth</div>
                    <div class="profile-info-value">
                        <?php
                        $dob = trim((string)($student['dob'] ?? ''));
                        echo h(($dob === '' || $dob === '0000-00-00') ? '—' : $dob);
                        ?>
                    </div>
                </div>

                <div class="profile-info-row">
                    <div class="profile-info-label">Address</div>
                    <div class="profile-info-value"><?= h(fmt_value(trim(($student['address'] ?? '') . ' ' . ($student['address1'] ?? '') . ' ' . ($student['address2'] ?? '')))) ?></div>
                </div>

                <div class="profile-info-row">
                    <div class="profile-info-label">LMS Status</div>
                    <div class="profile-info-value"><?= h($statusText) ?></div>
                </div>
            </div>
        </div>
    </div>

    <div class="profile-tab-panel" data-profile-panel="courses">
        <div class="profile-section-card mb-0" id="coursesInfo">
            <div class="profile-section-head">
                <h2 class="profile-section-title">Course Information</h2>
                <div class="profile-section-sub">Your enrolled courses and reference numbers.</div>
            </div>

            <div class="profile-section-body">
                <?php if ($courseDetails): ?>
                    <div class="profile-course-list">
                        <?php foreach ($courseDetails as $cd): ?>
                            <div class="profile-course-item">
                                <div class="profile-course-name">
                                    <?= h($cd['course_name']) ?>
                                </div>

                                <div class="profile-course-meta">
                                    <span class="course-meta-pill">
                                        <i class="bi bi-journal-bookmark"></i>
                                        Course ID <?= (int)$cd['course_id'] ?>
                                    </span>

                                    <span class="course-meta-pill">
                                        <i class="bi bi-people"></i>
                                        <?= h($cd['batch_name'] ?: 'Batch —') ?>
                                    </span>

                                    <span class="course-meta-pill course-ref-pill">
                                        <i class="bi bi-hash"></i>
                                        Ref <?= h($cd['reference_no'] ?: 'Not Assigned') ?>
                                    </span>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="text-muted">No course information found.</div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="profile-tab-panel" data-profile-panel="payments">
    <div class="profile-section-card mb-3">
        <div class="profile-section-head">
            <h2 class="profile-section-title">Due Payments</h2>
            <div class="profile-section-sub">Outstanding payment details by course.</div>
        </div>

        <div class="profile-section-body">
            <div class="table-responsive">
                <table class="table align-middle profile-pay-table mb-0">
                    <thead>
                        <tr>
                            <th>Due Date</th>
                            <th>Balance</th>
                            <th>Course</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!$duePayments): ?>
                            <tr>
                                <td colspan="3" class="text-center text-muted py-4">No due payments found</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($duePayments as $d): ?>
                                <?php
                                    $due = (float)$d['amount_due_lkr'];
                                    $paid = (float)$d['paid_lkr'];
                                    $balance = max(0, $due - $paid);
                                ?>
                                <tr>
                                    <td><?= h(!empty($d['due_date']) ? date('d M Y', strtotime((string)$d['due_date'])) : '—') ?></td>
                                    <td class="fw-bold text-danger">LKR <?= h(number_format($balance, 2)) ?></td>
                                    <td><?= h($d['course_code'] ?: '—') ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="profile-section-card mb-0">
        <button class="profile-section-head w-100 text-start border-0"
                type="button"
                data-bs-toggle="collapse"
                data-bs-target="#profilePaymentHistory"
                aria-expanded="false">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h2 class="profile-section-title">Payment History</h2>
                    <div class="profile-section-sub">Click to view paid records.</div>
                </div>
                <i class="bi bi-chevron-down"></i>
            </div>
        </button>

        <div class="collapse" id="profilePaymentHistory">
            <div class="profile-section-body">
                <div class="table-responsive">
                    <table class="table align-middle profile-pay-table mb-0">
                        <thead>
                            <tr>
                                <th>Paid Date</th>
                                <th>Amount Paid</th>
                                <th>Course</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$paymentRows): ?>
                                <tr>
                                    <td colspan="3" class="text-center text-muted py-4">No payment history found</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($paymentRows as $p): ?>
                                    <tr>
                                        <td><?= h(!empty($p['date_paid']) ? date('d M Y, h:i A', strtotime((string)$p['date_paid'])) : '—') ?></td>
                                        <td class="fw-bold text-success">LKR <?= h(number_format((float)$p['amount'], 2)) ?></td>
                                        <td><?= h($p['course_code'] ?: '—') ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

                         
    <div class="profile-tab-panel" data-profile-panel="security">
        <div class="profile-password-card mb-0" id="securityInfo">
            <div class="profile-section-head">
                <h2 class="profile-section-title">Change Password</h2>
                <div class="profile-section-sub">Update your academic login password.</div>
            </div>

            <div class="profile-section-body">
                <form method="post">
                    <input type="hidden" name="action" value="password">

                    <div class="mb-3">
                        <label class="form-label fw-bold">Current Password</label>
                        <input type="password" name="current_password" class="form-control" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">New Password</label>
                        <input type="password" name="new_password" class="form-control" minlength="6" required>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-bold">Confirm New Password</label>
                        <input type="password" name="confirm_password" class="form-control" minlength="6" required>
                    </div>

                    <button class="btn btn-outline-primary rounded-pill px-4 fw-bold">
                        <i class="bi bi-shield-lock me-1"></i>
                        Change Password
                    </button>
                </form>
            </div>
        </div>

        <div class="alert alert-light border rounded-4 mt-3 mb-0">
            <i class="bi bi-info-circle me-1"></i>
            To update official profile details, contact administration.
        </div>
    </div>
</div>


<script>
document.addEventListener('DOMContentLoaded', function () {
    const buttons = document.querySelectorAll('.profile-tab-btn');
    const panels = document.querySelectorAll('.profile-tab-panel');

    function openProfileTab(tab) {
        buttons.forEach(btn => {
            btn.classList.toggle('active', btn.getAttribute('data-profile-tab') === tab);
        });

        panels.forEach(panel => {
            panel.classList.toggle('active', panel.getAttribute('data-profile-panel') === tab);
        });
    }

    buttons.forEach(btn => {
        btn.addEventListener('click', function () {
            openProfileTab(btn.getAttribute('data-profile-tab') || 'basic');
        });
    });

    openProfileTab('basic');
});
</script>

<?php if (!$EMBEDDED_PROFILE): ?>
    <?php require_once __DIR__ . '/../includes/student_layout_bottom.php'; ?>
<?php else: ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    </body>
    </html>
<?php endif; ?>