<?php
require_once __DIR__ . '/includes/header.php';

$user_id = $_SESSION['user_id'];
$success_msg = '';
$error_msg = '';

// Fetch current user data
$stmt = db()->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_profile'])) {
        $full_name = $_POST['full_name'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $address = $_POST['address'];
        $password = $_POST['password'];
        $profile_image = $user['profile_image'];

        // Handle Profile Image Upload
        if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = 'uploads/profiles/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0775, true);
            
            $file_ext = pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION);
            $new_file_name = time() . '_u' . $user_id . '.' . $file_ext;
            $target_file = $upload_dir . $new_file_name;

            if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $target_file)) {
                $profile_image = $target_file;
            }
        }

        if (!empty($password)) {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $stmt = db()->prepare("UPDATE users SET full_name = ?, email = ?, phone = ?, address = ?, password = ?, profile_image = ? WHERE id = ?");
            $stmt->execute([$full_name, $email, $phone, $address, $hashed_password, $profile_image, $user_id]);
        } else {
            $stmt = db()->prepare("UPDATE users SET full_name = ?, email = ?, phone = ?, address = ?, profile_image = ? WHERE id = ?");
            $stmt->execute([$full_name, $email, $phone, $address, $profile_image, $user_id]);
        }
        $_SESSION['success'] = 'تم تحديث الملف الشخصي بنجاح';
        redirect('profile.php');
    }
}

// Get session messages
if (isset($_SESSION['success'])) {
    $success_msg = $_SESSION['success'];
    unset($_SESSION['success']);
}
?>

<div class="row">
    <div class="col-md-12 mb-4">
        <h2 class="fw-bold"><i class="fas fa-user-circle me-2"></i> الملف الشخصي</h2>
    </div>

    <?php if ($success_msg): ?>
        <div class="alert alert-success"><?= $success_msg ?></div>
    <?php endif; ?>

    <div class="col-md-8 mx-auto">
        <div class="card p-4">
            <h4 class="mb-4">تعديل الملف الشخصي</h4>
            <form method="POST" enctype="multipart/form-data">
                <div class="text-center mb-4">
                    <?php if ($user['profile_image']): ?>
                        <img src="<?= $user['profile_image'] ?>" alt="Profile" class="rounded-circle shadow" style="width: 150px; height: 150px; object-fit: cover; border: 3px solid #0d6efd;">
                    <?php else: ?>
                        <div class="rounded-circle bg-light d-inline-flex align-items-center justify-content-center shadow" style="width: 150px; height: 150px; border: 3px solid #ddd;">
                            <i class="fas fa-user fa-5x text-secondary"></i>
                        </div>
                    <?php endif; ?>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">الاسم الكامل</label>
                        <input type="text" name="full_name" class="form-control" value="<?= htmlspecialchars($user['full_name'] ?? '') ?>" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">البريد الإلكتروني</label>
                        <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($user['email'] ?? '') ?>">
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">رقم الهاتف</label>
                        <input type="text" name="phone" class="form-control" value="<?= htmlspecialchars($user['phone'] ?? '') ?>">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">الصورة الشخصية</label>
                        <input type="file" name="profile_image" class="form-control" accept="image/*">
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label">العنوان</label>
                    <textarea name="address" class="form-control" rows="3"><?= htmlspecialchars($user['address'] ?? '') ?></textarea>
                </div>

                <div class="mb-3">
                    <label class="form-label">كلمة المرور الجديدة (اتركها فارغة إذا لم ترغب في التغيير)</label>
                    <input type="password" name="password" class="form-control">
                </div>

                <button type="submit" name="update_profile" class="btn btn-primary w-100 mt-3">حفظ التغييرات</button>
            </form>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
