<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<title>Edit Profile - CV111</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
    body { background: #0a0a0a; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
    .gold-gradient { background: linear-gradient(135deg, #d4af37, #f0d264); }
    .header-bg { background: linear-gradient(160deg, #1a1005 0%, #0a0a0a 80%); }
    .card-bg { background: #141414; }
</style>
</head>
<body class="pb-8">

<header class="header-bg border-b border-gray-800 sticky top-0 z-50">
    <div class="max-w-2xl mx-auto px-4 h-14 flex items-center gap-3">
        <a href="/newprofile.php" class="text-gray-300 text-xl"><i class="fa-solid fa-arrow-left"></i></a>
        <div class="text-white font-bold text-base">Profile Edit করো</div>
    </div>
</header>

<main class="max-w-2xl mx-auto px-4 py-5">

    <div id="msgBox" class="hidden rounded-lg p-3 mb-4 text-xs font-bold text-center"></div>

    <div class="text-center mb-6">
        <div id="currentAvatar" class="w-20 h-20 rounded-full gold-gradient flex items-center justify-center text-3xl font-black text-gray-900 mx-auto">
            <i class="fa-solid fa-user"></i>
        </div>
    </div>

    <!-- ✅ নতুন যোগ — Avatar বেছে নেওয়া -->
    <div class="card-bg rounded-xl p-5 border border-gray-800 mb-4">
        <div class="text-gray-400 text-xs mb-3">Photo Upload করো</div>
        <input type="file" id="photoInput" accept="image/jpeg,image/png,image/webp" style="display:none;" onchange="handlePhotoSelect(event)">
        <button onclick="document.getElementById('photoInput').click()" class="w-full bg-[#0a0a0a] border border-gray-700 rounded-lg py-3 text-gray-300 text-sm font-bold">
            <i class="fa-solid fa-camera mr-1"></i> ছবি বেছে নাও
        </button>
        <div id="uploadStatus" class="text-xs text-gray-500 mt-2"></div>
    </div>

    <div class="card-bg rounded-xl p-5 border border-gray-800">
        <label class="text-gray-400 text-xs mb-1 block">Nickname</label>
        <input type="text" id="nickname" placeholder="তোমার Nickname" class="w-full bg-[#0a0a0a] border border-gray-700 rounded-lg px-4 py-3 text-white text-sm mb-4">
        <button onclick="saveNickname()" id="saveBtn" class="w-full gold-gradient text-gray-900 font-bold py-3 rounded-lg text-sm">Save করো</button>
    </div>

</main>

<script>
const token = localStorage.getItem('token');
if (!token) window.location.href = '/newlogin.php';

try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    document.getElementById('nickname').value = payload.codechorkamukala || '';
} catch (e) {}

// ✅ নতুন যোগ — Page খোলার সাথে সাথেই, আসল Saved Photo দেখানো
async function loadCurrentPhoto() {
    try {
        const res = await fetch('/get_user_photo.php', {
            headers: { 'Authorization': 'Bearer ' + token }
        });
        const data = await res.json();
        if (data.code === 0 && data.photo) {
            document.getElementById('currentAvatar').innerHTML = `<img src="${data.photo}" style="width:100%; height:100%; border-radius:50%; object-fit:cover;">`;
        }
    } catch (e) {}
}
loadCurrentPhoto();

function md5(str) {
    function rotateLeft(n, s) { return (n << s) | (n >>> (32 - s)); }
    function toHex(n) { let s = '', v; for (let i = 0; i < 4; i++) { v = (n >>> (i * 8)) & 255; s += ('0' + v.toString(16)).slice(-2); } return s; }
    function utf8Encode(str) { return unescape(encodeURIComponent(str)); }
    str = utf8Encode(str);
    const msgLen = str.length;
    const numBlocks = (((msgLen + 8) >>> 6) + 1) * 16;
    const M = new Array(numBlocks).fill(0);
    for (let i = 0; i < msgLen; i++) M[i >> 2] |= str.charCodeAt(i) << ((i % 4) * 8);
    M[msgLen >> 2] |= 0x80 << ((msgLen % 4) * 8);
    M[numBlocks - 2] = msgLen * 8;
    let a = 1732584193, b = -271733879, c = -1732584194, d = 271733878;
    const S = [7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21];
    const K = [];
    for (let i = 0; i < 64; i++) K[i] = (Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296)) | 0;
    for (let i = 0; i < numBlocks; i += 16) {
        let A = a, B = b, C = c, D = d;
        for (let j = 0; j < 64; j++) {
            let F, g;
            if (j < 16) { F = (B & C) | (~B & D); g = j; }
            else if (j < 32) { F = (D & B) | (~D & C); g = (5 * j + 1) % 16; }
            else if (j < 48) { F = B ^ C ^ D; g = (3 * j + 5) % 16; }
            else { F = C ^ (B | ~D); g = (7 * j) % 16; }
            F = (F + A + K[j] + (M[i + g] | 0)) | 0;
            A = D; D = C; C = B;
            B = (B + rotateLeft(F, S[j])) | 0;
        }
        a = (a + A) | 0; b = (b + B) | 0; c = (c + C) | 0; d = (d + D) | 0;
    }
    return toHex(a) + toHex(b) + toHex(c) + toHex(d);
}

// ✅ নতুন যোগ — আসল Photo Upload করা
async function handlePhotoSelect(event) {
    const file = event.target.files[0];
    if (!file) return;

    const status = document.getElementById('uploadStatus');
    status.textContent = 'Upload হচ্ছে...';

    // ✅ প্রথমে Preview দেখানো
    const reader = new FileReader();
    reader.onload = (e) => {
        document.getElementById('currentAvatar').innerHTML = `<img src="${e.target.result}" style="width:100%; height:100%; border-radius:50%; object-fit:cover;">`;
    };
    reader.readAsDataURL(file);

    // ✅ Server-এ Upload করা
    const formData = new FormData();
    formData.append('photo', file);

    try {
        const uploadRes = await fetch('/upload_avatar.php', { method: 'POST', body: formData });
        const uploadData = await uploadRes.json();

        if (uploadData.code !== 0) {
            status.textContent = '❌ ' + uploadData.msg;
            return;
        }

        // ✅ Upload সফল হলে, EditUserPhoto.php Call করে Save করা
        const random = Math.random().toString(36).substring(2, 15);
        const language = 0;
        const shonustr = `{"language":${language},"random":"${random}","userPhoto":"${uploadData.url}"}`;
        const signature = md5(shonustr).toUpperCase();

        const saveRes = await fetch('/deepanshu/api/webapi/EditUserPhoto.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
            body: JSON.stringify({ language, random, signature, userPhoto: uploadData.url, timestamp: Date.now() })
        });
        const saveData = await saveRes.json();

        status.textContent = saveData.code === 0 ? '✅ Photo Save হয়েছে!' : '❌ Save ব্যর্থ হয়েছে';
    } catch (e) {
        status.textContent = '❌ একটা সমস্যা হয়েছে।';
    }
}

async function saveNickname() {
    const nick = document.getElementById('nickname').value.trim();
    const msgBox = document.getElementById('msgBox');
    const btn = document.getElementById('saveBtn');

    if (!nick) { alert('Nickname দাও।'); return; }

    btn.textContent = 'Save হচ্ছে...';
    const random = Math.random().toString(36).substring(2, 15);
    const language = 0;
    // ✅ Server-এর ঠিক একই Format-এ Signature তৈরি করা
    const shonustr = `{"language":${language},"nikeName":"${nick}","random":"${random}"}`;
    const signature = md5(shonustr).toUpperCase();

    try {
        const res = await fetch('/deepanshu/api/webapi/EditNickName.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
            body: JSON.stringify({ language, nikeName: nick, random, signature, timestamp: Date.now() })
        });
        const data = await res.json();

        msgBox.classList.remove('hidden');
        if (data.code === 0) {
            msgBox.className = 'rounded-lg p-3 mb-4 text-xs font-bold text-center bg-green-500/10 border border-green-500/40 text-green-400';
            msgBox.textContent = '✅ Nickname Update হয়েছে!';
        } else {
            msgBox.className = 'rounded-lg p-3 mb-4 text-xs font-bold text-center bg-red-500/10 border border-red-500/40 text-red-400';
            msgBox.textContent = '❌ ' + (data.msg || 'Update ব্যর্থ হয়েছে।');
        }
    } catch (e) {
        msgBox.classList.remove('hidden');
        msgBox.textContent = 'একটা সমস্যা হয়েছে।';
    }
    btn.textContent = 'Save করো';
}
</script>

</body>
</html>
