<?php
/**
 * سودانا — User Profile v2 (Complete)
 * Features: view + edit name/phone, KYC levels, quick links
 * Route: /profile.php
 */
require_once __DIR__ . '/config.php';
session_start();
$userId = (int)($_SESSION['user_id'] ?? 0);
if (!$userId) { header('Location: ' . SITE_URL . '/'); exit; }
$lang = $_SESSION['lang'] ?? 'ar';
$dir  = $lang === 'ar' ? 'rtl' : 'ltr';
$pageTitle = $lang==='ar'?'ملفي':'My Profile';
$backUrl   = SITE_URL . '/';
$backLabel = $lang==='ar'?'الرئيسية':'Home';

$user = null; $wallet = null; $msg = null; $msgType = 'success';

// Handle edit form
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name  = mb_substr(trim($_POST['name'] ?? ''), 0, 100);
    $phone = mb_substr(trim($_POST['phone'] ?? ''), 0, 20);
    try {
        db()->prepare("UPDATE users SET name=?, phone=? WHERE id=?")
             ->execute([$name, $phone, $userId]);
        $_SESSION['user_name'] = $name;
        $msg = $lang==='ar' ? '✅ تم تحديث بياناتك بنجاح' : '✅ Profile updated successfully';
    } catch(Throwable $e) {
        $msg = $lang==='ar' ? '❌ خطأ في التحديث' : '❌ Update failed';
        $msgType = 'error';
    }
}

try {
    $q = db()->prepare("SELECT name, email, phone, user_type, provider_verified, created_at FROM users WHERE id=?");
    $q->execute([$userId]);
    $user = $q->fetch(PDO::FETCH_ASSOC);
    $wq = db()->prepare("SELECT balance_sdg, hold_balance, kyc_level FROM wallet WHERE user_id=?");
    $wq->execute([$userId]);
    $wallet = $wq->fetch(PDO::FETCH_ASSOC);
} catch(Throwable $e) {}

$kycLevels = [
    0 => ['ar'=>'بريد إلكتروني فقط', 'en'=>'Email only',     'limit'=>'2,000',   'badge'=>'⚪','color'=>'#9A9590'],
    1 => ['ar'=>'هاتف موثَّق',       'en'=>'Phone verified', 'limit'=>'10,000',  'badge'=>'🔵','color'=>'#3B82F6'],
    2 => ['ar'=>'هوية موثَّقة',      'en'=>'ID verified',    'limit'=>'50,000',  'badge'=>'🟢','color'=>'#16A34A'],
    3 => ['ar'=>'KYC كامل',          'en'=>'Full KYC',       'limit'=>'200,000', 'badge'=>'⭐','color'=>'#D4AF37'],
];
$kyc     = (int)($wallet['kyc_level'] ?? 0);
$kycInfo = $kycLevels[$kyc];
$nextKyc = $kycLevels[min($kyc+1,3)];
include __DIR__ . '/app/_head.php';
?>
<style>
.profile-hero{background:linear-gradient(135deg,var(--g1),var(--g3));color:#fff;padding:28px 20px;text-align:center}
.avatar{width:72px;height:72px;border-radius:50%;background:var(--gold);color:var(--g1);font-weight:900;font-size:1.7rem;display:flex;align-items:center;justify-content:center;margin:0 auto 12px;box-shadow:0 4px 16px rgba(0,0,0,.2)}
.kyc-badge{display:inline-flex;align-items:center;gap:6px;background:rgba(255,255,255,.15);border:1px solid rgba(255,255,255,.3);border-radius:20px;padding:4px 14px;font-size:.78rem;font-weight:700;margin-top:8px}
.kyc-progress{background:rgba(255,255,255,.15);border-radius:20px;height:6px;margin:12px 20px 0;overflow:hidden}
.kyc-bar{height:100%;background:var(--gold);border-radius:20px;transition:width .5s}
.form-field{margin-bottom:14px}
.form-field label{display:block;font-size:.82rem;font-weight:600;color:var(--text2);margin-bottom:5px}
.form-field input{width:100%;border:1.5px solid var(--border);border-radius:var(--r2);padding:10px 12px;font-family:Cairo,sans-serif;font-size:.9rem;outline:none;transition:border-color .15s}
.form-field input:focus{border-color:var(--g3)}
.form-field input[disabled]{background:var(--sand);color:var(--text2)}
.quick-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.quick-link{display:flex;align-items:center;gap:10px;padding:12px 14px;background:#fff;border:1.5px solid var(--border);border-radius:var(--r2);text-decoration:none;color:var(--text);transition:all .2s;font-size:.85rem;font-weight:600}
.quick-link:hover{border-color:var(--g3);background:var(--sand);transform:translateY(-1px)}
.quick-link .ql-icon{font-size:1.3rem}
.msg-ok{background:#D1FAE5;border:1px solid #6EE7B7;color:#065F46;padding:10px 14px;border-radius:var(--r2);margin-bottom:14px;font-size:.88rem}
.msg-err{background:#FEE2E2;border:1px solid #FCA5A5;color:#991B1B;padding:10px 14px;border-radius:var(--r2);margin-bottom:14px;font-size:.88rem}
@media(max-width:480px){.quick-grid{grid-template-columns:1fr}}
</style>

<div class="profile-hero">
  <div class="avatar"><?= mb_strtoupper(mb_substr($user['name'] ?? 'م', 0, 1)) ?></div>
  <h2 style="font-size:1.2rem;font-weight:900"><?= htmlspecialchars($user['name'] ?? '—') ?></h2>
  <p style="font-size:.82rem;color:rgba(255,255,255,.7)"><?= htmlspecialchars($user['email'] ?? '') ?></p>
  <div class="kyc-badge"><?= $kycInfo['badge'] ?> <?= $kycInfo[$lang] ?> — <?= $lang==='ar'?'حد':'Limit' ?>: <?= $kycInfo['limit'] ?> SDG/<?= $lang==='ar'?'يوم':'day' ?></div>
  <div class="kyc-progress"><div class="kyc-bar" style="width:<?= ($kyc+1)*25 ?>%"></div></div>
</div>

<div class="page-wrap" style="max-width:560px">

  <?php if($msg): ?>
  <div class="<?= $msgType==='success'?'msg-ok':'msg-err' ?>"><?= htmlspecialchars($msg) ?></div>
  <?php endif; ?>

  <!-- Edit form -->
  <div class="card" style="margin-bottom:16px">
    <h4 style="font-weight:800;color:var(--g1);margin-bottom:16px">✏️ <?= $lang==='ar'?'تعديل البيانات':'Edit Profile' ?></h4>
    <form method="POST">
      <div class="form-field">
        <label><?= $lang==='ar'?'الاسم الكامل':'Full Name' ?></label>
        <input type="text" name="name" value="<?= htmlspecialchars($user['name'] ?? '') ?>" required maxlength="100">
      </div>
      <div class="form-field">
        <label><?= $lang==='ar'?'رقم الهاتف':'Phone Number' ?></label>
        <input type="tel" name="phone" value="<?= htmlspecialchars($user['phone'] ?? '') ?>" placeholder="09xxxxxxxx" maxlength="20">
      </div>
      <div class="form-field">
        <label><?= $lang==='ar'?'البريد الإلكتروني (غير قابل للتعديل)':'Email (read-only)' ?></label>
        <input type="email" value="<?= htmlspecialchars($user['email'] ?? '') ?>" disabled>
      </div>
      <button type="submit" class="btn btn-primary btn-sm" style="width:100%;padding:11px">
        💾 <?= $lang==='ar'?'حفظ التغييرات':'Save Changes' ?>
      </button>
    </form>
  </div>

  <!-- KYC Upgrade -->
  <?php if($kyc < 3): ?>
  <div class="card" style="background:linear-gradient(135deg,#FEF3C7,#FFFBEB);border-color:#FCD34D;margin-bottom:16px">
    <h4 style="font-weight:800;margin-bottom:8px">📈 <?= $lang==='ar'?'رفع مستوى التحقق':'Upgrade Verification' ?></h4>
    <p style="font-size:.85rem;color:var(--text2);margin-bottom:14px">
      <?= $lang==='ar'
        ? 'الوثيقة المطلوبة: '.($kyc<1?'تأكيد رقم الهاتف':($kyc<2?'صورة الهوية الوطنية':'تأكيد إضافي'))
        : 'Required: '.($kyc<1?'Phone verification':($kyc<2?'National ID photo':'Additional verification')) ?>
      → <?= $lang==='ar'?'الحد سيرتفع إلى':'Limit will increase to' ?> <?= $nextKyc['limit'] ?> SDG/<?= $lang==='ar'?'يوم':'day' ?>
    </p>
    <div style="display:flex;gap:10px;flex-wrap:wrap">
      <?php if($kyc < 1): ?>
      <button class="btn btn-outline btn-sm" onclick="alert('<?= $lang==='ar'?'قريباً — إدخال رمز التحقق':'Coming soon — OTP verification' ?>')">
        📱 <?= $lang==='ar'?'تأكيد الهاتف':'Verify Phone' ?>
      </button>
      <?php endif; ?>
      <?php if($kyc < 2): ?>
      <button class="btn btn-gold btn-sm" onclick="alert('<?= $lang==='ar'?'قريباً — رفع صورة الهوية':'Coming soon — ID upload' ?>')">
        🪪 <?= $lang==='ar'?'رفع الهوية':'Upload ID' ?>
      </button>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- Quick Links -->
  <div class="card" style="margin-bottom:16px">
    <h4 style="font-weight:800;color:var(--g1);margin-bottom:14px">🔗 <?= $lang==='ar'?'روابط سريعة':'Quick Links' ?></h4>
    <div class="quick-grid">
      <a href="<?= SITE_URL ?>/wallet.php" class="quick-link">
        <span class="ql-icon">💳</span>
        <div>
          <div><?= $lang==='ar'?'المحفظة':'Wallet' ?></div>
          <div style="font-size:.72rem;color:var(--g2)"><?= number_format((float)($wallet['balance_sdg']??0),0) ?> SDG</div>
        </div>
      </a>
      <a href="<?= SITE_URL ?>/app/notifications.php" class="quick-link">
        <span class="ql-icon">🔔</span>
        <div><?= $lang==='ar'?'الإشعارات':'Notifications' ?></div>
      </a>
      <a href="<?= SITE_URL ?>/app/services.php" class="quick-link">
        <span class="ql-icon">🛍️</span>
        <div><?= $lang==='ar'?'الخدمات':'Services' ?></div>
      </a>
      <a href="<?= SITE_URL ?>/app/dashboard.php" class="quick-link">
        <span class="ql-icon">📊</span>
        <div><?= $lang==='ar'?'لوحة التحكم':'Dashboard' ?></div>
      </a>
    </div>
  </div>

  <!-- Account info -->
  <div class="card" style="margin-bottom:16px">
    <h4 style="font-weight:800;color:var(--g1);margin-bottom:14px">ℹ️ <?= $lang==='ar'?'معلومات الحساب':'Account Info' ?></h4>
    <div style="display:flex;flex-direction:column;gap:10px">
      <div style="display:flex;justify-content:space-between;font-size:.85rem">
        <span style="color:var(--text2)"><?= $lang==='ar'?'نوع الحساب':'Account Type' ?></span>
        <span style="font-weight:600"><?= ucfirst($user['user_type'] ?? 'user') ?></span>
      </div>
      <div style="display:flex;justify-content:space-between;font-size:.85rem">
        <span style="color:var(--text2)"><?= $lang==='ar'?'عضو منذ':'Member since' ?></span>
        <span style="font-weight:600"><?= $user['created_at'] ? date('d/m/Y', strtotime($user['created_at'])) : '—' ?></span>
      </div>
    </div>
  </div>

</div>
<?php include __DIR__ . '/app/_foot.php'; ?>
