<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;

final class AdminEditorsController extends Controller
{
    public function index(): void
    {
        require_login();
        if (!can_admin()) { http_response_code(403); echo "Forbidden"; return; }
        $db = Database::getInstance();
        $rows = $db->query("SELECT id,email,first_name,last_name,is_active FROM users WHERE role_id=3 ORDER BY id DESC LIMIT 1000")->fetchAll();
        $this->view('admin/editors/index', ['rows'=>$rows,'err'=>null]);
    }

    public function create(): void
    {
        require_login();
        if (!can_admin()) { http_response_code(403); echo "Forbidden"; return; }
        $this->view('admin/editors/create', ['err'=>null]);
    }

    public function store(): void
    {
        require_login();
        if (!can_admin()) { http_response_code(403); echo "Forbidden"; return; }
        csrf_check();
        $db = Database::getInstance();

        $email = strtolower(trim((string)($_POST['email'] ?? '')));
        $fn = trim((string)($_POST['first_name'] ?? 'Editor'));
        $ln = trim((string)($_POST['last_name'] ?? ''));
        if ($email==='') { $this->view('admin/editors/create',['err'=>'Email required']); return; }

        $st = $db->prepare("SELECT id FROM users WHERE email=:e LIMIT 1");
        $st->execute([':e'=>$email]);
        $uid = (int)($st->fetchColumn() ?: 0);

        if ($uid<=0) {
            $hash = password_hash(bin2hex(random_bytes(6)).'A!', PASSWORD_BCRYPT);
            $db->prepare("INSERT INTO users(role_id,first_name,last_name,email,password_hash,preferred_lang,is_active)
                          VALUES(3,:fn,:ln,:em,:ph,'ar',1)")
               ->execute([':fn'=>$fn,':ln'=>$ln,':em'=>$email,':ph'=>$hash]);
        } else {
            $db->prepare("UPDATE users SET role_id=3,is_active=1 WHERE id=:id")->execute([':id'=>$uid]);
        }

        header('Location: '.base_path('admin/editors')); exit;
    }

    public function toggle(): void
    {
        require_login();
        if (!can_admin()) { http_response_code(403); echo "Forbidden"; return; }
        csrf_check();
        $db = Database::getInstance();

        $id = (int)($_POST['id'] ?? 0);
        $st = $db->prepare("SELECT is_active FROM users WHERE id=:id LIMIT 1");
        $st->execute([':id'=>$id]);
        $cur = (int)($st->fetchColumn() ?? 1);

        $db->prepare("UPDATE users SET is_active=:v WHERE id=:id")->execute([':v'=>($cur?0:1),':id'=>$id]);
        header('Location: '.base_path('admin/editors')); exit;
    }
}
