<?php
/**
 * SAS Complete Integration Module
 * 
 * Combines: License Protection + Trial System + Analytics Tracking
 * 
 * ADD THIS TO YOUR config.php (after database connection)
 */

// ==========================================
// CONFIGURATION
// ==========================================

define('LICENSE_SERVER', 'https://manage.apasaja.my/license_server.php');
define('ANALYTICS_SERVER', 'https://manage.apasaja.my/analytics_collect.php');
define('TRIAL_DAYS', 30);
define('ANALYTICS_CACHE_HOURS', 24);

// ==========================================
// COMPLETE INTEGRATION CLASS
// ==========================================

class SASIntegration {
    private $pdo;
    private $licenseFile;
    private $analyticsCache;
    private $licenseData = null;
    
    public function __construct($pdo) {
        $this->pdo = $pdo;
        
        // Set paths relative to where sas_integration.php is located (root)
        $this->licenseFile = __DIR__ . '/license.key';
        $this->analyticsCache = __DIR__ . '/cache/analytics_last_sent.txt';
        
        // Ensure cache directory exists
        $cacheDir = __DIR__ . '/cache';
        if (!is_dir($cacheDir)) {
            @mkdir($cacheDir, 0755, true);
        }
        
        // Load license
        $this->loadLicense();
        
        // Check license validity
        $this->checkLicense();
    }
    
    // ==========================================
    // LICENSE MANAGEMENT
    // ==========================================
    
    /**
     * Load and decrypt license
     */
    private function loadLicense() {
        if (!file_exists($this->licenseFile)) {
            return;
        }
        
        $encrypted = file_get_contents($this->licenseFile);
        $key = hash('sha256', $_SERVER['HTTP_HOST'] . $_SERVER['DOCUMENT_ROOT'], true);
        $decoded = base64_decode($encrypted);
        
        if (strlen($decoded) < 16) {
            return;
        }
        
        $iv = substr($decoded, 0, 16);
        $encrypted = substr($decoded, 16);
        $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $key, 0, $iv);
        
        $this->licenseData = json_decode($decrypted, true);
    }
    
    /**
     * Check if license is valid and not expired
     */
    private function checkLicense() {
        // No license = redirect to activation
        if (!$this->licenseData) {
            $this->redirectToActivation('No license found');
        }
        
        // Check expiration
        if (isset($this->licenseData['expires_at']) && $this->licenseData['expires_at']) {
            $expiryTime = strtotime($this->licenseData['expires_at']);
            if ($expiryTime < time()) {
                $this->handleExpiredLicense();
            }
        }
        
        // Check if suspended
        if (isset($this->licenseData['status']) && $this->licenseData['status'] === 'suspended') {
            $this->showSuspendedPage();
        }
    }
    
    /**
     * Handle expired license
     */
    private function handleExpiredLicense() {
        $isTrial = $this->isTrial();
        
        if ($isTrial) {
            // Trial expired - show upgrade page
            $this->showTrialExpiredPage();
        } else {
            // Paid license expired - show renewal page
            $this->showLicenseExpiredPage();
        }
    }
    
    /**
     * Check if trial license
     */
    public function isTrial() {
        return isset($this->licenseData['status']) && $this->licenseData['status'] === 'trial';
    }
    
    /**
     * Get days remaining
     */
    public function getDaysRemaining() {
        if (!$this->licenseData || !isset($this->licenseData['expires_at'])) {
            return null;
        }
        
        $expiryTime = strtotime($this->licenseData['expires_at']);
        $now = time();
        $diff = $expiryTime - $now;
        
        return max(0, floor($diff / 86400));
    }
    
    /**
     * Should show trial nag
     */
    public function shouldShowNag() {
        if (!$this->isTrial()) {
            return false;
        }
        
        $daysRemaining = $this->getDaysRemaining();
        return $daysRemaining !== null && $daysRemaining <= 7;
    }
    
    /**
     * Render trial nag banner
     */
    public function renderNagBanner() {
        if (!$this->shouldShowNag()) {
            return '';
        }
        
        $daysRemaining = $this->getDaysRemaining();
        $urgency = $daysRemaining <= 3 ? 'danger' : 'warning';
        
        ob_start();
        include __DIR__ . '/includes/nag_banner.php';
        return ob_get_clean();
    }
    
    /**
     * Redirect to activation
     */
    private function redirectToActivation($reason = '') {
        // Allow activation page itself to load
        $currentPage = basename($_SERVER['PHP_SELF']);
        if ($currentPage === 'activate_license.php') {
            return;
        }
        
        // Use absolute path from document root
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'];
        $activationUrl = $protocol . '://' . $host . '/activate_license.php?reason=' . urlencode($reason);
        
        header('Location: ' . $activationUrl);
        exit;
    }
    
    /**
     * Show trial expired page
     */
    private function showTrialExpiredPage() {
        http_response_code(403);
        include __DIR__ . '/includes/trial_expired.php';
        exit;
    }
    
    /**
     * Show license expired page
     */
    private function showLicenseExpiredPage() {
        http_response_code(403);
        include __DIR__ . '/includes/license_expired.php';
        exit;
    }
    
    /**
     * Show suspended page
     */
    private function showSuspendedPage() {
        http_response_code(403);
        include __DIR__ . '/includes/license_suspended.php';
        exit;
    }
    
    // ==========================================
    // ANALYTICS TRACKING
    // ==========================================
    
    /**
     * Check if should send analytics
     */
    private function shouldSendAnalytics() {
        if (!file_exists($this->analyticsCache)) {
            return true;
        }
        
        $lastSent = (int)file_get_contents($this->analyticsCache);
        $hoursSince = (time() - $lastSent) / 3600;
        
        return $hoursSince >= ANALYTICS_CACHE_HOURS;
    }
    
    /**
     * Auto-send analytics (call on admin login)
     */
    public function sendAnalytics() {
        if (!$this->shouldSendAnalytics()) {
            return false;
        }
        
        // Gather statistics
        $stats = [
            'installation_id' => $this->getInstallationId(),
            'total_users' => $this->getCount('users'),
            'total_students' => $this->getCount('students'),
            'total_classes' => $this->getCount('classes'),
            'total_teachers' => $this->getCount('users', "role LIKE '%teacher%'"),
            'total_attendance_today' => $this->getCount('attendance_logs', "DATE(scan_time) = CURDATE()"),
            'active_users_today' => $this->getActiveUsersToday(),
            'total_bookings' => $this->getCount('bookings'),
            'total_announcements' => $this->getCount('announcements'),
            'domain' => $_SERVER['HTTP_HOST'] ?? null,
            'php_version' => PHP_VERSION,
            'mysql_version' => $this->getMySQLVersion(),
            'software_version' => '1.0',
            'license_status' => $this->licenseData['status'] ?? 'unknown',
            'is_trial' => $this->isTrial(),
            'recorded_at' => date('Y-m-d H:i:s')
        ];
        
        // Send to analytics server
        $this->sendToAnalyticsServer('daily_stats', $stats);
        
        // Update cache
        file_put_contents($this->analyticsCache, time());
        
        return true;
    }
    
    /**
     * Track feature usage
     */
    public function trackFeature($featureName, $metadata = []) {
        $data = [
            'installation_id' => $this->getInstallationId(),
            'feature_name' => $featureName,
            'metadata' => json_encode($metadata),
            'timestamp' => date('Y-m-d H:i:s')
        ];
        
        $this->sendToAnalyticsServer('feature_usage', $data);
    }
    
    /**
     * Track user login
     */
    public function trackLogin($userId, $role) {
        $data = [
            'installation_id' => $this->getInstallationId(),
            'event_type' => 'user_login',
            'role' => $role,
            'timestamp' => date('Y-m-d H:i:s')
        ];
        
        $this->sendToAnalyticsServer('event', $data);
        
        // Auto-send analytics on admin login
        if (strpos($role, 'admin') !== false) {
            $this->sendAnalytics();
        }
    }
    
    /**
     * Get installation ID
     */
    private function getInstallationId() {
        if (isset($this->licenseData['installation_id'])) {
            return $this->licenseData['installation_id'];
        }
        
        try {
            $stmt = $this->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
            $installationId = hash('sha256', $_SERVER['HTTP_HOST'] . microtime(true) . bin2hex(random_bytes(16)));
            
            $stmt = $this->pdo->prepare("INSERT INTO system_settings (setting_key, setting_value) VALUES ('installation_id', ?)");
            $stmt->execute([$installationId]);
            
            return $installationId;
        } catch (Exception $e) {
            return 'unknown';
        }
    }
    
    /**
     * Send to analytics server
     */
    private function sendToAnalyticsServer($eventType, $data) {
        $data['event_type'] = $eventType;
        $data['sent_at'] = date('Y-m-d H:i:s');
        
        $options = [
            'http' => [
                'header' => "Content-Type: application/json\r\n",
                'method' => 'POST',
                'content' => json_encode($data),
                'timeout' => 3
            ],
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false
            ]
        ];
        
        $context = stream_context_create($options);
        @file_get_contents(ANALYTICS_SERVER, false, $context);
    }
    
    // ==========================================
    // HELPER FUNCTIONS
    // ==========================================
    
    private function getCount($table, $where = '1=1') {
        try {
            $stmt = $this->pdo->query("SELECT COUNT(*) FROM {$table} WHERE {$where}");
            return (int)$stmt->fetchColumn();
        } catch (Exception $e) {
            return 0;
        }
    }
    
    private function getActiveUsersToday() {
        try {
            $stmt = $this->pdo->query("SELECT COUNT(DISTINCT user_id) FROM attendance_logs WHERE DATE(scan_time) = CURDATE()");
            return (int)$stmt->fetchColumn();
        } catch (Exception $e) {
            return 0;
        }
    }
    
    private function getMySQLVersion() {
        try {
            return $this->pdo->query('SELECT VERSION()')->fetchColumn();
        } catch (Exception $e) {
            return 'Unknown';
        }
    }
}

// ==========================================
// USAGE IN YOUR config.php:
// ==========================================

// ==========================================
// END OF SAS INTEGRATION
// ==========================================
