<?php
session_start();
require 'routeros_api.class.php';
header('Content-Type: application/json');

if(!isset($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])){
    http_response_code(401);
    echo json_encode(['success'=>false,'error'=>'not_authenticated']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);

$apType = $data['type'] ?? 'wifi';
if(!$data || empty($data['id']) || empty($data['name'])){
    http_response_code(400);
    echo json_encode(['success'=>false,'error'=>'invalid_input']);
    exit;
}

if ($apType !== 'odp' && empty($data['ip'])) {
    http_response_code(400);
    echo json_encode(['success'=>false,'error'=>'ip_required_for_wifi']);
    exit;
}

$safe_ip = preg_replace('/[^a-zA-Z0-9_\-\.]/','_', $_SESSION['ip']);
$dataFile = __DIR__."/ap_data_{$safe_ip}.json";
$apList = json_decode(file_get_contents($dataFile), true) ?: [];

$idx = null;
foreach($apList as $k=>$ap){ 
    if($ap['id']===$data['id']){ 
        $idx=$k; 
        break; 
    } 
}
if($idx===null){ 
    http_response_code(404); 
    echo json_encode(['success'=>false,'error'=>'not_found']); 
    exit; 
}

$oldIp = $apList[$idx]['ip'];
$oldType = $apList[$idx]['type'] ?? 'wifi';

if ($apType === 'wifi') {
    foreach($apList as $k=>$ap){ 
        if($k!=$idx && !empty($ap['ip']) && $ap['ip']===$data['ip']){ 
            echo json_encode(['success'=>false,'error'=>'duplicate_ip']); 
            exit; 
        }
    }
}

if(empty($data['lineColor']) && isset($apList[$idx]['lineColor'])){
    $data['lineColor'] = $apList[$idx]['lineColor'];
}

$apList[$idx] = [
    'id'        => $data['id'],
    'name'      => $data['name'],
    'ip'        => ($apType === 'odp') ? '' : ($data['ip'] ?? ''),
    'lat'       => (float)$data['lat'],
    'lng'       => (float)$data['lng'],
    'line'      => $data['line'] ?: null,
    'lineColor' => $data['lineColor'] ?? 'lime',
    'icon'      => $apList[$idx]['icon'] ?? 'wifi',
    'type'      => $apType
];

if(false === file_put_contents($dataFile, json_encode($apList, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE))){
    http_response_code(500);
    echo json_encode(['success'=>false,'error'=>'failed_save']); 
    exit;
}

$API = new RouterosAPI();
$status = 'skipped';
$bindingStatus = 'skipped';

if ($API->connect($_SESSION['ip'],$_SESSION['user'],$_SESSION['pass'])){

    if ($apType === 'wifi') {
        // ===== WIFI LOGIC =====
        $parentToken = null;
        if (!empty($data['line'])) {
            $foundParentName = null;
            foreach ($apList as $existingAp) {
                if (isset($existingAp['id']) && $existingAp['id'] === $data['line']) {
                    $foundParentName = trim($existingAp['name']);
                    break;
                }
            }
            $parentToken = $foundParentName ?: $data['line'];
        }

        if ($parentToken) {
            $commentValue = $data['name']."//".$data['lineColor']."/".$parentToken."//".$data['lat'].",".$data['lng'];
        } else {
            $commentValue = $data['name']."//".$data['lineColor']."///".$data['lat'].",".$data['lng'];
        }

        if ($oldIp !== $data['ip']) {
            $entries = $API->comm('/tool/netwatch/print',['?host'=>$oldIp]);
            if(!empty($entries[0]['.id'])){
                $API->comm('/tool/netwatch/remove', ['.id' => $entries[0]['.id']]);
            }
            $API->comm('/tool/netwatch/add',[
                'host'     => $data['ip'],
                'comment'  => $commentValue,
                'interval' => '10s',
                'timeout'  => '5s'
            ]);
            $status='updated';
        } else {
            $entries = $API->comm('/tool/netwatch/print',['?host'=>$data['ip']]);
            if(!empty($entries[0]['.id'])){
                $API->comm('/tool/netwatch/set', [
                    '.id'     => $entries[0]['.id'],
                    'comment' => $commentValue,
                    'interval' => '10s',
                    'timeout'  => '5s'
                ]);
                $status='ok';
            }
        }

        if ($oldIp !== $data['ip']) {
            $binding = $API->comm('/ip/hotspot/ip-binding/print',['?address'=>$oldIp]);
            if(!empty($binding[0]['.id'])){
                $API->comm('/ip/hotspot/ip-binding/remove',['.id' => $binding[0]['.id']]);
            }
            $API->comm('/ip/hotspot/ip-binding/add',[
                'address'   => $data['ip'],
                'to-address'=> $data['ip'],
                'comment'   => $commentValue,
                'type'      => 'bypassed'
            ]);
            $bindingStatus='updated';
        } else {
            $binding = $API->comm('/ip/hotspot/ip-binding/print',['?address'=>$data['ip']]);
            if(!empty($binding[0]['.id'])){
                $API->comm('/ip/hotspot/ip-binding/set',[
                    '.id'       => $binding[0]['.id'],
                    'comment'   => $commentValue,
                    'type'      => 'bypassed'
                ]);
                $bindingStatus='ok';
            }
        }
    } else if ($apType === 'odp') {
        // ===== ODP CERTIFICATE LOGIC =====
        
        $parentName = '';
        if (!empty($data['line'])) {
            foreach ($apList as $existingAp) {
                if (isset($existingAp['id']) && $existingAp['id'] === $data['line']) {
                    $parentName = trim($existingAp['name']);
                    break;
                }
            }
            if (empty($parentName)) {
                $parentName = $data['line'];
            }
        }

        // Hapus cert lama
        try {
            $oldCerts = $API->comm('/certificate/print');
            $foundCert = null;
            
            foreach ($oldCerts as $cert) {
                $certName = $cert['name'] ?? '';
                if (strpos($certName, $data['id'] . '#') === 0) {
                    $foundCert = $cert;
                    break;
                }
            }

            if ($foundCert && !empty($foundCert['.id'])) {
                $API->comm('/certificate/remove', ['.id' => $foundCert['.id']]);
            }
        } catch (Exception $e) {
            //error_log("Error removing old cert: " . $e->getMessage());//
        }

        // Format: ID#LAT#LNG#COLOR#PARENT#NAMA atau ID#LAT#LNG#COLOR#NAMA
        if (!empty($parentName)) {
            $certName = $data['id'] . '#' . $data['lat'] . '#' . $data['lng'] . '#' . $data['lineColor'] . '#' . $parentName . '#' . $data['name'];
        } else {
            $certName = $data['id'] . '#' . $data['lat'] . '#' . $data['lng'] . '#' . $data['lineColor'] . '#' . $data['name'];
        }

        // Buat cert baru
        try {
            $API->comm('/certificate/add', [
                'name' => $certName,
                'common-name' => $data['name'],
                'days-valid' => 3650
            ]);
            $status = 'certificate_updated';
            $bindingStatus = 'certificate_updated';
        } catch (Exception $e) {
            //error_log("Error adding certificate: " . $e->getMessage());//
            $status = 'error: ' . $e->getMessage();
            $bindingStatus = 'error: ' . $e->getMessage();
        }
    }

    $API->disconnect();
}

echo json_encode([
    'success'        => true,
    'ap'             => $apList[$idx],
    'mikrotik'       => $status,
    'hotspotBinding' => $bindingStatus
]);
?>