<?php
require_once 'auth.php';
include 'db.php';
requireLogin($conn);

$user_id = (int) ($_SESSION['user_id'] ?? 0);
$message = '';
$message_type = '';

// DAPATKAN MAKLUMAT PENGGUNA SEMASA (termasuk role)
$stmt = mysqli_prepare($conn, "SELECT * FROM users WHERE id = ?");
mysqli_stmt_bind_param($stmt, "i", $user_id);
mysqli_stmt_execute($stmt);
$user = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));

// Set role dari database
$role = $user['role'] ?? 'user';

function getSignatureOtpSession($user_id) {
    $otp_data = $_SESSION['signature_upload_otp'] ?? [];
    if (!is_array($otp_data) || (int) ($otp_data['user_id'] ?? 0) !== (int) $user_id) {
        return [];
    }

    if (strtotime((string) ($otp_data['expires_at'] ?? '')) <= time()) {
        unset($_SESSION['signature_upload_otp']);
        return [];
    }

    return $otp_data;
}

function isSignatureUploadVerified($user_id) {
    $otp_data = getSignatureOtpSession($user_id);
    if (empty($otp_data['verified'])) {
        return false;
    }

    return strtotime((string) ($otp_data['verified_until'] ?? '')) > time();
}

// PROSES PERMINTAAN OTP UNTUK TUKAR TANDATANGAN
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['request_signature_otp'])) {
    $email_input = normalizeEmailAddress($_POST['signature_email'] ?? '');
    $password_input = (string) ($_POST['signature_password'] ?? '');
    $registered_email = normalizeEmailAddress($user['email'] ?? '');

    if ($email_input === '' || !isValidEmailAddress($email_input)) {
        $message = " Sila masukkan emel sistem yang sah.";
        $message_type = 'error';
    } elseif ($email_input !== $registered_email) {
        $message = " Emel yang dimasukkan tidak sama dengan emel berdaftar dalam sistem.";
        $message_type = 'error';
    } elseif (!password_verify($password_input, (string) ($user['password'] ?? ''))) {
        $message = " Kata laluan tidak betul.";
        $message_type = 'error';
    } else {
        $token = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
        $expires_at = date('Y-m-d H:i:s', strtotime('+' . getPasswordResetExpiryMinutes() . ' minutes'));
        $mail_result = sendSignatureChangeOtpEmail($registered_email, $token, $expires_at, $user['fullname'] ?? '');

        if (!empty($mail_result['success'])) {
            $_SESSION['signature_upload_otp'] = [
                'user_id' => $user_id,
                'email' => $registered_email,
                'token' => $token,
                'expires_at' => $expires_at,
                'verified' => false,
            ];
            $message = " OTP telah dihantar ke emel sistem anda. Sila semak inbox atau spam.";
            $message_type = 'success';
        } else {
            $mail_error = trim((string) ($mail_result['message'] ?? ''));
            $message = " OTP tidak dapat dihantar ke emel. " . ($mail_error !== '' ? "Punca: {$mail_error}" : "Sila semak tetapan SMTP.");
            $message_type = 'error';
        }
    }
}

// PROSES SEMAK OTP TUKAR TANDATANGAN
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_signature_otp'])) {
    $otp_data = getSignatureOtpSession($user_id);
    $token_input = preg_replace('/\D+/', '', (string) ($_POST['signature_otp'] ?? ''));

    if (empty($otp_data)) {
        $message = " OTP telah tamat tempoh. Sila minta OTP baharu.";
        $message_type = 'error';
    } elseif ($token_input === '' || !hash_equals((string) ($otp_data['token'] ?? ''), $token_input)) {
        $message = " OTP salah. Sila semak semula OTP 6 digit yang dihantar ke emel.";
        $message_type = 'error';
    } else {
        $_SESSION['signature_upload_otp']['verified'] = true;
        $_SESSION['signature_upload_otp']['verified_until'] = date('Y-m-d H:i:s', strtotime('+10 minutes'));
        $message = " OTP berjaya disahkan. Anda boleh upload tandatangan baharu sekarang.";
        $message_type = 'success';
    }
}

// PROSES UPDATE MAKLUMAT DIRI
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $fullname = trim((string) ($_POST['fullname'] ?? ''));
    $short_name = trim((string) ($_POST['short_name'] ?? ''));
    $email = trim((string) ($_POST['email'] ?? ''));
    
    // Semak jika email sudah digunakan oleh user lain
    $check_email = mysqli_prepare($conn, "SELECT id FROM users WHERE email = ? AND id != ?");
    mysqli_stmt_bind_param($check_email, "si", $email, $user_id);
    mysqli_stmt_execute($check_email);
    $result_email = mysqli_stmt_get_result($check_email); // Simpan result dahulu
    
    // GUNA mysqli_num_rows() untuk mysqli_result (BUKAN mysqli_stmt_num_rows)
    if ($fullname === '' || $short_name === '') {
        $message = " Sila isi nama penuh dan nama pendek!";
        $message_type = 'error';
    } elseif (mysqli_num_rows($result_email) > 0) {
        $message = " Emel ini sudah digunakan oleh pengguna lain!";
        $message_type = 'error';
    } else {
        $update = mysqli_prepare($conn, "UPDATE users SET fullname=?, short_name=?, email=? WHERE id=?");
        mysqli_stmt_bind_param($update, "sssi", $fullname, $short_name, $email, $user_id);
        
        if (mysqli_stmt_execute($update)) {
            // Kemaskini session
            $_SESSION['fullname'] = $fullname;
            $_SESSION['short_name'] = $short_name;
            $_SESSION['email'] = $email;
            logActivity($conn, $user_id, 'update_profile', 'Kemaskini profil sendiri: ' . $fullname . ' (' . $email . ')');
            $message = " Maklumat profil berjaya dikemaskini!";
            $message_type = 'success';
            
            // Refresh user data
            $stmt = mysqli_prepare($conn, "SELECT * FROM users WHERE id = ?");
            mysqli_stmt_bind_param($stmt, "i", $user_id);
            mysqli_stmt_execute($stmt);
            $user = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));
        } else {
            $message = " Ralat sistem: " . mysqli_error($conn);
            $message_type = 'error';
        }
    }
}

// PROSES TUKAR KATA LALUAN
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $current_pass = (string) ($_POST['current_password'] ?? '');
    $new_pass = (string) ($_POST['new_password'] ?? '');
    $confirm_pass = (string) ($_POST['confirm_password'] ?? '');
    
    // Semak password semasa
    $stmt = mysqli_prepare($conn, "SELECT password FROM users WHERE id = ?");
    mysqli_stmt_bind_param($stmt, "i", $user_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $user_data = mysqli_fetch_assoc($result);
    
    if (!password_verify($current_pass, $user_data['password'])) {
        $message = " Kata laluan semasa tidak betul!";
        $message_type = 'error';
    } elseif ($new_pass !== $confirm_pass) {
        $message = " Kata laluan baharu tidak sepadan!";
        $message_type = 'error';
    } else {
        $hashed = password_hash($new_pass, PASSWORD_DEFAULT);
        $update = mysqli_prepare($conn, "UPDATE users SET password=? WHERE id=?");
        mysqli_stmt_bind_param($update, "si", $hashed, $user_id);
        
        if (mysqli_stmt_execute($update)) {
            logActivity($conn, $user_id, 'change_password', 'Tukar kata laluan akaun sendiri');
            $message = " Kata laluan berjaya ditukar!";
            $message_type = 'success';
        } else {
            $message = " Ralat sistem: " . mysqli_error($conn);
            $message_type = 'error';
        }
    }
}

// PROSES UPLOAD GAMBAR PROFIL
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_photo']) && !empty($_FILES['profile_photo']['name'])) {
    $upload_dir = 'uploads/';
    
    // Pastikan fail uploads wujud
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }
    
    $file = $_FILES['profile_photo'];
    $file_name = basename($file['name']);
    $file_tmp = $file['tmp_name'];
    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
    $allowed_ext = ['jpg', 'jpeg', 'png', 'gif'];
    
    if (!in_array($file_ext, $allowed_ext)) {
        $message = " Hanya fail JPG, JPEG, PNG & GIF dibenarkan!";
        $message_type = 'error';
    } elseif ($file['size'] > 2 * 1024 * 1024) { // Max 2MB
        $message = " Saiz fail tidak boleh melebihi 2MB!";
        $message_type = 'error';
    } else {
        // Generate unique filename
        $new_filename = 'profile_' . $user_id . '_' . time() . '.' . $file_ext;
        $upload_path = $upload_dir . $new_filename;
        
        if (move_uploaded_file($file_tmp, $upload_path)) {
            // Delete old profile photo if exists
            if (isset($user['profile_photo']) && $user['profile_photo'] && file_exists($user['profile_photo'])) {
                unlink($user['profile_photo']);
            }
            
            // Update database
            $update = mysqli_prepare($conn, "UPDATE users SET profile_photo=? WHERE id=?");
            mysqli_stmt_bind_param($update, "si", $upload_path, $user_id);
            mysqli_stmt_execute($update);
            
            $message = " Gambar profil berjaya dikemaskini!";
            $message_type = 'success';
            
            // Refresh user data
            $stmt = mysqli_prepare($conn, "SELECT * FROM users WHERE id = ?");
            mysqli_stmt_bind_param($stmt, "i", $user_id);
            mysqli_stmt_execute($stmt);
            $user = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));
        } else {
            $message = " Gagal memuat naik gambar!";
            $message_type = 'error';
        }
    }
}

// PROSES UPLOAD TANDATANGAN DIGITAL
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_signature']) && !empty($_FILES['signature_file']['name'])) {
    $upload_dir = 'uploads/signatures/';
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    $existing_signature_path = trim((string) ($user['signature_path'] ?? ''));
    $has_existing_signature = $existing_signature_path !== '' && file_exists($existing_signature_path);
    $can_replace_signature = !$has_existing_signature || isSignatureUploadVerified($user_id);

    if (!$can_replace_signature) {
        $message = " Sila sahkan OTP melalui emel sistem sebelum memuat naik tandatangan baharu.";
        $message_type = 'error';
    } else {
        $file = $_FILES['signature_file'];
        $file_name = basename($file['name']);
        $file_tmp = $file['tmp_name'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        $allowed_ext = ['jpg', 'jpeg', 'png', 'webp'];

        if (!in_array($file_ext, $allowed_ext, true)) {
            $message = " Hanya fail JPG, JPEG, PNG & WEBP dibenarkan untuk tandatangan!";
            $message_type = 'error';
        } elseif ($file['size'] > 2 * 1024 * 1024) {
            $message = " Saiz fail tandatangan tidak boleh melebihi 2MB!";
            $message_type = 'error';
        } else {
            $new_filename = 'signature_' . $user_id . '_' . time() . '.' . $file_ext;
            $upload_path = $upload_dir . $new_filename;

            if (move_uploaded_file($file_tmp, $upload_path)) {
                if ($has_existing_signature && file_exists($existing_signature_path)) {
                    unlink($existing_signature_path);
                }

                $update = mysqli_prepare($conn, "UPDATE users SET signature_path=? WHERE id=?");
                mysqli_stmt_bind_param($update, "si", $upload_path, $user_id);
                mysqli_stmt_execute($update);
                logActivity(
                    $conn,
                    $user_id,
                    $has_existing_signature ? 'update_signature' : 'create_signature',
                    ($has_existing_signature ? 'Ubah' : 'Daftar') . ' tandatangan digital sendiri'
                );
                unset($_SESSION['signature_upload_otp']);

                $message = " Tandatangan digital berjaya dikemaskini!";
                $message_type = 'success';

                $stmt = mysqli_prepare($conn, "SELECT * FROM users WHERE id = ?");
                mysqli_stmt_bind_param($stmt, "i", $user_id);
                mysqli_stmt_execute($stmt);
                $user = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));
            } else {
                $message = " Gagal memuat naik tandatangan!";
                $message_type = 'error';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profil Pengguna | MAINPP WORKSPACE</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <?php renderAppShellAssets(); ?>
    <style>
        :root {
            --primary: #0077b6; --primary-dark: #005f99; --secondary: #00b4d8;
            --deep-blue: #023e5f;
            --superadmin: #6c5ce7; --superadmin-dark: #5b4cdb;
            --bg-light: rgba(245, 250, 253, 0.72); --bg-card: rgba(255, 255, 255, 0.68); --text-main: #163447;
            --bg: var(--bg-light); --card: var(--bg-card); --text: var(--text-main);
            --text-muted: #2d5367; --border: rgba(255, 255, 255, 0.48); --sidebar-width: 280px;
            --success: #1a9955; --danger: #dc3545; --warning: #ffc107;
            --glass: rgba(255, 255, 255, 0.58);
            --glass-strong: rgba(255, 255, 255, 0.76);
            --shadow-soft: 0 24px 70px rgba(2, 62, 95, 0.16);
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', 'Inter', Tahoma, Geneva, Verdana, sans-serif; }
        body {
            background:
                linear-gradient(135deg, rgba(245, 250, 253, 0.90), rgba(222, 246, 252, 0.76)),
                url('assets/auth-bg.png') center/cover no-repeat fixed;
            min-height: 100vh;
            display: flex;
            color: var(--text-main);
            overflow-x: hidden;
        }

        body::before,
        body::after {
            content: "";
            position: fixed;
            pointer-events: none;
            z-index: 0;
        }

        body::before {
            width: 42vw;
            height: 42vw;
            right: -16vw;
            top: -18vw;
            border-radius: 50%;
            background: radial-gradient(circle, rgba(0, 180, 216, 0.24), transparent 62%);
            filter: blur(4px);
        }

        body::after {
            width: 48vw;
            height: 48vw;
            left: 120px;
            bottom: -30vw;
            border-radius: 46px;
            background:
                linear-gradient(155deg, rgba(255, 255, 255, 0.20), rgba(255, 255, 255, 0.03)),
                repeating-linear-gradient(0deg, transparent 0 34px, rgba(0, 119, 182, 0.08) 35px 36px);
            border: 1px solid rgba(255, 255, 255, 0.32);
            transform: rotate(-9deg);
        }
        
        /* Sidebar Styles */

        .sidebar { width: var(--sidebar-width); background: linear-gradient(180deg, rgba(2, 62, 95, 0.94), rgba(0, 119, 182, 0.84)), radial-gradient(circle at 22% 8%, rgba(0, 180, 216, 0.28), transparent 32%); border-right: 1px solid rgba(255, 255, 255, 0.22); position: fixed; height: 100vh; padding: 20px 0; overflow-y: auto; overflow-x: hidden; z-index: 1000; box-shadow: 18px 0 44px rgba(2, 38, 60, 0.20); transition: width 0.3s ease; display:flex; flex-direction:column; backdrop-filter: blur(18px) saturate(1.25); -webkit-backdrop-filter: blur(18px) saturate(1.25); }
        .sidebar.collapsed { width: 70px; }
        .sidebar-header { text-align: center; padding: 0 20px 20px; border-bottom: 1px solid rgba(255, 255, 255, 0.16); margin-bottom: 20px; white-space: nowrap; overflow: hidden; background: transparent !important; }
        .sidebar.collapsed .sidebar-header h3, .sidebar.collapsed .sidebar-header p, .sidebar.collapsed .menu-text { display: none; }
        .sidebar-header img { width: 54px; margin-bottom: 10px; transition: margin 0.3s ease; filter: drop-shadow(0 10px 18px rgba(0,0,0,0.25)); }
        .sidebar.collapsed .sidebar-header img { margin: 0 auto 10px; }
        .sidebar-header h3 { font-size: 1rem; font-weight: 800; color: #fff; margin-bottom: 4px; letter-spacing: 0.01em; }
        .sidebar-header p { font-size: 0.75rem; color: rgba(255,255,255,0.72); }
        .role-badge { display: inline-block; padding: 3px 10px; border-radius: 12px; font-size: 0.7rem; font-weight: 600; margin-left: 8px; }
        .role-badge.user { background: #e6f4ff; color: var(--primary); }
        .role-badge.admin { background: #d4edda; color: var(--success); }
        .role-badge.superadmin { background: linear-gradient(90deg, var(--superadmin), var(--superadmin-dark)); color: #fff; }
        .sidebar-menu { list-style: none; padding: 0 10px; display:flex; flex-direction:column; flex:1; }
        .sidebar-section { padding: 10px 18px 6px; color: rgba(255,255,255,0.58); font-size: 0.72rem; font-weight: 800; text-transform: uppercase; letter-spacing: 0.06em; }
        .sidebar-spacer { margin-top: auto; }
        .sidebar-menu li a { display: flex; align-items: center; gap: 12px; padding: 12px 18px; color: rgba(255,255,255,0.88); text-decoration: none; border-radius: 10px; margin-bottom: 5px; transition: all 0.2s ease; font-size: 0.9rem; white-space: nowrap; }
        .sidebar-menu li a:hover, .sidebar-menu li a.active { background: rgba(255,255,255,0.18); color: #fff; box-shadow: inset 0 0 0 1px rgba(255,255,255,0.18); }
        .sidebar-menu li a i { width: 20px; text-align: center; font-size: 1.1rem; }
        .sidebar-menu .dropdown { position: relative; }
        .sidebar-menu .dropdown-toggle { display: flex; align-items: center; justify-content: space-between; width: 100%; padding: 12px 18px; color: rgba(255,255,255,0.88); background: none; border: none; border-radius: 10px; cursor: pointer; font-size: 0.9rem; text-align: left; transition: all 0.2s ease; }
        .sidebar-menu .dropdown-toggle:hover, .sidebar-menu .dropdown-toggle.active { background: rgba(255,255,255,0.18); color: #fff; box-shadow: inset 0 0 0 1px rgba(255,255,255,0.18); }
        .sidebar-menu .dropdown-toggle i.chevron { transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); font-size: 0.8rem; }
        .sidebar-menu .dropdown.active .dropdown-toggle i.chevron { transform: rotate(180deg); }
        .sidebar-menu .dropdown-menu { display: flex; flex-direction: column; padding-left: 42px; margin-top: 4px; max-height: 0; opacity: 0; overflow: hidden; transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.25s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu { max-height: 260px; opacity: 1; }
        .sidebar-menu .dropdown-menu a { padding: 8px 18px; color: rgba(255,255,255,0.78); text-decoration: none; border-radius: 8px; font-size: 0.85rem; display: flex; align-items: center; gap: 8px; opacity: 0; transform: translateY(-5px); transition: opacity 0.2s ease, transform 0.2s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu a { opacity: 1; transform: translateY(0); }
        .sidebar-menu .dropdown-menu a:hover, .sidebar-menu .dropdown-menu a.active { background: rgba(255,255,255,0.16); color: #fff; }
        .sidebar.collapsed + .main { margin-left: 70px; }
        .sidebar-toggle { position: absolute; right: 10px; top: 20px; width: 28px; height: 28px; background: rgba(255,255,255,0.20); color: #fff; border: 1px solid rgba(255,255,255,0.28); border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 0.7rem; box-shadow: 0 10px 22px rgba(0,0,0,0.14); transition: transform 0.3s ease; z-index: 1001; }
        .sidebar.collapsed .sidebar-toggle { transform: rotate(180deg); }
        .main { position: relative; z-index: 1; margin-left: var(--sidebar-width); flex: 1; padding: 28px 32px; transition: margin-left 0.3s ease; }
        .top-bar { background: var(--glass); padding: 18px 24px; border-radius: 18px; box-shadow: var(--shadow-soft); margin-bottom: 18px; display: flex; justify-content: space-between; align-items: center; border: 1px solid var(--border); backdrop-filter: blur(22px) saturate(1.25); -webkit-backdrop-filter: blur(22px) saturate(1.25); }
        .top-bar h2 { color: var(--primary-dark); font-size: 1.35rem; font-weight: 850; display: flex; align-items: center; gap: 10px; }
        .top-bar h2 i { color: var(--secondary); }
        .user-info { display: flex; align-items: center; gap: 15px; font-size: 0.9rem; color: var(--text-muted); }
        .user-info span { color: var(--primary); font-weight: 600; }
        .user-info a { color: var(--danger); text-decoration: none; font-weight: 500; display: flex; align-items: center; gap: 5px; }
        .user-info a:hover { text-decoration: underline; }
        
        /* Profile Page Styles */
        .profile-container { display: grid; grid-template-columns: minmax(260px, 320px) minmax(0, 1fr); gap: 22px; max-width: 1120px; margin: 0 auto; align-items: start; }
        
        /* Profile Card */
        .profile-card, .form-section { background: var(--glass); border-radius: 22px; box-shadow: var(--shadow-soft); border: 1px solid var(--border); backdrop-filter: blur(24px) saturate(1.25); -webkit-backdrop-filter: blur(24px) saturate(1.25); }
        .profile-card { padding: 24px; text-align: center; position: sticky; top: 24px; }
        .profile-photo { width: 136px; height: 136px; border-radius: 50%; object-fit: cover; border: 4px solid rgba(0, 180, 216, 0.84); margin: 0 auto 18px; display: block; background: #f8fafc; box-shadow: 0 18px 34px rgba(2,62,95,0.16); }
        .profile-photo-placeholder { width: 136px; height: 136px; border-radius: 50%; background: linear-gradient(135deg, var(--primary), var(--secondary)); display: flex; align-items: center; justify-content: center; color: #fff; font-size: 2.8rem; margin: 0 auto 18px; }
        .profile-card h3 { color: var(--primary-dark); font-size: 1.08rem; line-height: 1.35; font-weight: 850; }
        .profile-card h3 { margin-bottom: 10px; }
        .profile-meta { color: var(--text-muted); font-size: 0.9rem; font-weight: 650; }
        .profile-role-badge { margin-top:10px;display:inline-block; }
        .signature-preview { min-height: 82px; border: 1px dashed rgba(0,119,182,0.28); border-radius: 14px; background: rgba(255,255,255,0.56); display: flex; align-items: center; justify-content: center; padding: 12px; margin-top: 18px; }
        .signature-preview img { max-width: 190px; max-height: 70px; object-fit: contain; }
        .signature-preview.empty { color: var(--text-muted); font-size: 0.84rem; }
        .upload-form { margin-top: 15px; }
        .upload-form input[type="file"] { display: none; }
        .upload-label { display: inline-flex; align-items: center; justify-content: center; gap: 7px; padding: 9px 14px; background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; border-radius: 999px; cursor: pointer; font-size: 0.84rem; font-weight: 800; transition: transform 0.2s ease, filter 0.2s ease; }
        .upload-label:hover { transform: translateY(-1px); filter: brightness(1.04); }
        .upload-filename { display: block; margin-top: 8px; font-size: 0.8rem; color: var(--text-muted); font-weight: 650; }
        .signature-modal-overlay { position: fixed; inset: 0; z-index: 3000; display: none; align-items: center; justify-content: center; padding: 24px; background: rgba(15, 23, 42, 0.52); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); }
        .signature-modal-overlay.is-open { display: flex; }
        body.signature-modal-open { overflow: hidden; }
        .signature-security { width: min(100%, 440px); max-height: min(86vh, 680px); overflow-y: auto; padding: 22px; border: 1px solid rgba(255,255,255,0.52); border-radius: 22px; background: rgba(255,255,255,0.78); text-align: left; box-shadow: 0 30px 90px rgba(2, 38, 60, 0.26); backdrop-filter: blur(24px) saturate(1.25); -webkit-backdrop-filter: blur(24px) saturate(1.25); }
        .signature-modal-header { display: flex; align-items: flex-start; justify-content: space-between; gap: 14px; margin-bottom: 14px; }
        .signature-security h4 { color: var(--primary-dark); font-size: 1rem; margin-bottom: 4px; display: flex; align-items: center; gap: 7px; }
        .signature-security p { color: var(--text-muted); font-size: 0.84rem; line-height: 1.5; margin-bottom: 0; }
        .signature-close { width: 34px; height: 34px; border: 1px solid rgba(0,119,182,0.16); border-radius: 12px; background: rgba(255,255,255,0.68); color: var(--text-main); cursor: pointer; display: inline-flex; align-items: center; justify-content: center; }
        .signature-close:hover { background: #eef6fb; color: var(--primary-dark); }
        .signature-security .form-group { margin-bottom: 10px; }
        .signature-security .form-group label { font-size: 0.8rem; }
        .signature-security input:not([type="file"]) { width: 100%; padding: 10px 12px; border: 1px solid rgba(0,119,182,0.18); border-radius: 12px; font-size: 0.86rem; background: rgba(255,255,255,0.78); color: var(--text-main); }
        .signature-security input[type="file"] { display: none; }
        .signature-security .btn { width: 100%; justify-content: center; padding: 9px 12px; font-size: 0.84rem; }
        .signature-save-btn { margin-top: 10px; }
        .signature-toggle { margin-top: 14px; width: 100%; justify-content: center; padding: 10px 14px; }
        .signature-step { padding-top: 12px; margin-top: 12px; border-top: 1px solid rgba(0,119,182,0.14); }
        .signature-step:first-of-type { padding-top: 0; margin-top: 0; border-top: 0; }
        .signature-verified { margin-top: 12px; padding: 10px 12px; background: #ecfdf3; border: 1px solid #bbf7d0; color: #166534; border-radius: 10px; font-size: 0.82rem; text-align: left; line-height: 1.45; }
        .signature-modal-alert { margin-bottom: 12px; }
        
        /* Form Sections */
        .profile-form-stack { display: grid; gap: 18px; }
        .form-section { padding: 22px; margin-bottom: 0; }
        .form-section h3 { color: var(--primary-dark); font-size: 1.08rem; margin-bottom: 18px; padding-bottom: 12px; border-bottom: 1px solid rgba(0,119,182,0.14); display: flex; align-items: center; gap: 8px; font-weight: 850; }
        .form-section h3 i { color: var(--secondary); }
        .profile-form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px 16px; }
        .profile-form-grid .full-row { grid-column: 1 / -1; }
        .form-group { margin-bottom: 0; }
        .form-group label { display: block; margin-bottom: 6px; font-weight: 700; color: var(--text-main); font-size: 0.88rem; }
        .form-group input, .form-group select { width: 100%; padding: 11px 14px; border: 1px solid rgba(0,119,182,0.18); border-radius: 12px; font-size: 0.92rem; background: rgba(255,255,255,0.78); color: var(--text-main); }
        .form-group input:focus, .form-group select:focus { border-color: var(--primary); outline: none; box-shadow: 0 0 0 4px rgba(0,119,182,0.13); background: #fff; }
        .form-group input[readonly] { background: rgba(236, 244, 248, 0.72); color: var(--text-muted); cursor: not-allowed; }
        .pass-wrapper { position: relative; }
        .pass-wrapper input { padding-right: 44px; }
        .toggle-pass { position: absolute; right: 14px; top: 50%; transform: translateY(-50%); width: 22px; height: 22px; border: 0; background: transparent; color: var(--text-muted); padding: 0; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; }
        .toggle-pass svg { width: 20px; height: 20px; fill: currentColor; transition: color 0.2s ease; }
        .toggle-pass:hover { color: var(--primary); }
        .form-actions { display: flex; gap: 12px; margin-top: 18px; justify-content: flex-end; }
        .btn { padding: 10px 18px; border: none; border-radius: 999px; cursor: pointer; font-size: 0.9rem; font-weight: 850; display: inline-flex; align-items: center; gap: 7px; text-decoration: none; transition: transform 0.2s ease, filter 0.2s ease, box-shadow 0.2s ease; }
        .btn-primary { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        .btn-secondary { background: rgba(255,255,255,0.68); color: var(--primary-dark); border: 1px solid rgba(0,119,182,0.16); }
        .btn:hover { transform: translateY(-1px); filter: brightness(1.04); }
        
        /* Messages */
        .alert { padding: 12px 16px; border-radius: 14px; margin: 0 auto 18px; max-width: 1120px; font-weight: 650; }
        .alert-success { background: #d4edda; color: #155724; border-left: 4px solid var(--success); }
        .alert-error { background: #f8d7da; color: #721c24; border-left: 4px solid var(--danger); }
        
        /* Footer */
        .page-footer { text-align: center; padding: 20px; color: var(--text-muted); font-size: 0.8rem; margin-top: 30px; }

        @media (max-width: 992px) {
            .sidebar { width: 70px; }
            .sidebar .sidebar-header h3, .sidebar .sidebar-header p, .sidebar .menu-text, .sidebar .role-badge, .sidebar .dropdown-menu, .sidebar .sidebar-section { display: none; }
            .main { margin-left: 70px; }
            .sidebar-toggle { display: none; }
            .profile-container { grid-template-columns: 1fr; }
            .profile-card { position: static; }
        }
        @media (max-width: 640px) {
            .main { padding: 18px 16px; }
            .profile-form-grid { grid-template-columns: 1fr; }
            .form-actions { justify-content: stretch; }
            .btn { width: 100%; justify-content: center; }
        }
        .sidebar {
            overflow: hidden;
        }
        .sidebar-header {
            flex: 0 0 auto;
        }
        .sidebar-menu {
            flex: 1 1 auto;
            min-height: 0;
            overflow-y: auto;
            overflow-x: hidden;
            padding-bottom: 0;
            overscroll-behavior: contain;
            scrollbar-width: thin;
            scrollbar-color: #8f8f8f transparent;
        }
        .sidebar-menu::-webkit-scrollbar {
            width: 10px;
        }
        .sidebar-menu::-webkit-scrollbar-track {
            background: transparent;
        }
        .sidebar-menu::-webkit-scrollbar-thumb {
            background: #8f8f8f;
            border-radius: 999px;
            border: 2px solid transparent;
            background-clip: content-box;
        }
        .sidebar-menu::-webkit-scrollbar-button {
            display: none;
            width: 0;
            height: 0;
        }
    
        /* Button hover animation */
        .main .btn,
        .main .tab-btn,
        .main .action-btn,
        .main .btn-action,
        .main .filter-btn,
        .main .button,
        .main .generate-closing-btn,
        .main .attachment-remove-btn,
        .main .page-add-btn,
        .main .page-delete-btn,
        .main .delete-current-page-btn,
        .main .form-actions a,
        .main .form-actions button,
        .main .filter-actions a,
        .main .filter-actions button,
        .main .document-command a,
        .main .document-command button,
        .main table a[class*="btn"],
        .main table button[class*="btn"],
        .main input[type="submit"],
        .main input[type="button"] {
            transition: transform 0.2s ease, filter 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease, border-color 0.2s ease !important;
            will-change: transform;
        }

        .main .btn:hover:not(:disabled),
        .main .tab-btn:hover:not(:disabled),
        .main .action-btn:hover:not(:disabled),
        .main .btn-action:hover:not(:disabled),
        .main .filter-btn:hover:not(:disabled),
        .main .button:hover:not(:disabled),
        .main .generate-closing-btn:hover:not(:disabled),
        .main .attachment-remove-btn:hover:not(:disabled),
        .main .page-add-btn:hover:not(:disabled),
        .main .page-delete-btn:hover:not(:disabled),
        .main .delete-current-page-btn:hover:not(:disabled),
        .main .form-actions a:hover,
        .main .form-actions button:hover:not(:disabled),
        .main .filter-actions a:hover,
        .main .filter-actions button:hover:not(:disabled),
        .main .document-command a:hover,
        .main .document-command button:hover:not(:disabled),
        .main table a[class*="btn"]:hover,
        .main table button[class*="btn"]:hover:not(:disabled),
        .main input[type="submit"]:hover:not(:disabled),
        .main input[type="button"]:hover:not(:disabled) {
            transform: translateY(-1px);
            filter: brightness(1.04);
            box-shadow: 0 14px 28px rgba(0, 119, 182, 0.18);
        }

        .main .btn:active:not(:disabled),
        .main .tab-btn:active:not(:disabled),
        .main .action-btn:active:not(:disabled),
        .main .btn-action:active:not(:disabled),
        .main .filter-btn:active:not(:disabled),
        .main .button:active:not(:disabled),
        .main .generate-closing-btn:active:not(:disabled),
        .main .attachment-remove-btn:active:not(:disabled),
        .main .page-add-btn:active:not(:disabled),
        .main .page-delete-btn:active:not(:disabled),
        .main .delete-current-page-btn:active:not(:disabled),
        .main .form-actions a:active,
        .main .form-actions button:active:not(:disabled),
        .main .filter-actions a:active,
        .main .filter-actions button:active:not(:disabled),
        .main .document-command a:active,
        .main .document-command button:active:not(:disabled),
        .main table a[class*="btn"]:active,
        .main table button[class*="btn"]:active:not(:disabled),
        .main input[type="submit"]:active:not(:disabled),
        .main input[type="button"]:active:not(:disabled) {
            transform: translateY(0);
            filter: brightness(0.98);
        }</style>
</head>
<body class="role-<?= htmlspecialchars($role) ?>">

    <!-- SIDEBAR -->
    <aside class="sidebar" id="sidebar">
        <button class="sidebar-toggle" id="sidebarToggle" title="Tutup/Buka Menu">
            <i class="fas fa-chevron-left"></i>
        </button>
        <div class="sidebar-header">
            <img src="mainpp.png" alt="Logo MAINPP">
            <h3>MAINPP WORKSPACE</h3>
        </div>
        <ul class="sidebar-menu">
            <?php renderUnifiedSidebarMenu($conn, $role, 'profile_pengguna.php'); ?>
        </ul>
    </aside>

    <!-- MAIN CONTENT -->
    <main class="main">
        <div class="top-bar">
            <h2><i class="fas fa-user"></i> Profil Pengguna</h2>
            <?php renderTopBarUserMenu($conn, $role, 'profile_pengguna.php'); ?>
        </div>

        <?php
        renderBreadcrumb([
            ['label' => 'Dashboard', 'url' => 'dashboard.php'],
            ['label' => 'Profil Pengguna', 'url' => 'profile_pengguna.php', 'current' => true]
        ]);
        ?>

        <!-- MESSAGES -->
        <?php if ($message): ?>
        <div class="alert alert-<?= $message_type ?>">
            <?= htmlspecialchars($message) ?>
        </div>
        <?php endif; ?>

        <div class="profile-container">
            
            <!-- PROFILE PHOTO SECTION -->
            <div class="profile-card">
                <?php if (isset($user['profile_photo']) && $user['profile_photo'] && file_exists($user['profile_photo'])): ?>
                    <img src="<?= htmlspecialchars($user['profile_photo']) ?>" alt="Profil" class="profile-photo">
                <?php else: ?>
                    <div class="profile-photo-placeholder">
                        <i class="fas fa-user"></i>
                    </div>
                <?php endif; ?>
                
                <h3><?= htmlspecialchars($user['fullname']) ?></h3>
                <p class="profile-meta"><?= htmlspecialchars($user['department']) ?></p>
                <span class="role-badge profile-role-badge <?= htmlspecialchars($role) ?>"><?= ucfirst($role) ?></span>
                
                <form method="POST" enctype="multipart/form-data" class="upload-form">
                    <label class="upload-label" for="profile_photo">
                        <i class="fas fa-camera"></i> Tukar Gambar
                    </label>
                    <input type="file" name="profile_photo" id="profile_photo" accept="image/*" onchange="this.form.submit()">
                    <input type="hidden" name="upload_photo" value="1">
                    <span class="upload-filename" id="filename">JPG, PNG, GIF (Max 2MB)</span>
                </form>

                <?php
                $signature_path = trim((string) ($user['signature_path'] ?? ''));
                $has_signature = $signature_path !== '' && file_exists($signature_path);
                $signature_otp_data = getSignatureOtpSession($user_id);
                $signature_upload_verified = isSignatureUploadVerified($user_id);
                $signature_workflow_open = !empty($signature_otp_data)
                    || $signature_upload_verified
                    || ($_SERVER['REQUEST_METHOD'] === 'POST' && (
                        isset($_POST['request_signature_otp'])
                        || isset($_POST['verify_signature_otp'])
                        || isset($_POST['upload_signature'])
                    ));
                ?>
                <div class="signature-preview <?= $has_signature ? '' : 'empty' ?>">
                    <?php if ($has_signature): ?>
                        <img src="<?= htmlspecialchars($signature_path) ?>" alt="Tandatangan Digital">
                    <?php else: ?>
                        Tandatangan belum didaftarkan
                    <?php endif; ?>
                </div>
                <button type="button" class="btn btn-secondary signature-toggle" id="signatureToggle" aria-controls="signatureModal" aria-expanded="<?= $signature_workflow_open ? 'true' : 'false' ?>">
                    <i class="fas fa-signature"></i> <?= $has_signature ? 'Tukar Tandatangan' : 'Daftar Tandatangan' ?>
                </button>

                <div class="signature-modal-overlay <?= $signature_workflow_open ? 'is-open' : '' ?>" id="signatureModal" aria-hidden="<?= $signature_workflow_open ? 'false' : 'true' ?>">
                    <div class="signature-security" role="dialog" aria-modal="true" aria-labelledby="signatureModalTitle">
                        <div class="signature-modal-header">
                            <div>
                                <h4 id="signatureModalTitle"><i class="fas fa-shield-halved"></i> <?= $has_signature ? 'Tukar Tandatangan' : 'Daftar Tandatangan' ?></h4>
                            </div>
                    <button type="button" class="signature-close" id="signatureModalClose" title="Tutup borang tandatangan" aria-label="Tutup borang tandatangan">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>

                        <?php if ($message && ($_SERVER['REQUEST_METHOD'] === 'POST') && (isset($_POST['request_signature_otp']) || isset($_POST['verify_signature_otp']) || isset($_POST['upload_signature']))): ?>
                        <div class="alert alert-<?= htmlspecialchars($message_type) ?> signature-modal-alert">
                            <?= htmlspecialchars($message) ?>
                        </div>
                        <?php endif; ?>

                        <form method="POST" enctype="multipart/form-data">
                            <?php if ($has_signature): ?>
                            <div class="signature-step">
                                <div class="form-group">
                                    <label>Emel Sistem</label>
                                    <input type="email" name="signature_email" value="<?= htmlspecialchars($user['email'] ?? '') ?>" autocomplete="email">
                                </div>
                                <div class="form-group">
                                    <label>Kata Laluan</label>
                                    <div class="pass-wrapper">
                                        <input type="password" name="signature_password" id="signaturePassword" autocomplete="current-password">
                                        <button type="button" class="toggle-pass" onclick="togglePass('signaturePassword', this)" aria-label="Papar atau sembunyi kata laluan">
                                            <svg viewBox="0 0 24 24"><path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/></svg>
                                        </button>
                                    </div>
                                </div>
                                <button type="submit" name="request_signature_otp" class="btn btn-secondary">
                                    <i class="fas fa-envelope"></i> Dapatkan OTP
                                </button>
                            </div>

                            <?php if (!empty($signature_otp_data) || $signature_upload_verified): ?>
                            <div class="signature-step">
                                <div class="form-group">
                                    <label>OTP 6 Digit</label>
                                    <input type="text" name="signature_otp" inputmode="numeric" maxlength="6" placeholder="Masukkan OTP">
                                </div>
                                <button type="submit" name="verify_signature_otp" class="btn btn-primary">
                                    <i class="fas fa-check"></i> Sahkan OTP
                                </button>
                            </div>
                            <?php endif; ?>
                            <?php endif; ?>

                            <?php if (!$has_signature || $signature_upload_verified): ?>
                            <?php if ($signature_upload_verified): ?>
                            <div class="signature-verified">
                                <i class="fas fa-circle-check"></i> OTP telah disahkan. Upload tandatangan baharu dalam masa 10 minit.
                            </div>
                            <?php endif; ?>
                            <div class="signature-step">
                                <label class="upload-label" for="signature_file_panel">
                                    <i class="fas fa-signature"></i> <?= $has_signature ? 'Upload Tandatangan Baru' : 'Upload Tandatangan' ?>
                                </label>
                                <input type="file" name="signature_file" id="signature_file_panel" accept=".png,.jpg,.jpeg,.webp,image/png,image/jpeg,image/webp" onchange="this.form.submit()">
                                <input type="hidden" name="upload_signature" value="1">
                                <button type="submit" name="upload_signature" value="1" class="btn btn-primary signature-save-btn">
                                    <i class="fas fa-upload"></i> Simpan Tandatangan
                                </button>
                                <span class="upload-filename">PNG, JPG, WEBP (Max 2MB)</span>
                            </div>
                            <?php endif; ?>
                        </form>
                    </div>
                </div>
            </div>

            <!-- PROFILE FORM SECTION -->
            <div class="profile-form-stack">
                <!-- Maklumat Diri -->
                <div class="form-section">
                    <h3><i class="fas fa-id-card"></i> Maklumat Diri</h3>
                    <form method="POST">
                        <div class="profile-form-grid">
                            <div class="form-group">
                                <label>Nama Penuh</label>
                                <input type="text" name="fullname" value="<?= htmlspecialchars($user['fullname']) ?>" required>
                            </div>
                            <div class="form-group">
                                <label>Nama Panggilan</label>
                                <input type="text" name="short_name" value="<?= htmlspecialchars($user['short_name'] ?? '') ?>" maxlength="100" required>
                            </div>
                            <div class="form-group">
                                <label>Emel</label>
                                <input type="email" name="email" value="<?= htmlspecialchars($user['email']) ?>" required>
                            </div>
                            <div class="form-group">
                                <label>No. Kad Pengenalan</label>
                                <input type="text" value="<?= htmlspecialchars($user['ic_number']) ?>" readonly>
                            </div>
                            <div class="form-group">
                                <label>Bahagian</label>
                                <input type="text" value="<?= htmlspecialchars($user['department'] ?? '-') ?>" readonly>
                            </div>
                            <div class="form-group">
                                <label>Jawatan</label>
                                <input type="text" value="<?= htmlspecialchars($user['position'] ?? '-') ?>" readonly>
                            </div>
                        </div>
                        <div class="form-actions">
                            <button type="submit" name="update_profile" class="btn btn-primary">
                                Simpan Profil
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Tukar Kata Laluan -->
                <div class="form-section">
                    <h3><i class="fas fa-key"></i> Tukar Kata Laluan</h3>
                    <form method="POST">
                        <div class="profile-form-grid">
                            <div class="form-group">
                                <label>Kata Laluan Semasa</label>
                                <div class="pass-wrapper">
                                    <input type="password" name="current_password" id="currentPassword" required>
                                    <button type="button" class="toggle-pass" onclick="togglePass('currentPassword', this)" aria-label="Papar atau sembunyi kata laluan">
                                        <svg viewBox="0 0 24 24"><path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/></svg>
                                    </button>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Kata Laluan Baharu</label>
                                <div class="pass-wrapper">
                                    <input type="password" name="new_password" id="newPassword" required>
                                    <button type="button" class="toggle-pass" onclick="togglePass('newPassword', this)" aria-label="Papar atau sembunyi kata laluan">
                                        <svg viewBox="0 0 24 24"><path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/></svg>
                                    </button>
                                </div>
                            </div>
                            <div class="form-group full-row">
                                <label>Sahkan Kata Laluan Baharu</label>
                                <div class="pass-wrapper">
                                    <input type="password" name="confirm_password" id="confirmPassword" required>
                                    <button type="button" class="toggle-pass" onclick="togglePass('confirmPassword', this)" aria-label="Papar atau sembunyi kata laluan">
                                        <svg viewBox="0 0 24 24"><path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/></svg>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="form-actions">
                            <button type="submit" name="change_password" class="btn btn-primary">
                                Tukar Kata Laluan
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="page-footer">
            Hakcipta Terpelihara &copy; <?= date('Y') ?> Majlis Agama Islam Negeri Pulau Pinang.
        </div>
    </main>

    <script>
                const sidebar = document.getElementById('sidebar');
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', () => sidebar.classList.toggle('collapsed'));
        }
        if (window.innerWidth < 992) sidebar.classList.add('collapsed');

        document.querySelectorAll('.sidebar-menu .dropdown-toggle, .dropdown-toggle').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                const dropdown = this.parentElement;
                const isActive = dropdown.classList.contains('active');
                document.querySelectorAll('.sidebar-menu .dropdown, .dropdown').forEach(item => {
                    if (item !== dropdown) item.classList.remove('active');
                });
                dropdown.classList.toggle('active', !isActive);
            });
        });
        function confirmLogout() { return confirm("Adakah anda pasti ingin log keluar?"); }

        function togglePass(inputId, btn) {
            const input = document.getElementById(inputId);
            if (!input || !btn) return;

            const isPass = input.type === 'password';
            input.type = isPass ? 'text' : 'password';
            const openIcon = '<svg viewBox="0 0 24 24"><path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/></svg>';
            const closedIcon = '<svg viewBox="0 0 24 24"><path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/></svg>';
            btn.innerHTML = isPass ? openIcon : closedIcon;
        }

        const signatureToggle = document.getElementById('signatureToggle');
        const signatureModal = document.getElementById('signatureModal');
        const signatureModalClose = document.getElementById('signatureModalClose');

        function setSignatureModalOpen(isOpen) {
            if (!signatureModal) return;
            signatureModal.classList.toggle('is-open', isOpen);
            signatureModal.setAttribute('aria-hidden', isOpen ? 'false' : 'true');
            document.body.classList.toggle('signature-modal-open', isOpen);
            if (signatureToggle) {
                signatureToggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
            }
        }

        if (signatureToggle && signatureModal) {
            setSignatureModalOpen(signatureModal.classList.contains('is-open'));
            signatureToggle.addEventListener('click', function() {
                setSignatureModalOpen(true);
            });
        }

        if (signatureModalClose) {
            signatureModalClose.addEventListener('click', function() {
                setSignatureModalOpen(false);
            });
        }

        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape' && signatureModal && signatureModal.classList.contains('is-open')) {
                setSignatureModalOpen(false);
            }
        });
    </script>
    <?php renderSessionTimeoutScript(); ?>
</body>
</html>
