<?php
/**
 * ════════════════════════════════════════════════════════════════
 *  PATCH v1.5.15 — AdminController additions
 * ════════════════════════════════════════════════════════════════
 *  Add these two methods to your existing AdminController.php,
 *  AFTER the toggleUser() method and BEFORE the fields() method.
 *
 *  1. Open:  app/Controllers/AdminController.php
 *  2. Find:  public function toggleUser()
 *  3. Paste the two methods below AFTER the closing brace of toggleUser()
 * ════════════════════════════════════════════════════════════════
 */

    public function editUser(): void
    {
        $id = (int)($this->request->segment(3) ?? 0);
        $pdo = \App\Core\Database::pdo();
        $user = $pdo->prepare("SELECT id, full_name, email, role, status FROM users WHERE id = ? LIMIT 1");
        $user->execute([$id]);
        $editUser = $user->fetch();
        if (!$editUser) { $this->flash('error', 'کاربر یافت نشد.'); $this->redirect('/admin/users'); return; }
        $this->view('admin/edit_user', ['title' => 'ویرایش کاربر', 'editUser' => $editUser], 'admin');
    }

    public function updateUser(): void
    {
        $id       = (int)($this->request->segment(3) ?? 0);
        $name     = trim((string)$this->request->input('full_name'));
        $email    = trim(strtolower((string)$this->request->input('email')));
        $role     = in_array($this->request->input('role'), ['admin','user']) ? $this->request->input('role') : 'user';
        $status   = in_array($this->request->input('status'), ['active','inactive']) ? $this->request->input('status') : 'active';
        $pass     = (string)$this->request->input('password');

        if (!$name || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->flash('error', 'نام و ایمیل معتبر الزامی است.');
            $this->redirect('/admin/users/' . $id . '/edit');
            return;
        }

        try {
            $pdo = \App\Core\Database::pdo();
            // Check email conflict
            $conflict = $pdo->prepare("SELECT id FROM users WHERE email = ? AND id != ? LIMIT 1");
            $conflict->execute([$email, $id]);
            if ($conflict->fetchColumn()) {
                $this->flash('error', 'این ایمیل توسط کاربر دیگری استفاده می‌شود.');
                $this->redirect('/admin/users/' . $id . '/edit');
                return;
            }
            if ($pass && strlen($pass) >= 8) {
                $pdo->prepare("UPDATE users SET full_name=?, email=?, role=?, status=?, password=? WHERE id=?")
                    ->execute([$name, $email, $role, $status, password_hash($pass, PASSWORD_DEFAULT), $id]);
            } else {
                $pdo->prepare("UPDATE users SET full_name=?, email=?, role=?, status=? WHERE id=?")
                    ->execute([$name, $email, $role, $status, $id]);
            }
            $this->flash('success', 'اطلاعات کاربر بروزرسانی شد.');
            $this->redirect('/admin/users');
        } catch (\Throwable $e) {
            $this->flash('error', 'خطا در بروزرسانی کاربر.');
            $this->redirect('/admin/users/' . $id . '/edit');
        }
    }
