<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\Session;
use App\Core\Database;
use App\Models\User;
use App\Models\Post;
use App\Models\Category;
use App\Models\Page;

class AdminController extends Controller
{
    private Database $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    public function dashboard(Request $request): Response
    {
        $stats = [
            'total_users'    => (int)$this->db->query("SELECT COUNT(*) FROM users")->fetchColumn(),
            'total_posts'    => (int)$this->db->query("SELECT COUNT(*) FROM posts")->fetchColumn(),
            'total_comments' => (int)$this->db->query("SELECT COUNT(*) FROM comments")->fetchColumn(),
            'total_categories' => (int)$this->db->query("SELECT COUNT(*) FROM categories")->fetchColumn(),
            'recent_logs'    => (new \App\Models\ActivityLog())->getRecent(20)
        ];
        
        $recentPosts = $this->db->query(
            "SELECT p.*, u.username FROM posts p JOIN users u ON p.user_id = u.id ORDER BY p.created_at DESC LIMIT 10"
        )->fetchAll();
        
        $recentUsers = $this->db->query(
            "SELECT * FROM users ORDER BY created_at DESC LIMIT 10"
        )->fetchAll();

        return $this->render('admin.dashboard', compact('stats', 'recentPosts', 'recentUsers'));
    }

    public function users(Request $request): Response
    {
        $userModel = new User();
        $users = $userModel->getAll(100);
        return $this->render('admin.users', compact('users'));
    }

    public function settings(Request $request): Response
    {
        $settingsRaw = $this->db->query("SELECT * FROM site_settings")->fetchAll();
        $settings = [];
        foreach ($settingsRaw as $s) $settings[$s['key']] = $s['value'];
        return $this->render('admin.settings', compact('settings'));
    }

    public function saveSettings(Request $request): Response
    {
        $keys = ['site_name', 'meta_description', 'allow_registration', 'dark_mode_default', 'footer_text', 'footer_desc'];
        foreach ($keys as $key) {
            $val = $request->post($key, '');
            $stmt = $this->db->prepare("INSERT INTO site_settings (`key`, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = ?");
            $stmt->execute([$key, $val, $val]);
        }
        Session::flash('success', 'Settings saved');
        return Response::redirect('/admin/settings');
    }

    public function categories(Request $request): Response
    {
        $categories = (new \App\Models\Category())->all();
        return $this->render('admin.categories.index', compact('categories'));
    }

    public function storeCategory(Request $request): Response
    {
        $name = trim($request->post('name', ''));
        $description = trim($request->post('description', ''));
        $icon = trim($request->post('icon', 'folder'));
        if (!$name) {
            Session::flash('error', 'Name required');
            return Response::redirect('/admin/categories');
        }
        $slug = strtolower(preg_replace('/[^a-z0-9]+/i', '-', $name));
        (new Category())->create(compact('name', 'slug', 'description', 'icon'));
        Session::flash('success', 'Category created');
        return Response::redirect('/admin/categories');
    }

    public function updateCategory(Request $request, int $id): Response
    {
        (new Category())->update($id, [
            'name' => trim($request->post('name', '')),
            'description' => trim($request->post('description', '')),
            'icon' => trim($request->post('icon', 'folder')),
        ]);
        Session::flash('success', 'Category updated');
        return Response::redirect('/admin/categories');
    }

    public function deleteCategory(Request $request, int $id): Response
    {
        (new Category())->delete($id);
        Session::flash('success', 'Category deleted');
        return Response::redirect('/admin/categories');
    }

    public function deletePost(Request $request, int $id): Response
    {
        (new Post())->delete($id);
        Session::flash('success', 'Post deleted');
        return Response::redirect($_SERVER['HTTP_REFERER'] ?? '/');
    }

    public function blockPost(Request $request, int $id): Response
    {
        $this->db->prepare("UPDATE posts SET status = IF(status='active','blocked','active') WHERE id = ?")->execute([$id]);
        Session::flash('success', 'Post status toggled');
        return Response::redirect($_SERVER['HTTP_REFERER'] ?? '/');
    }

    public function pinTopic(Request $request, int $id): Response
    {
        $post = $this->db->prepare("SELECT sort_order FROM posts WHERE id = ?");
        $post->execute([$id]);
        $p = $post->fetch();
        $newOrder = ($p && $p['sort_order'] >= 9000) ? 0 : 9999;
        $this->db->prepare("UPDATE posts SET sort_order = ? WHERE id = ?")->execute([$newOrder, $id]);
        return Response::redirect($_SERVER['HTTP_REFERER'] ?? '/');
    }

    public function deleteComment(Request $request, int $id): Response
    {
        (new \App\Models\Comment())->delete($id);
        return Response::redirect($_SERVER['HTTP_REFERER'] ?? '/');
    }

    public function banUser(Request $request, int $id): Response
    {
        (new User())->update($id, ['role_id' => 0]);
        Session::flash('success', 'User banned');
        return Response::redirect($_SERVER['HTTP_REFERER'] ?? '/admin/users');
    }

    public function unbanUser(Request $request, int $id): Response
    {
        (new User())->update($id, ['role_id' => 1]);
        Session::flash('success', 'User unbanned');
        return Response::redirect($_SERVER['HTTP_REFERER'] ?? '/admin/users');
    }

    public function updatePostsOrder(Request $request): Response
    {
        $orders = json_decode($request->post('orders', '[]'), true);
        if (!is_array($orders)) return Response::json(['success' => false], 400);
        foreach ($orders as $item) {
            if (isset($item['id'], $item['order'])) {
                $this->db->prepare("UPDATE posts SET sort_order = ? WHERE id = ?")->execute([(int)$item['order'], (int)$item['id']]);
            }
        }
        return Response::json(['success' => true]);
    }

    public function pages(Request $request): Response
    {
        $pages = (new Page())->all();
        return $this->render('admin.pages.index', compact('pages'));
    }

    public function createPage(Request $request): Response
    {
        return $this->render('admin.pages.create');
    }

    public function storePage(Request $request): Response
    {
        $title = trim($request->post('title', ''));
        $content = trim($request->post('content', ''));
        $slug = strtolower(preg_replace('/[^a-z0-9]+/i', '-', $title));
        if (!$title) {
            Session::flash('error', 'Title required');
            return Response::redirect('/admin/pages/create');
        }
        (new Page())->create(compact('title', 'slug', 'content'));
        Session::flash('success', 'Page created');
        return Response::redirect('/admin/pages');
    }

    public function editPage(Request $request, int $id): Response
    {
        $page = (new Page())->find($id);
        if (!$page) return new Response('Not found', 404);
        return $this->render('admin.pages.edit', compact('page'));
    }

    public function updatePage(Request $request, int $id): Response
    {
        (new Page())->update($id, [
            'title' => trim($request->post('title', '')),
            'content' => trim($request->post('content', '')),
            'is_active' => (int)$request->post('is_active', 1),
        ]);
        Session::flash('success', 'Page updated');
        return Response::redirect('/admin/pages');
    }

    public function deletePage(Request $request, int $id): Response
    {
        (new Page())->delete($id);
        Session::flash('success', 'Page deleted');
        return Response::redirect('/admin/pages');
    }
}
