<?php

namespace App\Controllers;

use App\Models\Server;
use App\Models\Client;
use App\Utils\View;
use App\Services\ASNService;

class ServerController
{
    public function index()
    {
        $serverModel = new Server();
        $sql = "SELECT s.*, c.name as client_name FROM servers s JOIN clients c ON s.client_id = c.id";
        $stmt = \App\Config\Database::getInstance()->getConnection()->prepare($sql);
        $stmt->execute();
        $servers = $stmt->fetchAll();

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

    public function create()
    {
        $clientModel = new Client();
        $clients = $clientModel->where('status', 'active');

        View::render('layouts.admin', [
            'title' => 'Novo Servidor',
            'content' => __DIR__ . '/../../resources/views/admin/servers/form.php',
            'clients' => $clients
        ]);
    }

    public function store()
    {
        $clientModel = new Client();
        $client = $clientModel->find($_POST['client_id']);

        if (!$client) {
            View::redirect('/admin/servers');
            return;
        }

        // Validate IP vs ASN
        if (!ASNService::validateIP($_POST['ip_v4'], $client['asn'])) {
            $_SESSION['flash_error'] = "O IP informado não pertence ao ASN do cliente ({$client['asn']}).";
            // Keep input data
            $_SESSION['old_input'] = $_POST;
            View::redirect('/admin/servers/create');
            return;
        }

        $data = [
            'client_id' => $_POST['client_id'],
            'name' => $_POST['name'],
            'ip_v4' => $_POST['ip_v4'],
            'ip_v6' => $_POST['ip_v6'] ?? null,
            'serial_key' => bin2hex(random_bytes(16)),
            'status' => 'active'
        ];

        $sql = "INSERT INTO servers (client_id, name, ip_v4, ip_v6, serial_key, status) VALUES (:client_id, :name, :ip_v4, :ip_v6, :serial_key, :status)";
        $stmt = \App\Config\Database::getInstance()->getConnection()->prepare($sql);
        $stmt->execute($data);

        View::redirect('/admin/servers');
    }

    public function edit($id)
    {
        $serverModel = new Server();
        $server = $serverModel->find($id);

        if (!$server) {
            View::redirect('/admin/servers');
        }

        $clientModel = new Client();
        $clients = $clientModel->where('status', 'active');

        View::render('layouts.admin', [
            'title' => 'Editar Servidor',
            'content' => __DIR__ . '/../../resources/views/admin/servers/form.php',
            'server' => $server,
            'clients' => $clients
        ]);
    }

    public function update($id)
    {
        $serverModel = new Server();
        $server = $serverModel->find($id);

        if (!$server) {
            View::redirect('/admin/servers');
            return;
        }

        // If IP changed, validate again
        if ($_POST['ip_v4'] !== $server['ip_v4']) {
            $clientModel = new Client();
            $client = $clientModel->find($_POST['client_id']);

            if (!ASNService::validateIP($_POST['ip_v4'], $client['asn'])) {
                $_SESSION['flash_error'] = "O IP informado não pertence ao ASN do cliente ({$client['asn']}).";
                View::redirect('/admin/servers/edit/' . $id);
                return;
            }
        }

        $data = [
            'id' => $id,
            'client_id' => $_POST['client_id'],
            'name' => $_POST['name'],
            'ip_v4' => $_POST['ip_v4'],
            'ip_v6' => $_POST['ip_v6'] ?? null,
            'status' => $_POST['status']
        ];

        $sql = "UPDATE servers SET client_id=:client_id, name=:name, ip_v4=:ip_v4, ip_v6=:ip_v6, status=:status WHERE id=:id";
        $stmt = \App\Config\Database::getInstance()->getConnection()->prepare($sql);
        $stmt->execute($data);

        View::redirect('/admin/servers');
    }

    public function delete($id)
    {
        $serverModel = new Server();
        $serverModel->delete($id);
        View::redirect('/admin/servers');
    }

    public function resetMachineId($id)
    {
        $serverModel = new Server();
        $server = $serverModel->find($id);

        if ($server) {
            $sql = "UPDATE servers SET machine_id = NULL WHERE id = :id";
            $stmt = \App\Config\Database::getInstance()->getConnection()->prepare($sql);
            $stmt->execute(['id' => $id]);

            // Log action
            $logSql = "INSERT INTO api_logs (server_id, action, message, ip_address) VALUES (:sid, 'reset_machine', 'Machine ID reset by admin', :ip)";
            $logStmt = \App\Config\Database::getInstance()->getConnection()->prepare($logSql);
            $logStmt->execute([
                'sid' => $id,
                'ip' => $_SERVER['REMOTE_ADDR'] ?? null
            ]);
        }

        View::redirect('/admin/servers/edit/' . $id);
    }
}
