<?php
declare(strict_types=1);
session_start();
if (!isset($_SESSION['student_id'])) {
    header('Location: student-login.php');
    exit;
}

$name=$_SESSION['student_name']??'Học sinh';
$studentId=(int)$_SESSION['student_id'];

require_once __DIR__.'/../config/database.php';
$pdo=getDbConnection();

// Hồ sơ cá nhân: đọc/lưu trực tiếp từ bảng students.
if (empty($_SESSION['profile_csrf'])) {
    $_SESSION['profile_csrf']=bin2hex(random_bytes(32));
}

$profile=[
    'full_name'=>$name,
    'phone'=>'',
    'email'=>'',
    'birth_date'=>'',
    'gender'=>'',
    'province'=>'',
    'school_name'=>'',
    'class_name'=>'',
    'avatar_source'=>'default',
    'custom_avatar_path'=>'',
];
$profileMessage='';
$profileError='';
$profileForceOpen=false;

$passwordMessage='';
$passwordError='';
$passwordForceOpen=false;

try {
    $profileStmt=$pdo->prepare("SELECT full_name, phone, email, birth_date, gender, province, school_name, class_name, avatar_source, custom_avatar_path FROM students WHERE id=? LIMIT 1");
    $profileStmt->execute([$studentId]);
    $dbProfile=$profileStmt->fetch(PDO::FETCH_ASSOC);
    if ($dbProfile) {
        $profile=array_merge($profile,$dbProfile);
        $name=(string)($profile['full_name'] ?: $name);
    }
} catch (Throwable $e) {
    $profileError='Chưa đọc được thông tin cá nhân.';
}


// Avatar: học sinh có thể tải ảnh riêng lên và lưu đường dẫn vào students.custom_avatar_path.
$avatarMessage='';
$avatarError='';

if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action']??'')==='upload_avatar') {
    $token=(string)($_POST['csrf_token']??'');

    if (!hash_equals((string)$_SESSION['profile_csrf'],$token)) {
        $avatarError='Phiên làm việc đã thay đổi. Em tải lại trang rồi thử lại.';
    } elseif (!isset($_FILES['avatar_file']) || !is_array($_FILES['avatar_file'])) {
        $avatarError='Em hãy chọn một ảnh.';
    } else {
        $file=$_FILES['avatar_file'];
        $uploadError=(int)($file['error']??UPLOAD_ERR_NO_FILE);

        if ($uploadError!==UPLOAD_ERR_OK) {
            $avatarError='Chưa tải được ảnh. Em thử lại nhé.';
        } elseif ((int)($file['size']??0)>3*1024*1024) {
            $avatarError='Ảnh gốc tối đa 3 MB.';
        } else {
            $tmp=(string)($file['tmp_name']??'');
            $finfo=new finfo(FILEINFO_MIME_TYPE);
            $mime=$tmp!=='' ? (string)$finfo->file($tmp) : '';
            $allowed=[
                'image/jpeg'=>'jpg',
                'image/png'=>'png',
                'image/webp'=>'webp',
            ];

            if (!isset($allowed[$mime])) {
                $avatarError='Chỉ nhận ảnh JPG, PNG hoặc WEBP.';
            } elseif (@getimagesize($tmp)===false) {
                $avatarError='File đã chọn không phải ảnh hợp lệ.';
            } else {
                $uploadDir=__DIR__.'/../uploads/student-avatars';
                if (!is_dir($uploadDir) && !mkdir($uploadDir,0755,true) && !is_dir($uploadDir)) {
                    $avatarError='Chưa tạo được thư mục lưu avatar.';
                } else {
                    // Chuẩn hóa avatar về JPEG nhỏ để tiết kiệm dung lượng.
                    $sourceImage=null;
                    if ($mime==='image/jpeg') {
                        $sourceImage=@imagecreatefromjpeg($tmp);
                    } elseif ($mime==='image/png') {
                        $sourceImage=@imagecreatefrompng($tmp);
                    } elseif ($mime==='image/webp' && function_exists('imagecreatefromwebp')) {
                        $sourceImage=@imagecreatefromwebp($tmp);
                    }

                    if (!$sourceImage) {
                        $avatarError='Không xử lý được ảnh này. Em thử ảnh JPG hoặc PNG nhé.';
                    } else {
                        $srcW=imagesx($sourceImage);
                        $srcH=imagesy($sourceImage);
                        $side=min($srcW,$srcH);
                        $srcX=(int)(($srcW-$side)/2);
                        $srcY=(int)(($srcH-$side)/2);
                        $avatarSize=320;

                        $avatarImage=imagecreatetruecolor($avatarSize,$avatarSize);
                        imagecopyresampled(
                            $avatarImage,$sourceImage,
                            0,0,$srcX,$srcY,
                            $avatarSize,$avatarSize,$side,$side
                        );

                        $filename='student_'.$studentId.'_'.bin2hex(random_bytes(8)).'.jpg';
                        $target=$uploadDir.'/'.$filename;
                        $relativePath='uploads/student-avatars/'.$filename;

                        // Avatar nhỏ: ưu tiên vài chục KB, trần tối đa 150 KB.
                        $maxAvatarBytes=150*1024;
                        $quality=74;
                        $saved=imagejpeg($avatarImage,$target,$quality);
                        clearstatcache(true,$target);

                        while ($saved && is_file($target) && filesize($target)>$maxAvatarBytes && $quality>42) {
                            $quality-=6;
                            $saved=imagejpeg($avatarImage,$target,$quality);
                            clearstatcache(true,$target);
                        }

                        imagedestroy($avatarImage);
                        imagedestroy($sourceImage);

                        if (!$saved || !is_file($target) || filesize($target)>$maxAvatarBytes) {
                            @unlink($target);
                            $avatarError='Ảnh chưa nén được đủ nhỏ. Em thử ảnh khác nhé.';
                        } else {
                        try {
                            $oldPath=(string)($profile['custom_avatar_path']??'');
                            $avatarStmt=$pdo->prepare("UPDATE students SET avatar_source='upload', custom_avatar_path=? WHERE id=?");
                            $avatarStmt->execute([$relativePath,$studentId]);

                            // Chỉ xóa avatar cũ do hệ thống này tạo, sau khi DB đã cập nhật thành công.
                            if ($oldPath!=='' && str_starts_with($oldPath,'uploads/student-avatars/')) {
                                $oldFile=__DIR__.'/../'.$oldPath;
                                if (is_file($oldFile) && realpath(dirname($oldFile))===realpath($uploadDir)) {
                                    @unlink($oldFile);
                                }
                            }

                            header('Location: student-profile.php?avatar_saved=1');
                            exit;
                        } catch (Throwable $e) {
                            @unlink($target);
                            $avatarError='Chưa lưu được avatar vào hồ sơ.';
                        }
                    }
                    }
                }
            }
        }
    }
}

if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action']??'')==='save_profile') {
    $profileForceOpen=true;
    $token=(string)($_POST['csrf_token']??'');

    $fullName=trim((string)($_POST['full_name']??''));
    $phone=trim((string)($_POST['phone']??''));
    $email=trim((string)($_POST['email']??''));
    $birthDateRaw=trim((string)($_POST['birth_date']??''));
    $gender=trim((string)($_POST['gender']??''));
    $province=trim((string)($_POST['province']??''));
    $schoolName=trim((string)($_POST['school_name']??''));
    $className=trim((string)($_POST['class_name']??''));

    $profile=[
        'full_name'=>$fullName,
        'phone'=>$phone,
        'email'=>$email,
        'birth_date'=>$birthDateRaw,
        'gender'=>$gender,
        'province'=>$province,
        'school_name'=>$schoolName,
        'class_name'=>$className,
    ];

    if (!hash_equals((string)$_SESSION['profile_csrf'],$token)) {
        $profileError='Phiên làm việc đã thay đổi. Em tải lại trang rồi thử lại.';
    } elseif ($fullName==='') {
        $profileError='Em hãy nhập họ và tên.';
    } elseif ($phone==='') {
        $profileError='Em hãy nhập số điện thoại.';
    } elseif ($email!=='' && !filter_var($email,FILTER_VALIDATE_EMAIL)) {
        $profileError='Gmail chưa đúng định dạng.';
    } else {
        $birthDate=null;
        if ($birthDateRaw!=='') {
            $birthDateObj=DateTime::createFromFormat('Y-m-d',$birthDateRaw);
            if (!$birthDateObj || $birthDateObj->format('Y-m-d')!==$birthDateRaw || $birthDateObj>new DateTime('today')) {
                $profileError='Ngày tháng năm sinh chưa hợp lệ.';
            } else { $birthDate=$birthDateRaw; }
        }
        if ($profileError==='' && $gender!=='' && !in_array($gender,['male','female'],true)) {
            $profileError='Giới tính chưa hợp lệ.';
        }

        if ($profileError==='') {
            try {
                $saveStmt=$pdo->prepare("UPDATE students SET full_name=?, phone=?, email=?, birth_date=?, gender=?, province=?, school_name=?, class_name=? WHERE id=?");
                $saveStmt->execute([
                    $fullName,
                    $phone,
                    $email!=='' ? $email : null,
                    $birthDate,
                    $gender!=='' ? $gender : null,
                    $province!=='' ? $province : null,
                    $schoolName!=='' ? $schoolName : null,
                    $className!=='' ? $className : null,
                    $studentId,
                ]);
                $_SESSION['student_name']=$fullName;
                $name=$fullName;
                header('Location: student-profile.php?profile_saved=1');
                exit;
            } catch (Throwable $e) {
                $profileError='Chưa lưu được thông tin. Em thử lại nhé.';
            }
        }
    }
}


if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action']??'')==='change_password') {
    $passwordForceOpen=true;
    $token=(string)($_POST['csrf_token']??'');
    $currentPassword=(string)($_POST['current_password']??'');
    $newPassword=(string)($_POST['new_password']??'');
    $confirmPassword=(string)($_POST['confirm_password']??'');

    if (!hash_equals((string)$_SESSION['profile_csrf'],$token)) {
        $passwordError='Phiên làm việc đã thay đổi. Em tải lại trang rồi thử lại.';
    } elseif ($currentPassword==='' || $newPassword==='' || $confirmPassword==='') {
        $passwordError='Em hãy nhập đầy đủ 3 ô mật khẩu.';
    } elseif (strlen($newPassword)<6) {
        $passwordError='Mật khẩu mới cần ít nhất 6 ký tự.';
    } elseif ($newPassword!==$confirmPassword) {
        $passwordError='Hai mật khẩu mới chưa giống nhau.';
    } else {
        try {
            $passwordStmt=$pdo->prepare("SELECT password_hash FROM students WHERE id=? LIMIT 1");
            $passwordStmt->execute([$studentId]);
            $currentHash=(string)($passwordStmt->fetchColumn() ?: '');

            if ($currentHash==='' || !password_verify($currentPassword,$currentHash)) {
                $passwordError='Mật khẩu hiện tại chưa đúng.';
            } elseif (password_verify($newPassword,$currentHash)) {
                $passwordError='Mật khẩu mới phải khác mật khẩu hiện tại.';
            } else {
                $newHash=password_hash($newPassword,PASSWORD_DEFAULT);
                if ($newHash===false) {
                    $passwordError='Chưa tạo được mật khẩu mới. Em thử lại nhé.';
                } else {
                    $updatePasswordStmt=$pdo->prepare("UPDATE students SET password_hash=? WHERE id=?");
                    $updatePasswordStmt->execute([$newHash,$studentId]);

                    header('Location: student-profile.php?password_saved=1');
                    exit;
                }
            }
        } catch (Throwable $e) {
            $passwordError='Chưa đổi được mật khẩu. Em thử lại nhé.';
        }
    }
}

if (isset($_GET['profile_saved'])) {
    $profileMessage='Đã lưu thay đổi.';
    $profileForceOpen=true;
}


if (isset($_GET['password_saved'])) {
    $passwordMessage='Đã đổi mật khẩu.';
    $passwordForceOpen=true;
}

if (isset($_GET['avatar_saved'])) {
    $avatarMessage='Đã đổi avatar.';
}

$avatarPath=(string)($profile['custom_avatar_path']??'');
$avatarUrl='';
if (($profile['avatar_source']??'')==='upload' && $avatarPath!=='' && str_starts_with($avatarPath,'uploads/student-avatars/')) {
    $avatarUrl='../'.ltrim($avatarPath,'/');
} elseif (($profile['avatar_source']??'')==='preset' && $avatarPath!=='' && str_starts_with($avatarPath,'assets/avatars/presets/')) {
    $avatarUrl='../'.ltrim($avatarPath,'/');
}

// Tiến độ học tập: dùng đúng nguồn tiến độ + sổ XP chung của EnglishSpeak.
$progressStats=[
    'lessons_completed'=>0,
    'activities_completed'=>0,
    'best_score'=>0,
    'attempt_count'=>0,
    'completion_xp'=>0,
    'practice_xp'=>0,
];

try {
    $stmt=$pdo->prepare("SELECT
        SUM(CASE WHEN content_type='lesson' AND status='completed' THEN 1 ELSE 0 END) AS lessons_completed,
        SUM(CASE WHEN content_type='activity' AND status='completed' THEN 1 ELSE 0 END) AS activities_completed,
        MAX(CASE WHEN content_type='activity' THEN best_score ELSE NULL END) AS best_score,
        SUM(CASE WHEN content_type='activity' THEN COALESCE(attempt_count,0) ELSE 0 END) AS attempt_count
        FROM student_content_progress
        WHERE student_id=?");
    $stmt->execute([$studentId]);
    $row=$stmt->fetch(PDO::FETCH_ASSOC) ?: [];
    $progressStats['lessons_completed']=(int)($row['lessons_completed']??0);
    $progressStats['activities_completed']=(int)($row['activities_completed']??0);
    $progressStats['best_score']=(int)round((float)($row['best_score']??0));
    $progressStats['attempt_count']=(int)($row['attempt_count']??0);

    $xpStmt=$pdo->prepare("SELECT
        COALESCE(SUM(CASE WHEN xp_source='completion' THEN xp_change ELSE 0 END),0) AS completion_xp,
        COALESCE(SUM(CASE WHEN xp_source IN ('practice','new_best') THEN xp_change ELSE 0 END),0) AS practice_xp
        FROM xp_transactions
        WHERE student_id=?");
    $xpStmt->execute([$studentId]);
    $xpRow=$xpStmt->fetch(PDO::FETCH_ASSOC) ?: [];
    $progressStats['completion_xp']=(int)($xpRow['completion_xp']??0);
    $progressStats['practice_xp']=(int)($xpRow['practice_xp']??0);
} catch (Throwable $e) {
    // Không làm hỏng trang Hồ sơ nếu dữ liệu tiến độ chưa sẵn sàng.
}

$pageTitle='';$pageSubtitle='';$activeStudentNav='profile';
include __DIR__.'/../includes/student-layout-start.php';
?>
<style>
:root{
    --pf-bg:#eef7ff;
    --pf-surface:#ffffff;
    --pf-text:#17324d;
    --pf-muted:#6f8799;
    --pf-primary:#197fc4;
    --pf-soft:#e7f4ff;
    --pf-border:#dbe9f3;
    --pf-shadow:0 7px 22px rgba(29,80,116,.09);
    --pf-width:520px;
    --pf-nav-height:78px;
}

*{box-sizing:border-box}

html,body{
    margin:0!important;
    min-height:100%;
    background:var(--pf-bg)!important;
    color:var(--pf-text)!important;
    font-family:"Segoe UI",Tahoma,Arial,sans-serif!important;
}

body{
    padding-bottom:calc(var(--pf-nav-height) + env(safe-area-inset-bottom) + 16px)!important;
}

.student-app{
    width:min(100%,var(--pf-width))!important;
    min-height:100vh!important;
    margin:0 auto!important;
    background:#f7fbff!important;
    box-shadow:0 0 28px rgba(27,73,108,.08)!important;
}

.student-header{
    position:sticky!important;
    top:0!important;
    z-index:40!important;
    display:grid!important;
    grid-template-columns:46px minmax(0,1fr) 46px!important;
    align-items:center!important;
    gap:9px!important;
    min-height:96px!important;
    padding:10px 14px!important;
    background:linear-gradient(135deg,#3488ef,#17b8e4)!important;
    color:#fff!important;
    box-shadow:0 5px 15px rgba(31,135,210,.22)!important;
}

.student-header__text{
    min-width:0!important;
    text-align:center!important;
}

.student-header__text h1{
    margin:0!important;
    color:#fff!important;
    font-size:23px!important;
    font-weight:850!important;
    line-height:1.15!important;
    display:flex!important;
    align-items:center!important;
    justify-content:center!important;
}

.student-header__text p{
    margin:4px 0 0!important;
    color:rgba(255,255,255,.92)!important;
    font-size:12.5px!important;
}

.student-header__spacer{
    width:44px!important;
    height:44px!important;
}

.student-content{
    width:100%!important;
    padding:16px 14px 26px!important;
}

.student-nav{
    position:fixed!important;
    z-index:9999!important;
    left:50%!important;
    bottom:0!important;
    width:min(100%,var(--pf-width))!important;
    min-height:var(--pf-nav-height)!important;
    display:grid!important;
    grid-template-columns:repeat(4,minmax(0,1fr))!important;
    padding:7px 8px calc(7px + env(safe-area-inset-bottom))!important;
    border-top:1px solid #dce5ed!important;
    background:rgba(255,255,255,.98)!important;
    box-shadow:0 -6px 18px rgba(32,65,93,.11)!important;
    transform:translateX(-50%)!important;
    backdrop-filter:blur(14px);
}

.student-nav__item{
    position:relative!important;
    display:flex!important;
    min-width:0!important;
    flex-direction:column!important;
    align-items:center!important;
    justify-content:center!important;
    gap:2px!important;
    color:#586879!important;
    text-decoration:none!important;
}

.student-nav__icon{
    width:42px!important;
    height:34px!important;
    display:grid!important;
    place-items:center!important;
    border-radius:12px!important;
    font-size:23px!important;
}

.student-nav__label{
    overflow:hidden!important;
    max-width:100%!important;
    color:inherit!important;
    font-size:11.5px!important;
    font-weight:750!important;
    white-space:nowrap!important;
    text-overflow:ellipsis!important;
}

.student-nav__item.is-active{color:var(--pf-primary)!important}
.student-nav__item.is-active .student-nav__icon{background:var(--pf-soft)!important}
.student-nav__item.is-active::after{
    content:"";
    position:absolute;
    top:-7px;
    width:52px;
    height:3px;
    border-radius:999px;
    background:var(--pf-primary);
}




















.profile-head{
    margin-bottom:14px;
    padding:15px 16px;
    border:1px solid var(--pf-border);
    border-radius:19px;
    background:linear-gradient(135deg,#edf6ff,#e6f1ff);
    box-shadow:var(--pf-shadow);
}

.profile-head strong{
    display:block;
    color:#123e62;
    font-size:18px;
}

.profile-head span{
    display:block;
    margin-top:5px;
    color:var(--pf-muted);
    font-size:13px;
}

.card-list{
    display:grid!important;
    gap:11px!important;
}

.card-list .card{
    min-height:76px!important;
    display:grid!important;
    grid-template-columns:48px minmax(0,1fr) 24px!important;
    align-items:center!important;
    gap:12px!important;
    padding:12px 14px!important;
    border:1px solid var(--pf-border)!important;
    border-radius:18px!important;
    background:#fff!important;
    box-shadow:0 7px 22px rgba(29,80,116,.08)!important;
    color:var(--pf-text)!important;
    text-decoration:none!important;
}

.card-list .card__icon{
    width:46px!important;
    height:46px!important;
    display:grid!important;
    place-items:center!important;
    border-radius:14px!important;
    background:var(--pf-soft)!important;
    font-size:25px!important;
}

.card-list .card__body{
    min-width:0!important;
    display:flex!important;
    flex-direction:column!important;
    gap:4px!important;
}

.card-list .card__title{
    color:#123e62!important;
    font-size:16px!important;
    font-weight:850!important;
    line-height:1.25!important;
}

.card-list .card__text{
    color:var(--pf-muted)!important;
    font-size:12.5px!important;
    line-height:1.35!important;
}

.card-list .card__arrow{
    color:#1680c4!important;
    font-size:25px!important;
    text-align:right!important;
}

.card-list .logout-card{
    grid-template-columns:48px minmax(0,1fr)!important;
}

.card-list .logout-card .card__icon{
    background:#fff1e7!important;
}

.profile-form{
    display:none;
    margin-top:12px;
    padding:16px;
    border:1px solid var(--pf-border);
    border-radius:18px;
    background:#fff;
    box-shadow:var(--pf-shadow);
}
.profile-form.is-open{display:block}

.profile-form__title{
    margin:0 0 14px;
    color:#123e62;
    font-size:18px;
    font-weight:850;
}

.profile-field{
    display:grid;
    gap:6px;
    margin-bottom:12px;
}
.profile-field label{
    color:#36536e;
    font-size:12.5px;
    font-weight:800;
}
.profile-field input,
.profile-field select{
    width:100%;
    min-height:44px;
    padding:10px 12px;
    border:1px solid #d8e5ef;
    border-radius:12px;
    background:#fafdff;
    color:#17324d;
    font:inherit;
    outline:none;
}
.profile-field input:focus,
.profile-field select:focus{
    border-color:#76b9e9;
    box-shadow:0 0 0 3px rgba(25,127,196,.10);
}

.profile-form__actions{
    display:flex;
    justify-content:flex-end;
    gap:9px;
    margin-top:14px;
}
.profile-btn{
    min-height:42px;
    padding:0 14px;
    border-radius:12px;
    font-weight:800;
    cursor:pointer;
}
.profile-btn--secondary{
    border:1px solid #d8e5ef;
    background:#fff;
    color:#48647b;
}
.profile-btn--primary{
    border:0;
    background:#197fc4;
    color:#fff;
}
.profile-note{
    margin-top:10px;
    color:#7a8da0;
    font-size:11.5px;
    line-height:1.45;
}

.profile-gender{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
}
.profile-gender label{
    display:flex;
    align-items:center;
    gap:7px;
    min-height:42px;
    padding:8px 12px;
    border:1px solid #d8e5ef;
    border-radius:12px;
    background:#fafdff;
    color:#36536e;
    font-size:13px;
    font-weight:750;
    cursor:pointer;
}
.profile-gender input{
    width:auto!important;
    min-height:0!important;
    padding:0!important;
    margin:0;
    accent-color:#197fc4;
}















@media(max-width:390px){
    .student-content{
        padding-left:11px!important;
        padding-right:11px!important;
    }
    .profile-head{
        padding:14px;
    }
    .card-list .card{
        min-height:72px!important;
        grid-template-columns:44px minmax(0,1fr) 20px!important;
        gap:10px!important;
        padding:11px 12px!important;
    }
    .card-list .card__icon{
        width:42px!important;
        height:42px!important;
        font-size:23px!important;
    }
}
</style>

<form id="avatarUploadForm" method="post" enctype="multipart/form-data" style="display:none;">
    <input type="hidden" name="action" value="upload_avatar">
    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['profile_csrf'], ENT_QUOTES, 'UTF-8') ?>">
    <input type="file" id="avatarFileInput" name="avatar_file" accept="image/jpeg,image/png,image/webp">
</form>

<?php if ($avatarError!==''): ?>
<div class="profile-note" style="margin:0 0 10px;color:#b42318;font-weight:700;"><?= htmlspecialchars($avatarError, ENT_QUOTES, 'UTF-8') ?></div>
<?php elseif ($avatarMessage!==''): ?>
<div class="profile-note" style="margin:0 0 10px;color:#137a48;font-weight:700;"><?= htmlspecialchars($avatarMessage, ENT_QUOTES, 'UTF-8') ?></div>
<?php endif; ?>

<section class="profile-top-card">
    <a href="student-avatar.php" class="profile-avatar-button" id="profileAvatarButton" aria-label="My Avatar" title="My Avatar">
        <?php if ($avatarUrl!==''): ?>
            <img src="<?= htmlspecialchars($avatarUrl, ENT_QUOTES, 'UTF-8') ?>" alt="Avatar">
        <?php else: ?>
            <span aria-hidden="true">👤</span>
        <?php endif; ?>
        <span class="profile-avatar-edit" aria-hidden="true">✎</span>
    </a>
    <div class="profile-top-info">
        <div class="profile-top-name"><?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?></div>
    </div>
</section>

<div class="card-list">
<button type="button" class="card" id="openProfileForm" style="width:100%;text-align:left;cursor:pointer;"><span class="card__icon">👤</span><span class="card__body"><span class="card__title">Thông tin cá nhân</span><span class="card__text">Điền và cập nhật thông tin.</span></span><span class="card__arrow">›</span></button>

<form method="post" class="profile-form<?= $profileForceOpen ? ' is-open' : '' ?>" id="profileFormPanel" autocomplete="on">
    <input type="hidden" name="action" value="save_profile">
    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['profile_csrf'], ENT_QUOTES, 'UTF-8') ?>">

    <div class="profile-field">
        <label for="profile_full_name">Họ và tên</label>
        <input type="text" id="profile_full_name" name="full_name" required
               value="<?= htmlspecialchars((string)($profile['full_name']??''), ENT_QUOTES, 'UTF-8') ?>"
               placeholder="Nhập họ và tên">
    </div>

    <div class="profile-field">
        <label for="profile_birth_date">Ngày tháng năm sinh</label>
        <input type="date" id="profile_birth_date" name="birth_date" max="<?= htmlspecialchars(date('Y-m-d'), ENT_QUOTES, 'UTF-8') ?>"
               value="<?= htmlspecialchars((string)($profile['birth_date']??''), ENT_QUOTES, 'UTF-8') ?>">
    </div>

    <div class="profile-field">
        <label>Giới tính</label>
        <div class="profile-gender">
            <label><input type="radio" name="gender" value="male" <?= (($profile['gender']??'')==='male') ? 'checked' : '' ?>> Nam</label>
            <label><input type="radio" name="gender" value="female" <?= (($profile['gender']??'')==='female') ? 'checked' : '' ?>> Nữ</label>
        </div>
    </div>

    <div class="profile-field">
        <label for="profile_phone">Số điện thoại</label>
        <input type="tel" id="profile_phone" name="phone" required
               value="<?= htmlspecialchars((string)($profile['phone']??''), ENT_QUOTES, 'UTF-8') ?>"
               placeholder="Nhập số điện thoại">
    </div>

    <div class="profile-field">
        <label for="profile_email">Gmail</label>
        <input type="email" id="profile_email" name="email"
               value="<?= htmlspecialchars((string)($profile['email']??''), ENT_QUOTES, 'UTF-8') ?>"
               placeholder="Nhập Gmail">
    </div>

    <div class="profile-field">
        <label for="profile_province">Tỉnh / Thành phố</label>
        <input type="text" id="profile_province" name="province"
               value="<?= htmlspecialchars((string)($profile['province']??''), ENT_QUOTES, 'UTF-8') ?>"
               placeholder="Ví dụ: Bến Tre">
    </div>

    <div class="profile-field">
        <label for="profile_school">Trường đang học</label>
        <input type="text" id="profile_school" name="school_name"
               value="<?= htmlspecialchars((string)($profile['school_name']??''), ENT_QUOTES, 'UTF-8') ?>"
               placeholder="Nhập tên trường">
    </div>

    <div class="profile-field">
        <label for="profile_class">Lớp</label>
        <input type="text" id="profile_class" name="class_name"
               value="<?= htmlspecialchars((string)($profile['class_name']??''), ENT_QUOTES, 'UTF-8') ?>"
               placeholder="Ví dụ: 1/1, 2A, 5/3">
    </div>

    <div class="profile-form__actions">
        <button type="button" class="profile-btn profile-btn--secondary" id="closeProfileForm">Đóng</button>
        <button type="submit" class="profile-btn profile-btn--primary">Lưu thay đổi</button>
    </div>

    <?php if ($profileError!==''): ?>
        <div class="profile-note" id="profileDemoNote" style="color:#b42318;font-weight:700;">
            <?= htmlspecialchars($profileError, ENT_QUOTES, 'UTF-8') ?>
        </div>
    <?php elseif ($profileMessage!==''): ?>
        <div class="profile-note" id="profileDemoNote" style="color:#137a48;font-weight:700;">
            <?= htmlspecialchars($profileMessage, ENT_QUOTES, 'UTF-8') ?>
        </div>
    <?php endif; ?>
</form>


<button type="button" class="card" id="openPasswordForm" style="width:100%;text-align:left;cursor:pointer;">
    <span class="card__icon">🔐</span>
    <span class="card__body">
        <span class="card__title">Đổi mật khẩu</span>
        <span class="card__text">Thay đổi mật khẩu đăng nhập.</span>
    </span>
    <span class="card__arrow">›</span>
</button>

<form method="post" class="profile-form<?= $passwordForceOpen ? ' is-open' : '' ?>" id="passwordFormPanel" autocomplete="off">
    <input type="hidden" name="action" value="change_password">
    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['profile_csrf'], ENT_QUOTES, 'UTF-8') ?>">

    <div class="profile-field">
        <label for="current_password">Mật khẩu hiện tại</label>
        <input type="password" id="current_password" name="current_password" autocomplete="current-password" required placeholder="Nhập mật khẩu hiện tại">
    </div>

    <div class="profile-field">
        <label for="new_password">Mật khẩu mới</label>
        <input type="password" id="new_password" name="new_password" autocomplete="new-password" minlength="6" required placeholder="Tối thiểu 6 ký tự">
    </div>

    <div class="profile-field">
        <label for="confirm_password">Nhập lại mật khẩu mới</label>
        <input type="password" id="confirm_password" name="confirm_password" autocomplete="new-password" minlength="6" required placeholder="Nhập lại mật khẩu mới">
    </div>

    <div class="profile-form__actions">
        <button type="button" class="profile-btn profile-btn--secondary" id="closePasswordForm">Đóng</button>
        <button type="submit" class="profile-btn profile-btn--primary">Đổi mật khẩu</button>
    </div>

    <?php if ($passwordError!==''): ?>
        <div class="profile-note" style="color:#b42318;font-weight:700;">
            <?= htmlspecialchars($passwordError, ENT_QUOTES, 'UTF-8') ?>
        </div>
    <?php elseif ($passwordMessage!==''): ?>
        <div class="profile-note" style="color:#137a48;font-weight:700;">
            <?= htmlspecialchars($passwordMessage, ENT_QUOTES, 'UTF-8') ?>
        </div>
    <?php endif; ?>
</form>


<button type="button" class="card" id="openProgressPanel" style="width:100%;text-align:left;cursor:pointer;">
    <span class="card__icon">📈</span>
    <span class="card__body">
        <span class="card__title">Tiến độ</span>
        <span class="card__text">Bài học và hoạt động đã hoàn thành.</span>
    </span>
    <span class="card__arrow">›</span>
</button>

<div class="profile-form" id="progressPanel">
    <div class="profile-field">
        <label>Bài học đã hoàn thành</label>
        <input type="text" value="<?= $progressStats['lessons_completed'] ?> bài" readonly>
    </div>

    <div class="profile-field">
        <label>Hoạt động đã hoàn thành</label>
        <input type="text" value="<?= $progressStats['activities_completed'] ?> hoạt động" readonly>
    </div>

    <div class="profile-field">
        <label>Điểm cao nhất</label>
        <input type="text" value="<?= $progressStats['best_score'] ?>%" readonly>
    </div>

    <div class="profile-field">
        <label>Số lần học</label>
        <input type="text" value="<?= $progressStats['attempt_count'] ?> lần" readonly>
    </div>

    <div class="profile-field">
        <label>XP hoàn thành</label>
        <input type="text" value="<?= $progressStats['completion_xp'] ?> XP" readonly>
    </div>

    <div class="profile-field">
        <label>XP luyện tập</label>
        <input type="text" value="<?= $progressStats['practice_xp'] ?> XP" readonly>
    </div>

    <div class="profile-form__actions">
        <button type="button" class="profile-btn profile-btn--secondary" id="closeProgressPanel">Đóng</button>
    </div>

</div>

<a class="card logout-card" href="logout.php"><span class="card__icon">🚪</span><span class="card__body"><span class="card__title">Đăng xuất</span><span class="card__text">Thoát khỏi tài khoản hiện tại.</span></span></a>
</div>


<style>
/* =========================================================
   Profile UI — đồng bộ Home / Đang học / Xếp hạng
   ========================================================= */
:root{
    --pf-bg:#ffffff;
    --pf-surface:#ffffff;
    --pf-text:#0b4f9c;
    --pf-muted:#315d82;
    --pf-primary:#0b4f9c;
    --pf-soft:#eef7ff;
    --pf-border:#cfe4f5;
    --pf-shadow:0 5px 16px rgba(29,80,116,.06);
}

html,body{
    background:#ffffff!important;
    color:var(--pf-text)!important;
}
.student-app{
    background:#ffffff!important;
    box-shadow:0 0 24px rgba(20,60,90,.06)!important;
}

/* Bỏ dải xanh/header cũ */
.student-header{
    display:none!important;
}

.student-content{
    padding-top:10px!important;
}

/* Khối Hồ sơ đầu trang */
.profile-top-card{
    position:sticky;
    top:0;
    z-index:90;
    display:flex;
    align-items:center;
    gap:14px;
    margin-bottom:14px;
    padding:14px 16px;
    border:1px solid #cfe4f5;
    border-radius:18px;
    background:#eef7ff;
    box-shadow:0 6px 14px rgba(29,80,116,.05);
}

.profile-avatar-button{
    position:relative;
    width:68px;
    height:68px;
    flex:0 0 68px;
    display:grid;
    place-items:center;
    padding:0;
    border:3px solid #ffffff;
    border-radius:50%;
    background:#ffffff;
    color:#0b4f9c;
    box-shadow:0 3px 10px rgba(29,80,116,.12);
    font-size:36px;
    cursor:pointer;
    overflow:visible;
}
.profile-avatar-button img{
    width:100%;
    height:100%;
    display:block;
    object-fit:cover;
    border-radius:50%;
}
.profile-avatar-edit{
    position:absolute;
    right:-4px;
    bottom:-4px;
    width:23px;
    height:23px;
    display:grid;
    place-items:center;
    border:2px solid #fff;
    border-radius:50%;
    background:#0b4f9c;
    color:#fff;
    font-size:12px;
    font-weight:900;
}

.profile-top-info{
    min-width:0;
}
.profile-top-label{
    color:#0b4f9c;
    font-size:19px;
    font-weight:900;
    letter-spacing:.02em;
}
.profile-top-name{
    margin-top:4px;
    color:#315d82;
    font-size:16px;
    font-weight:850;
    line-height:1.25;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
}

/* Các mục chính */
.card-list{
    gap:12px!important;
}
.card-list .card{
    min-height:78px!important;
    border-color:#d4e3ee!important;
    background:#ffffff!important;
    box-shadow:0 5px 16px rgba(29,80,116,.06)!important;
}
.card-list .card__icon{
    background:#eef7ff!important;
}
.card-list .card__title{
    color:#0b4f9c!important;
    font-size:17px!important;
    font-weight:900!important;
}
.card-list .card__text{
    color:#315d82!important;
    font-size:13.5px!important;
    font-weight:700!important;
}
.card-list .card__arrow{
    color:#0b4f9c!important;
}

/* Form mở rộng */
.profile-form{
    border-color:#d4e3ee!important;
    background:#ffffff!important;
    box-shadow:0 5px 16px rgba(29,80,116,.06)!important;
}
.profile-form__title{
    color:#0b4f9c!important;
    font-size:19px!important;
    font-weight:900!important;
}
.profile-field label{
    color:#315d82!important;
    font-size:13px!important;
    font-weight:850!important;
}
.profile-field input,
.profile-field select{
    min-height:46px!important;
    background:#ffffff!important;
    color:#17324d!important;
    border-color:#d4e3ee!important;
}
.profile-btn--primary{
    background:#0b4f9c!important;
}
.profile-btn--secondary{
    color:#315d82!important;
}

/* Đăng xuất giữ nhận diện riêng nhẹ */
.card-list .logout-card .card__icon{
    background:#fff3ea!important;
}

/* Menu chân đồng bộ các trang trước */
.student-nav{
    background:#ffffff!important;
}
.student-nav__item{
    color:#315d82!important;
}
.student-nav__item.is-active{
    color:#0b4f9c!important;
}
.student-nav__item.is-active .student-nav__icon{
    background:#eef7ff!important;
}
.student-nav__item.is-active::after{
    background:#0b4f9c!important;
}
.student-nav__label{
    color:inherit!important;
    font-size:12.5px!important;
    font-weight:850!important;
}

@media(max-width:390px){
    .profile-top-card{
        padding:12px 14px;
        gap:12px;
    }
    .profile-avatar-button{
        width:62px;
        height:62px;
        flex-basis:62px;
        font-size:33px;
    }
    .profile-top-label{
        font-size:18px;
    }
    .profile-top-name{
        font-size:15px;
    }
}

/* Final profile visual adjustments */
.profile-avatar-button{
    width:78px!important;
    height:78px!important;
    flex:0 0 78px!important;
    font-size:41px!important;
}
.profile-top-name{
    margin-top:0!important;
    font-size:18px!important;
    font-weight:900!important;
}
.card-list .logout-card{
    border-color:#f3c79f!important;
    background:#fff8f1!important;
}
.card-list .logout-card .card__icon{
    background:#ffead8!important;
}
.card-list .logout-card .card__title{
    color:#d96b19!important;
}
.card-list .logout-card .card__text{
    color:#a85b25!important;
}
@media(max-width:390px){
    .profile-avatar-button{
        width:72px!important;
        height:72px!important;
        flex-basis:72px!important;
        font-size:38px!important;
    }
}

/* Chừa khoảng trống cuối vùng cuộn để menu chân không che form/nút */
.student-content{
    padding-bottom:calc(var(--pf-nav-height) + 36px + env(safe-area-inset-bottom))!important;
}

</style>


<script>
(() => {
    const openBtn = document.getElementById('openProfileForm');
    const closeBtn = document.getElementById('closeProfileForm');
    const panel = document.getElementById('profileFormPanel');

    openBtn?.addEventListener('click', () => {
        if (!panel) return;

        const willOpen = !panel.classList.contains('is-open');

        // Thu các mục khác nếu đang mở
        passwordPanel?.classList.remove('is-open');
        progressPanel?.classList.remove('is-open');

        // Bấm lần 1 mở, bấm lần 2 thu
        panel.classList.toggle('is-open');

        if (willOpen) {
            panel.scrollIntoView({behavior:'smooth', block:'nearest'});
        }
    });

    closeBtn?.addEventListener('click', () => {
        panel?.classList.remove('is-open');
    });


    const openPasswordBtn = document.getElementById('openPasswordForm');
    const closePasswordBtn = document.getElementById('closePasswordForm');
    const passwordPanel = document.getElementById('passwordFormPanel');

    const openProgressBtn = document.getElementById('openProgressPanel');
    const closeProgressBtn = document.getElementById('closeProgressPanel');
    const progressPanel = document.getElementById('progressPanel');

    openPasswordBtn?.addEventListener('click', () => {
        if (!passwordPanel) return;

        const willOpen = !passwordPanel.classList.contains('is-open');

        // Thu các mục khác nếu đang mở
        panel?.classList.remove('is-open');
        progressPanel?.classList.remove('is-open');

        // Bấm lần 1 mở, bấm lần 2 thu
        passwordPanel.classList.toggle('is-open');

        if (willOpen) {
            passwordPanel.scrollIntoView({behavior:'smooth', block:'nearest'});
        }
    });

    closePasswordBtn?.addEventListener('click', () => {
        passwordPanel?.classList.remove('is-open');
    });


    openProgressBtn?.addEventListener('click', () => {
        if (!progressPanel) return;

        const willOpen = !progressPanel.classList.contains('is-open');

        // Thu các mục khác nếu đang mở
        panel?.classList.remove('is-open');
        passwordPanel?.classList.remove('is-open');

        // Bấm lần 1 mở, bấm lần 2 thu
        progressPanel.classList.toggle('is-open');

        if (willOpen) {
            progressPanel.scrollIntoView({behavior:'smooth', block:'nearest'});
        }
    });

    closeProgressBtn?.addEventListener('click', () => {
        progressPanel?.classList.remove('is-open');
    });
})();
</script>

<?php include __DIR__.'/../includes/student-layout-end.php'; ?>
