<?php
/**
 * Session Wrapper for Multi-Admin Support
 * Prevents session conflicts between multiple logged-in admins
 */

class AdminSessionManager {
    private $pdo;
    
    public function __construct($database = null) {
        if (!$database) {
            require_once __DIR__ . "/database.php";
            $database = new Database();
        }
        $this->pdo = $database->getConnection();
    }
    
    /**
     * Create unique session for admin
     */
    public function createAdminSession($adminData) {
        $sessionToken = $this->generateUniqueToken();
        $adminId = is_string($adminData["original_id"]) ? 
                   (int)filter_var($adminData["original_id"], FILTER_SANITIZE_NUMBER_INT) : 
                   $adminData["original_id"] ?? $adminData["id"] ?? 1;
        $siteId = $adminData["site_id"] ?? 1;
        
        // Store session using existing table structure
        // Use id column for session_token, store admin_data in user_agent temporarily
        $stmt = $this->pdo->prepare("
            INSERT INTO admin_sessions 
            (id, admin_id, site_id, ip_address, user_agent, last_activity, expires_at) 
            VALUES (?, ?, ?, ?, ?, NOW(), DATE_ADD(NOW(), INTERVAL 24 HOUR))
            ON DUPLICATE KEY UPDATE
                user_agent = VALUES(user_agent),
                last_activity = NOW(),
                expires_at = DATE_ADD(NOW(), INTERVAL 24 HOUR)
        ");
        
        $stmt->execute([
            $sessionToken,
            $adminId,
            $siteId,
            $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1',
            json_encode($adminData) // Store admin_data in user_agent field
        ]);
        
        return $sessionToken;
    }
    
    /**
     * Validate admin session
     */
    public function validateAdminSession($sessionToken) {
        if (!$sessionToken) return false;
        
        $stmt = $this->pdo->prepare("
            SELECT user_agent, site_id, admin_id 
            FROM admin_sessions 
            WHERE id = ? 
            AND expires_at > NOW()
        ");
        $stmt->execute([$sessionToken]);
        $session = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($session) {
            // Update last activity
            $updateStmt = $this->pdo->prepare("
                UPDATE admin_sessions 
                SET last_activity = NOW() 
                WHERE id = ?
            ");
            $updateStmt->execute([$sessionToken]);
            
            // Decode admin_data from user_agent field
            $adminData = json_decode($session["user_agent"], true);
            return $adminData ?: false;
        }
        
        return false;
    }
    
    /**
     * Set site context for current session
     */
    public function setSiteContext($sessionToken, $siteId) {
        $adminData = $this->validateAdminSession($sessionToken);
        if (!$adminData) return false;
        
        // Update current site context
        $_SESSION["admin_current_site_" . $adminData["original_id"]] = $siteId;
        
        return true;
    }
    
    /**
     * Get site context for current session
     */
    public function getSiteContext($sessionToken) {
        $adminData = $this->validateAdminSession($sessionToken);
        if (!$adminData) return 1;
        
        $adminId = $adminData["original_id"] ?? $adminData["id"];
        return $_SESSION["admin_current_site_" . $adminId] ?? $adminData["site_id"] ?? 1;
    }
    
    /**
     * Logout admin session
     */
    public function logoutAdminSession($sessionToken) {
        $stmt = $this->pdo->prepare("DELETE FROM admin_sessions WHERE id = ?");
        $stmt->execute([$sessionToken]);
        
        return true;
    }
    
    /**
     * Generate unique session token
     */
    private function generateUniqueToken() {
        return bin2hex(random_bytes(32)) . "_" . time();
    }
    
    /**
     * Clean expired sessions
     */
    public function cleanExpiredSessions() {
        $stmt = $this->pdo->prepare("DELETE FROM admin_sessions WHERE expires_at < NOW()");
        $stmt->execute();
        
        return $stmt->rowCount();
    }
}
