<?php
/**
 * settings_photo_card.php — paste this where you want the profile photo control
 * inside your settings page. (Your settings page should already call session_start().)
 *
 * It reads the current photo + name from the session. Drop upload_photo.php in the
 * SAME folder as your settings page (or change UPLOAD_URL in the JS below).
 */
$pp   = $_SESSION['profile_photo'] ?? null;
$name = $_SESSION['name'] ?? 'User';
$ppUrl = $pp ? '/seven-credit-system/assets/profile_photos/'.htmlspecialchars($pp).'?v='.time() : '';
$initial = strtoupper(mb_substr($name, 0, 1));
?>
<style>
.pp-card{max-width:420px;margin:0 auto;background:#fff;border:1px solid #e5e7eb;border-radius:18px;padding:22px;text-align:center;font-family:"Noto Sans Lao","Inter",Arial,sans-serif}
.pp-avatar{position:relative;width:118px;height:118px;margin:0 auto 14px;border-radius:50%;overflow:hidden;background:linear-gradient(135deg,#7f1d1d,#b91c1c);box-shadow:0 4px 18px rgba(0,0,0,.18)}
.pp-avatar img{width:100%;height:100%;object-fit:cover;display:block}
.pp-initial{width:100%;height:100%;display:flex;align-items:center;justify-content:center;color:#fff;font-size:46px;font-weight:800}
.pp-cam{position:absolute;right:4px;bottom:4px;width:34px;height:34px;border-radius:50%;background:#b91c1c;border:3px solid #fff;display:flex;align-items:center;justify-content:center;font-size:16px;color:#fff;cursor:pointer}
.pp-name{font-size:16px;font-weight:800;color:#111827;margin-bottom:2px}
.pp-hint{font-size:12px;color:#6b7280;margin-bottom:16px}
.pp-btn{display:inline-block;padding:11px 22px;background:#b91c1c;color:#fff;border:none;border-radius:12px;font-size:14px;font-weight:800;font-family:inherit;cursor:pointer;transition:opacity .15s}
.pp-btn:hover{opacity:.9}
.pp-btn:disabled{opacity:.6;cursor:default}
.pp-msg{margin-top:12px;font-size:13px;font-weight:600;min-height:18px}
.pp-msg.ok{color:#15803d}
.pp-msg.err{color:#b91c1c}
.pp-spin{display:inline-block;width:14px;height:14px;border:2px solid rgba(255,255,255,.5);border-top-color:#fff;border-radius:50%;animation:ppspin .7s linear infinite;vertical-align:-2px;margin-right:6px}
@keyframes ppspin{to{transform:rotate(360deg)}}
</style>

<div class="pp-card">
    <div class="pp-avatar" id="ppAvatar" onclick="document.getElementById('ppFile').click()">
        <?php if ($ppUrl): ?>
            <img id="ppImg" src="<?= $ppUrl ?>" alt="Profile photo">
        <?php else: ?>
            <div class="pp-initial" id="ppInitial"><?= $initial ?></div>
        <?php endif; ?>
        <div class="pp-cam">📷</div>
    </div>
    <div class="pp-name"><?= htmlspecialchars($name) ?></div>
    <div class="pp-hint">JPG, PNG or WEBP · up to 5&nbsp;MB</div>

    <input type="file" id="ppFile" accept="image/jpeg,image/png,image/webp" style="display:none">
    <button type="button" class="pp-btn" id="ppBtn" onclick="document.getElementById('ppFile').click()">Change photo</button>
    <div class="pp-msg" id="ppMsg"></div>
</div>

<script>
(function(){
    const UPLOAD_URL = 'upload_photo.php';   // change to an absolute path if needed
    const file   = document.getElementById('ppFile');
    const btn    = document.getElementById('ppBtn');
    const msg    = document.getElementById('ppMsg');
    const avatar = document.getElementById('ppAvatar');

    function setMsg(text, type){ msg.textContent = text || ''; msg.className = 'pp-msg' + (type ? ' '+type : ''); }

    function showPreview(url){
        let img = document.getElementById('ppImg');
        if(!img){
            const init = document.getElementById('ppInitial');
            if(init) init.remove();
            img = document.createElement('img');
            img.id = 'ppImg';
            avatar.insertBefore(img, avatar.firstChild);
        }
        img.src = url;
    }

    file.addEventListener('change', async function(){
        const f = file.files[0];
        if(!f) return;

        // client-side checks
        if(!['image/jpeg','image/png','image/webp'].includes(f.type)){
            setMsg('Please choose a JPG, PNG or WEBP image.', 'err'); file.value=''; return;
        }
        if(f.size > 5*1024*1024){
            setMsg('Please choose an image under 5 MB.', 'err'); file.value=''; return;
        }

        // instant local preview
        const localUrl = URL.createObjectURL(f);
        showPreview(localUrl);

        // upload
        btn.disabled = true;
        setMsg('Uploading…', '');
        btn.innerHTML = '<span class="pp-spin"></span>Uploading…';
        try{
            const fd = new FormData();
            fd.append('photo', f);
            const res = await fetch(UPLOAD_URL, { method:'POST', body: fd, credentials:'same-origin' });
            const data = await res.json().catch(()=>null);
            if(res.ok && data && data.ok){
                showPreview(data.url + '?v=' + Date.now());   // server copy, cache-busted
                setMsg('Photo updated ✓', 'ok');
                // update any other avatars on the page (e.g. header)
                document.querySelectorAll('[data-user-photo]').forEach(el=>{
                    if(el.tagName==='IMG') el.src = data.url + '?v=' + Date.now();
                });
            }else{
                setMsg((data && data.error) ? data.error : 'Upload failed ('+res.status+').', 'err');
            }
        }catch(e){
            setMsg('Network error — please try again.', 'err');
        }finally{
            URL.revokeObjectURL(localUrl);
            btn.disabled = false;
            btn.textContent = 'Change photo';
            file.value = '';
        }
    });
})();
</script>