<?php

namespace App\Controllers;

use App\Models\Server;
use App\Models\Order;
use App\Models\Domain;
use App\Models\Client;
use App\Utils\View;

class ClientDashboardController
{
    private function getClientId()
    {
        if (!isset($_SESSION['user_id'])) {
            View::redirect('/login');
            exit;
        }

        $userModel = new \App\Models\User();
        $user = $userModel->find($_SESSION['user_id']);

        if (!$user) {
            // Invalid user in session
            session_destroy();
            View::redirect('/login');
            exit;
        }

        return $user['client_id'];
    }

    public function index()
    {
        $clientId = $this->getClientId();

        $serverModel = new Server();
        $orderModel = new Order();
        $domainModel = new Domain();

        // Client specific stats
        $myServers = $serverModel->where('client_id', $clientId);
        $activeServers = array_filter($myServers, fn($s) => $s['status'] === 'active');

        $stats = [
            'my_servers' => count($myServers),
            'active_servers' => count($activeServers),
            'total_blocked' => $domainModel->countBlocked(), // Global blocked count
            'recent_orders' => count($orderModel->recent(30)), // Orders in last month approx (using limit for now)
            'total_orders' => count($orderModel->findAll())
        ];

        $allOrders = $orderModel->findAll();
        usort($allOrders, function ($a, $b) {
            return $b['id'] - $a['id'];
        });
        $recent_orders = array_slice($allOrders, 0, 10);

        View::render('layouts.client', [
            'title' => 'Visão Geral',
            'content' => __DIR__ . '/../../resources/views/client/dashboard.php',
            'stats' => $stats,
            'recent_orders' => $recent_orders
        ]);
    }

    public function servers()
    {
        $clientId = $this->getClientId();
        $serverModel = new Server();
        $servers = $serverModel->where('client_id', $clientId);

        View::render('layouts.client', [
            'title' => 'Meus Servidores',
            'content' => __DIR__ . '/../../resources/views/client/servers.php',
            'servers' => $servers
        ]);
    }

    public function orders()
    {
        $orderModel = new Order();
        $query = $_GET['q'] ?? '';

        if (!empty($query)) {
            $conn = \App\Config\Database::getInstance()->getConnection();
            $term = "%$query%";
            $sql = "SELECT DISTINCT o.* FROM orders o 
                    LEFT JOIN order_items oi ON o.id = oi.order_id 
                    LEFT JOIN domains d ON oi.domain_id = d.id 
                    WHERE o.title LIKE :term OR d.name LIKE :term 
                    ORDER BY o.received_at DESC";
            $stmt = $conn->prepare($sql);
            $stmt->execute(['term' => $term]);
            $orders = $stmt->fetchAll();
        } else {
            $orders = $orderModel->findAll();
            // Sort by ID DESC
            usort($orders, function ($a, $b) {
                return $b['id'] - $a['id'];
            });
        }

        // Pagination Logic
        $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        $perPage = 20;
        $total = count($orders);
        $totalPages = ceil($total / $perPage);
        $offset = ($page - 1) * $perPage;
        $paginatedOrders = array_slice($orders, $offset, $perPage);

        View::render('layouts.client', [
            'title' => 'Ordens Judiciais',
            'content' => __DIR__ . '/../../resources/views/client/orders.php',
            'orders' => $paginatedOrders,
            'pagination' => [
                'current' => $page,
                'total' => $totalPages,
                'next' => ($page < $totalPages) ? $page + 1 : null,
                'prev' => ($page > 1) ? $page - 1 : null
            ]
        ]);
    }

    public function viewOrder($id)
    {
        $orderModel = new Order();
        $order = $orderModel->find($id);

        if (!$order) {
            View::redirect('/client/orders');
            return;
        }

        // Get domains for this order
        $conn = \App\Config\Database::getInstance()->getConnection();
        $stmt = $conn->prepare("SELECT d.name, oi.action FROM domains d JOIN order_items oi ON d.id = oi.domain_id WHERE oi.order_id = :order_id");
        $stmt->execute(['order_id' => $id]);
        $domains = $stmt->fetchAll();

        View::render('layouts.client', [
            'title' => 'Detalhes da Ordem #' . $id,
            'content' => __DIR__ . '/../../resources/views/client/orders_view.php',
            'order' => $order,
            'domains' => $domains
        ]);
    }

    public function profile()
    {
        $clientId = $this->getClientId();
        $clientModel = new Client();
        $client = $clientModel->find($clientId);

        View::render('layouts.client', [
            'title' => 'Meu Perfil',
            'content' => __DIR__ . '/../../resources/views/client/profile.php',
            'client' => $client
        ]);
    }

    public function updatePassword()
    {
        $password = $_POST['password'];
        $confirm = $_POST['confirm_password'];

        if ($password !== $confirm) {
            $_SESSION['flash_error'] = "As senhas não conferem.";
            View::redirect('/client/profile');
            return;
        }

        $validation = \App\Utils\PasswordValidator::validate($password);
        if ($validation !== true) {
            $_SESSION['flash_error'] = $validation;
            View::redirect('/client/profile');
            return;
        }

        $hash = password_hash($password, PASSWORD_DEFAULT);
        $userId = $_SESSION['user_id'];

        $conn = \App\Config\Database::getInstance()->getConnection();
        $stmt = $conn->prepare("UPDATE users SET password = :password WHERE id = :id");
        $stmt->execute(['password' => $hash, 'id' => $userId]);

        $_SESSION['flash_success'] = "Senha atualizada com sucesso.";
        View::redirect('/client/profile');
    }
}
