<?php
include "../includes/header.php"; 
require_once "../includes/db.php";

// التحقق من تسجيل الدخول
$user_id = $_SESSION['user_id'] ?? 1;

// جلب بيانات المستخدم
$stmt = $pdo->prepare("SELECT * FROM users WHERE id=? LIMIT 1");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name  = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $password = !empty($_POST['password']) ? password_hash($_POST['password'], PASSWORD_BCRYPT) : $user['password'];
    
    $avatar = $user['avatar'];
    if (!empty($_FILES['avatar']['name'])) {
        $avatar = time() . "_" . $_FILES['avatar']['name'];
        move_uploaded_file($_FILES['avatar']['tmp_name'], "../assets/uploads/" . $avatar);
    }

    $stmt = $pdo->prepare("UPDATE users SET name=?, email=?, phone=?, password=?, avatar=? WHERE id=?");
    $stmt->execute([$name, $email, $phone, $password, $avatar, $user_id]);

    header("Location: profile.php?updated=1");
    exit;
}
?>

<section class="container" style="margin-top:40px;">
  <h2 class="section-title">ملفي الشخصي</h2>

  <form method="post" enctype="multipart/form-data" style="max-width:600px;margin:auto;background:#121212;padding:20px;border-radius:8px;">
    <label>الاسم:</label>
    <input type="text" name="name" value="<?= e($user['name']); ?>" required style="width:100%;padding:10px;margin:6px 0;">

    <label>البريد الإلكتروني:</label>
    <input type="email" name="email" value="<?= e($user['email']); ?>" required style="width:100%;padding:10px;margin:6px 0;">

    <label>رقم الجوال:</label>
    <input type="text" name="phone" value="<?= e($user['phone']); ?>" style="width:100%;padding:10px;margin:6px 0;">

    <label>كلمة المرور الجديدة:</label>
    <input type="password" name="password" placeholder="اتركها فارغة إن لم ترغب بالتغيير" style="width:100%;padding:10px;margin:6px 0;">

    <label>الصورة الشخصية:</label><br>
    <?php if ($user['avatar']): ?>
      <img src="../assets/uploads/<?= e($user['avatar']); ?>" alt="صورة المستخدم" style="height:80px;border-radius:50%;margin-bottom:10px;"><br>
    <?php endif; ?>
    <input type="file" name="avatar" accept="image/*" style="margin:10px 0;">

    <button type="submit" class="btn">حفظ التغييرات</button>
  </form>
</section>

<?php include "../includes/footer.php"; ?>
