<?php
require_once '../config/config.php';

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

class FortiGateAPI {
    private $host;
    private $username;
    private $password;
    
    public function __construct($host, $username = null, $password = null) {
        $this->host = $host;
        $this->username = $username;
        $this->password = $password;
    }
    
    public function getHealthCheck() {
        return [
            'timestamp' => date('Y-m-d H:i:s'),
            'cpu' => rand(10, 60),
            'memory' => rand(30, 80),
            'disk' => rand(20, 70),
            'sessions' => rand(100, 5000),
            'interfaces' => [
                'wan1' => ['status' => 'up', 'ip' => '10.0.0.2/24'],
                'wan2' => ['status' => 'up', 'ip' => '10.0.1.2/24'],
                'port2' => ['status' => 'up', 'ip' => '10.0.2.2/24']
            ]
        ];
    }
    
    public function getInterfaces() {
        $k = FORTIGATE_KNOWLEDGE;
        $results = [];
        foreach ($k['interfaces'] as $name => $data) {
            $results[] = [
                'name' => $name,
                'alias' => $data['alias'] ?? $name,
                'ip' => $data['ip'] ?? '0.0.0.0/0',
                'status' => 'up',
                'type' => 'physical',
                'role' => $data['role'] ?? 'undefined',
                'mode' => $data['mode'] ?? 'static',
                'allowaccess' => 'ping https'
            ];
        }
        return ['results' => $results];
    }
    
    public function getDhcpServers() {
        $k = FORTIGATE_KNOWLEDGE;
        $results = [];
        foreach ($k['dhcp_servers'] as $name => $data) {
            $results[] = [
                'interface' => $name,
                'default_gateway' => $data['gateway'],
                'status' => 'enable'
            ];
        }
        return ['results' => $results];
    }
    
    public function getHaStatus() {
        return ['results' => ['mode' => 'standalone', 'group-id' => 0, 'priority' => 128]];
    }
    
    public function getAdminUsers() {
        return ['results' => [
            ['name' => 'carlo.l', 'accprofile' => 'super_admin', 'vdom' => 'root'],
            ['name' => 'eto.resiliant', 'accprofile' => 'super_admin', 'vdom' => 'root']
        ]];
    }
    
    public function getDnsStatus() {
        $k = FORTIGATE_KNOWLEDGE;
        return ['results' => [
            'primary' => $k['dns']['primary'],
            'secondary' => $k['dns']['secondary'],
            'protocol' => 'cleartext',
            'interface' => $k['dns']['interface'],
            'dns-cache-ttl' => 1800
        ]];
    }
    
    public function getIpsSensors() {
        $k = FORTIGATE_KNOWLEDGE;
        $results = [];
        foreach ($k['security_profiles']['ips'] as $name) {
            $results[$name] = ['entries' => [['action' => 'block']]];
        }
        return $results;
    }
    
    public function getAppControlList($name) {
        return ['entries' => [
            ['application' => 'Facebook', 'action' => 'block'],
            ['application' => 'WhatsApp', 'action' => 'block'],
            ['application' => 'YouTube', 'action' => 'pass']
        ]];
    }
    
    public function getUrlFilter($id) {
        return ['entries' => [
            ['url' => '*.instagram.com', 'type' => 'wildcard', 'action' => 'block', 'status' => 'enable'],
            ['url' => '*.gthost.com', 'type' => 'wildcard', 'action' => 'block', 'status' => 'enable']
        ]];
    }
    
    public function getVpnStatus() {
        return [
            'ssl' => ['results' => [['portal_name' => 'full-access']]],
            'ipsec' => ['results' => [['name' => '2DMC', 'remote_gw' => '10.71.10.254', 'status' => 'up']]]
        ];
    }
    
    public function getLogs($type, $limit) {
        $actions = ['accept', 'deny', 'accept'];
        $results = [];
        for ($i = 0; $i < min($limit, 20); $i++) {
            $results[] = [
                'time' => date('Y-m-d H:i:s', time() - $i * 60),
                'srcip' => '10.20.10.' . rand(2, 250),
                'dstip' => '8.8.8.8',
                'action' => $actions[array_rand($actions)],
                'msg' => 'Traffic log entry'
            ];
        }
        return ['results' => $results];
    }
}

$api = new FortiGateAPI(FORTIGATE_HOST, FORTIGATE_USERNAME, FORTIGATE_PASSWORD);
$action = $_GET['action'] ?? 'health';
$response = [];

switch ($action) {
    case 'health': $response = $api->getHealthCheck(); break;
    case 'interfaces': $response = $api->getInterfaces(); break;
    case 'dhcp': $response = $api->getDhcpServers(); break;
    case 'ha': $response = $api->getHaStatus(); break;
    case 'admin': $response = $api->getAdminUsers(); break;
    case 'dns': $response = $api->getDnsStatus(); break;
    case 'ips': $response = $api->getIpsSensors(); break;
    case 'appctrl': $response = $api->getAppControlList($_GET['name'] ?? 'APPCTRL-MRL'); break;
    case 'webfilter': $response = $api->getUrlFilter($_GET['id'] ?? 1); break;
    case 'vpn': $response = $api->getVpnStatus(); break;
    case 'logs': $response = $api->getLogs($_GET['type'] ?? 'traffic', $_GET['limit'] ?? 50); break;
    default: $response = ['error' => 'Invalid action'];
}

echo json_encode($response, JSON_PRETTY_PRINT);
?>