<?php
// src/DhcpBundle/Service/CurlKeaService.php

namespace App\DhcpBundle\Service;

use Exception;

class CurlKeaService
{
    public function executeCurlCommand($command, $arguments = null, $create_backup = true)
    {
        $apiUrl = getenv('DHCP_IP');
        if (!$apiUrl) {
            $apiUrl = 'http://localhost:8000/';
        }

        if ($command == 'config-get' || $command == 'config-write') {
            $requestData = array(
                'command' => $command,
                'service' => array('dhcp4'),
            );
        } elseif ($command == 'config-set' || $command == 'config-test') {
            $requestData = array(
                'command' => $command,
                'service' => array('dhcp4'),
                'arguments' => $arguments,
            );
        } else {
            return "Error: Comando no válido";
        }
        //f (($command == 'config-set' || $command == 'config-write') && $create_backup) {
        if ($command == 'config-set' && $create_backup) {    
            $this->backupConfig();
        }
        $jsonData = json_encode($requestData);
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $apiUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Expect:'));
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_POST, true);
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $output = json_decode($response, true);

            if ($httpCode >= 200 && $httpCode < 300) {

                return $output;
            } else {
                $error = curl_error($ch);
                throw new Exception($error);
                //return false;
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    public function convertMaskToCIDR($mask)
    {
        $bits = 0;
        $mask = explode(".", $mask);

        foreach ($mask as $octect)
            $bits += strlen(str_replace("0", "", decbin($octect)));

        return $bits;
    }

    function backupConfig()
    {
        $get_command = 'config-get';
        $get_output = $this->executeCurlCommand($get_command);
        if ($get_output == false || $get_output[0]["result"] != 0) {
            throw new Exception('Error al obtener la configuración actual de Kea DHCP');
        }
        $config_text = json_encode($get_output[0]['arguments']);
        $configurationParsed = str_replace('\\', '', $config_text);

        $backup_dir = __DIR__ . '/../../../etc/kea/backup';
        if (!is_dir($backup_dir)) {
            throw new Exception('El directorio de backup no existe');
        }
        if (!is_writable($backup_dir)) {
            throw new Exception('El directorio de backup no tiene permisos de escritura');
        }
        $backup_files = glob($backup_dir . '/*.conf');
        if (count($backup_files) >= 10) {
            usort($backup_files, function ($a, $b) {
                return filemtime($a) - filemtime($b);
            });
            unlink($backup_files[0]);
        }
        $backup_file = $backup_dir . '/' . date('Y-m-d_H-i-s') . '.conf';
        if (!file_put_contents($backup_file, $configurationParsed)) {
            throw new Exception('Error al guardar la configuración de backup');
        }
    }
}
