<?php
/**
 * Update Checker for SAS Client
 * File: check_updates.php
 * 
 * Checks for available updates from manage.apasaja.my
 * Called by dashboard.php or via AJAX
 */

session_start();
require_once 'config.php';

// Only allow logged-in admins
requireLogin();

// Define update server (only if not already defined)
if (!defined('UPDATE_CHECK_URL')) {
    define('UPDATE_CHECK_URL', 'https://manage.apasaja.my/update_check_api.php');
}

// ==========================================
// HELPER FUNCTIONS
// ==========================================

function getCurrentVersion($pdo) {
    try {
        $stmt = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = 'software_version'");
        $stmt->execute();
        $result = $stmt->fetch();
        
        if ($result) {
            return $result['setting_value'];
        }
        
        // Default version if not set
        return '1.0.0';
    } catch (Exception $e) {
        return '1.0.0';
    }
}

function getInstallationId($pdo) {
    try {
        $stmt = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = 'installation_id'");
        $stmt->execute();
        $result = $stmt->fetch();
        
        if ($result) {
            return $result['setting_value'];
        }
        
        // Generate new if not exists
        $installationId = hash('sha256', $_SERVER['HTTP_HOST'] . microtime(true) . bin2hex(random_bytes(16)));
        
        $stmt = $pdo->prepare("INSERT INTO system_settings (setting_key, setting_value) VALUES ('installation_id', ?)");
        $stmt->execute([$installationId]);
        
        return $installationId;
    } catch (Exception $e) {
        return 'unknown';
    }
}

function getLicenseData() {
    if (!file_exists('license.key')) {
        return null;
    }
    
    $licenseContent = file_get_contents('license.key');
    $key = hash('sha256', $_SERVER['HTTP_HOST'] . $_SERVER['DOCUMENT_ROOT'], true);
    $decoded = base64_decode($licenseContent);
    
    if (strlen($decoded) <= 16) {
        return null;
    }
    
    $iv = substr($decoded, 0, 16);
    $encrypted = substr($decoded, 16);
    $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $key, 0, $iv);
    
    if (!$decrypted) {
        return null;
    }
    
    return json_decode($decrypted, true);
}

// ==========================================
// MAIN LOGIC
// ==========================================

$response = ['success' => false];

try {
    // Get current version
    $currentVersion = getCurrentVersion($pdo);
    
    // Get installation ID
    $installationId = getInstallationId($pdo);
    
    // Get license data
    $licenseData = getLicenseData();
    
    if (!$licenseData) {
        $response = [
            'success' => false,
            'message' => 'No valid license found'
        ];
    } else {
        // Prepare request to update server
        $requestData = [
            'license_key' => $licenseData['license_key'],
            'domain' => $_SERVER['HTTP_HOST'],
            'current_version' => $currentVersion,
            'installation_id' => $installationId
        ];
        
        $options = [
            'http' => [
                'header' => "Content-Type: application/json\r\n",
                'method' => 'POST',
                'content' => json_encode($requestData),
                'timeout' => 10
            ],
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false
            ]
        ];
        
        $context = stream_context_create($options);
        $result = @file_get_contents(UPDATE_CHECK_URL, false, $context);
        
        if ($result === false) {
            $response = [
                'success' => false,
                'message' => 'Could not connect to update server'
            ];
        } else {
            $serverResponse = json_decode($result, true);
            
            if ($serverResponse && $serverResponse['success']) {
                // Cache the result
                $cacheData = [
                    'checked_at' => date('Y-m-d H:i:s'),
                    'response' => $serverResponse
                ];
                
                file_put_contents(__DIR__ . '/cache/update_check.json', json_encode($cacheData));
                
                $response = $serverResponse;
            } else {
                $response = $serverResponse ?: ['success' => false, 'message' => 'Invalid server response'];
            }
        }
    }
    
} catch (Exception $e) {
    $response = [
        'success' => false,
        'message' => 'Error checking for updates: ' . $e->getMessage()
    ];
}

// ==========================================
// OUTPUT
// ==========================================

header('Content-Type: application/json');
echo json_encode($response);
?>