<?php
/**
 * profile_photo.php — the page that "Profile Photo" in Settings should open.
 * Put this in the SAME folder as your settings page (e.g. /seven-credit-system/customer/).
 * Point the Settings "Profile Photo" row at it:  href="profile_photo.php"
 *
 * It both shows the uploader AND saves the photo (posts to itself), so no other file is needed.
 */

session_start();

$ROOT      = rtrim($_SERVER['DOCUMENT_ROOT'], '/').'/seven-credit-system';
$PHOTO_DIR = $ROOT.'/assets/profile_photos';
$PHOTO_WEB = '/seven-credit-system/assets/profile_photos';

// fall back to a path relative to this script if DOCUMENT_ROOT doesn't resolve
if (!is_dir($PHOTO_DIR)) {
    foreach ([
        __DIR__.'/../assets/profile_photos',
        __DIR__.'/../../assets/profile_photos',
        __DIR__.'/assets/profile_photos',
    ] as $cand) {
        if (is_dir($cand)) { $PHOTO_DIR = $cand; break; }
    }
}

require_once $ROOT.'/config/database.php';   // provides $pdo

/* ───────────────────────────── handle the upload (AJAX POST to self) ───────────────────────────── */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json; charset=utf-8');

    $fail = function ($msg, $code = 400) {
        http_response_code($code);
        echo json_encode(['ok' => false, 'error' => $msg]);
        exit;
    };

    if (empty($_SESSION['user_id']))            $fail('You are not logged in.', 401);
    if (!isset($_FILES['photo']))               $fail('No file was received.');

    $userId = (int) $_SESSION['user_id'];
    $f = $_FILES['photo'];

    if ($f['error'] !== UPLOAD_ERR_OK) {
        $map = [
            UPLOAD_ERR_INI_SIZE  => 'The file is larger than the server allows.',
            UPLOAD_ERR_FORM_SIZE => 'The file is too large.',
            UPLOAD_ERR_PARTIAL   => 'The upload was interrupted, please try again.',
            UPLOAD_ERR_NO_FILE   => 'No file was selected.',
        ];
        $fail($map[$f['error']] ?? 'Upload failed (error '.$f['error'].').');
    }
    if ($f['size'] > 5 * 1024 * 1024)           $fail('Please choose an image under 5 MB.');

    $info = @getimagesize($f['tmp_name']);
    if ($info === false)                        $fail('That file is not a valid image.');

    $allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
    $mime = $info['mime'] ?? '';
    if (!isset($allowed[$mime]))                $fail('Please use a JPG, PNG or WEBP image.');
    $ext = $allowed[$mime];

    if (!is_dir($PHOTO_DIR)) @mkdir($PHOTO_DIR, 0775, true);
    @chmod($PHOTO_DIR, 0775);
    if (!is_dir($PHOTO_DIR) || !is_writable($PHOTO_DIR)) {
        $abs = realpath($PHOTO_DIR) ?: $PHOTO_DIR;
        $fail('The server cannot write to the photo folder. Set it writable (chmod 775). Folder on server: '.$abs, 500);
    }

    $filename = 'user_'.$userId.'_'.time().'.'.$ext;
    $dest     = $PHOTO_DIR.'/'.$filename;

    // square-crop to 512px with GD if available, else just move the file
    $saved = false;
    if (function_exists('imagecreatetruecolor')) {
        $src = null;
        if ($mime === 'image/jpeg')  $src = @imagecreatefromjpeg($f['tmp_name']);
        elseif ($mime === 'image/png')  $src = @imagecreatefrompng($f['tmp_name']);
        elseif ($mime === 'image/webp' && function_exists('imagecreatefromwebp')) $src = @imagecreatefromwebp($f['tmp_name']);
        if ($src) {
            $w = imagesx($src); $h = imagesy($src); $side = min($w, $h);
            $sx = (int)(($w - $side) / 2); $sy = (int)(($h - $side) / 2);
            $out = imagecreatetruecolor(512, 512);
            imagealphablending($out, false); imagesavealpha($out, true);
            imagefilledrectangle($out, 0, 0, 512, 512, imagecolorallocatealpha($out, 0, 0, 0, 127));
            imagecopyresampled($out, $src, 0, 0, $sx, $sy, 512, 512, $side, $side);
            if ($ext === 'jpg')  $saved = imagejpeg($out, $dest, 88);
            elseif ($ext === 'png')  $saved = imagepng($out, $dest, 6);
            elseif ($ext === 'webp' && function_exists('imagewebp')) $saved = imagewebp($out, $dest, 88);
            imagedestroy($src); imagedestroy($out);
        }
    }
    if (!$saved && !move_uploaded_file($f['tmp_name'], $dest)) {
        $fail('Could not save the uploaded file.', 500);
    }

    try {
        $stmt = $pdo->prepare('SELECT profile_photo FROM users WHERE id = ?');
        $stmt->execute([$userId]);
        $old = $stmt->fetchColumn();
        $pdo->prepare('UPDATE users SET profile_photo = ? WHERE id = ?')->execute([$filename, $userId]);
    } catch (Throwable $e) {
        @unlink($dest);
        $fail('Database error while saving your photo.', 500);
    }

    $_SESSION['profile_photo'] = $filename;
    if ($old && $old !== $filename && is_file($PHOTO_DIR.'/'.$old)) @unlink($PHOTO_DIR.'/'.$old);

    echo json_encode(['ok' => true, 'url' => $PHOTO_WEB.'/'.$filename]);
    exit;
}

/* ───────────────────────────── render the page ───────────────────────────── */
if (empty($_SESSION['user_id'])) { header('Location: ../auth/login.php'); exit; }

$pp      = $_SESSION['profile_photo'] ?? null;
$name    = $_SESSION['name'] ?? 'User';
$ppUrl   = $pp ? $PHOTO_WEB.'/'.rawurlencode($pp).'?v='.time() : '';
$initial = strtoupper(mb_substr($name, 0, 1));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Profile Photo — Seven Wallet</title>
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;600;700;800&family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
body{font-family:"Noto Sans Lao","Inter",Arial,sans-serif;background:#f3f4f6;-webkit-text-size-adjust:100%;min-height:100vh}
.hdr{background:#b03030;color:#fff;padding:calc(16px + env(safe-area-inset-top)) 18px 16px;display:flex;align-items:center;gap:14px}
.hdr .back{width:38px;height:38px;border:none;background:rgba(255,255,255,.18);border-radius:50%;color:#fff;font-size:20px;cursor:pointer;display:flex;align-items:center;justify-content:center}
.hdr h1{font-size:19px;font-weight:800}
.wrap{padding:22px 18px}
.card{max-width:420px;margin:0 auto;background:#fff;border-radius:18px;padding:26px 22px;text-align:center;box-shadow:0 1px 3px rgba(0,0,0,.06)}
.avatar{position:relative;width:130px;height:130px;margin:0 auto 16px;border-radius:50%;overflow:hidden;background:linear-gradient(135deg,#7f1d1d,#b91c1c);box-shadow:0 6px 22px rgba(0,0,0,.2)}
.avatar img{width:100%;height:100%;object-fit:cover;display:block}
.avatar .initial{width:100%;height:100%;display:flex;align-items:center;justify-content:center;color:#fff;font-size:52px;font-weight:800}
.avatar .cam{position:absolute;right:6px;bottom:6px;width:38px;height:38px;border-radius:50%;background:#b91c1c;border:3px solid #fff;display:flex;align-items:center;justify-content:center;font-size:17px;cursor:pointer}
.name{font-size:17px;font-weight:800;color:#111827}
.hint{font-size:12px;color:#6b7280;margin:4px 0 18px}
.btn{display:inline-block;width:100%;max-width:280px;padding:14px;background:#b91c1c;color:#fff;border:none;border-radius:12px;font-size:15px;font-weight:800;font-family:inherit;cursor:pointer;transition:opacity .15s}
.btn:hover{opacity:.92}.btn:disabled{opacity:.6;cursor:default}
.msg{margin-top:14px;font-size:13px;font-weight:600;min-height:18px}
.msg.ok{color:#15803d}.msg.err{color:#b91c1c}
.spin{display:inline-block;width:14px;height:14px;border:2px solid rgba(255,255,255,.5);border-top-color:#fff;border-radius:50%;animation:sp .7s linear infinite;vertical-align:-2px;margin-right:6px}
@keyframes sp{to{transform:rotate(360deg)}}
</style>
</head>
<body>
<div class="hdr">
    <button class="back" onclick="history.length>1?history.back():location.href='settings.php'">←</button>
    <h1>Profile Photo</h1>
</div>

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

        <input type="file" id="file" accept="image/jpeg,image/png,image/webp" hidden>
        <button class="btn" id="btn" onclick="file.click()">Upload / Change photo</button>
        <div class="msg" id="msg"></div>
    </div>
</div>

<script>
const file=document.getElementById('file'),btn=document.getElementById('btn'),
      msg=document.getElementById('msg'),avatar=document.getElementById('avatar');

function setMsg(t,c){msg.textContent=t||'';msg.className='msg'+(c?' '+c:'');}
function preview(url){
    let img=document.getElementById('img');
    if(!img){const i=document.getElementById('initial');if(i)i.remove();
        img=document.createElement('img');img.id='img';avatar.insertBefore(img,avatar.firstChild);}
    img.src=url;
}

file.addEventListener('change',async()=>{
    const f=file.files[0];if(!f)return;
    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;}

    const local=URL.createObjectURL(f);preview(local);
    btn.disabled=true;btn.innerHTML='<span class="spin"></span>Uploading…';setMsg('');
    try{
        const fd=new FormData();fd.append('photo',f);
        const res=await fetch('profile_photo.php',{method:'POST',body:fd,credentials:'same-origin'});
        const d=await res.json().catch(()=>null);
        if(res.ok&&d&&d.ok){preview(d.url+'?v='+Date.now());setMsg('Photo updated ✓','ok');}
        else setMsg((d&&d.error)?d.error:'Upload failed ('+res.status+').','err');
    }catch(e){setMsg('Network error — please try again.','err');}
    finally{URL.revokeObjectURL(local);btn.disabled=false;btn.textContent='Upload / Change photo';file.value='';}
});
</script>
<?php require __DIR__ . '/../config/auto_update.php'; ?>
</body>
</html>