<?php
require_once __DIR__ . '/../site-identity.php';
/**
 * Integrated Admin Authentication System - FIXED VERSION
 * Simplified untuk mengatasi masalah database connection
 */

class IntegratedAdminAuth {
    private $pdo;
    
    public function __construct() {
        try {
            $host = defined('DB_HOST') ? DB_HOST : 'localhost';
            $dbname = defined('DB_NAME') ? DB_NAME : 'linkslot88_autoprediksikjmngpfjr941';
            $user = defined('DB_USER') ? DB_USER : 'linkslot88_autopred97841dellon9781a';
            $pass = defined('DB_PASS') ? DB_PASS : 'prediksiautomanjur9854ikjbnienfxx';

            $this->pdo = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8mb4", $user, $pass, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            ]);
        } catch (PDOException $e) {
            throw new Exception("Cannot connect to database: " . $e->getMessage());
        }
    }
    
    /**
     * Login function
     */
    public function login($username, $password, $loginType = 'auto') {
        try {
            // Try master admin first
            if ($loginType === 'auto' || $loginType === 'master') {
                $masterAdmin = $this->authenticateMasterAdmin($username, $password);
                if ($masterAdmin) {
                    return [
                        'success' => true,
                        'admin_data' => $masterAdmin,
                        'message' => 'Login berhasil sebagai Master Admin',
                        'admin_type' => 'master'
                    ];
                }
            }
            
            // Try site admin
            if ($loginType === 'auto' || $loginType === 'sub') {
                $siteAdmin = $this->authenticateSiteAdmin($username, $password);
                if ($siteAdmin) {
                    return [
                        'success' => true,
                        'admin_data' => $siteAdmin,
                        'message' => 'Login berhasil sebagai Site Admin',
                        'admin_type' => 'site'
                    ];
                }
            }
            
            return [
                'success' => false,
                'message' => 'Username atau password salah',
                'admin_type' => null
            ];
            
        } catch (Exception $e) {
            error_log("Login error: " . $e->getMessage());
            return [
                'success' => false,
                'message' => 'Terjadi kesalahan sistem',
                'admin_type' => null
            ];
        }
    }
    
    /**
     * Authenticate master admin
     */
    private function authenticateMasterAdmin($username, $password) {
        $stmt = $this->pdo->prepare("
            SELECT * FROM admin_users 
            WHERE username = ? AND is_active = 1 AND role = 'master_admin'
        ");
        $stmt->execute([$username]);
        $admin = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($admin && md5($password) === $admin['password']) {
            // Update last login
            $updateStmt = $this->pdo->prepare("UPDATE admin_users SET last_login = NOW() WHERE id = ?");
            $updateStmt->execute([$admin['id']]);
            
            // Create session ID
            $sessionId = 'master_' . bin2hex(random_bytes(16)) . '_' . $admin['id'];
            
            return [
                'id' => 'master_' . $admin['id'],
                'original_id' => $admin['id'],
                'username' => $admin['username'],
                'email' => 'master@autoprediksi.com',
                'full_name' => 'Master Admin',
                'site_id' => 1,
                'site_name' => 'Autoprediksi',
                'domain' => 'localhost',
                'is_master' => true,
                'admin_type' => 'master',
                'session_id' => $sessionId,
                'permissions' => $this->getAllPermissions(),
                'market_access' => $this->getAllMarkets(),
                'login_time' => time()
            ];
        }
        
        return false;
    }
    
    /**
     * Authenticate site admin
     */
    private function authenticateSiteAdmin($username, $password) {
        $stmt = $this->pdo->prepare("
            SELECT * FROM admin_users 
            WHERE username = ? AND is_active = 1 AND role = 'site_admin'
        ");
        $stmt->execute([$username]);
        $admin = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($admin && md5($password) === $admin['password']) {
            // Update last login
            $updateStmt = $this->pdo->prepare("UPDATE admin_users SET last_login = NOW() WHERE id = ?");
            $updateStmt->execute([$admin['id']]);
            
            // Create session ID
            $sessionId = 'site_' . bin2hex(random_bytes(16)) . '_' . $admin['id'];
            
            return [
                'id' => 'site_' . $admin['id'],
                'original_id' => $admin['id'],
                'username' => $admin['username'],
                'email' => $admin['site_access'] . '@autoprediksi.com',
                'full_name' => 'Site Admin ' . ucfirst($admin['site_access']),
                'site_id' => $admin['id'],
                'site_name' => ucfirst($admin['site_access']),
                'domain' => $admin['site_access'] . '.localhost',
                'site_access' => $admin['site_access'],
                'is_master' => false,
                'admin_type' => 'site',
                'session_id' => $sessionId,
                'permissions' => $this->getSitePermissions(),
                'market_access' => $this->getSiteMarkets(),
                'login_time' => time()
            ];
        }
        
        return false;
    }
    
    /**
     * Validate session
     */
    public function validateSession($sessionId) {
        if (isset($_SESSION['integrated_admin_session_id']) && 
            $_SESSION['integrated_admin_session_id'] === $sessionId) {
            return $_SESSION['integrated_admin_data'] ?? false;
        }
        return false;
    }
    
    /**
     * Get all permissions (for master admin)
     */
    private function getAllPermissions() {
        return [
            'manage_all_sites' => ['name' => 'Manage All Sites', 'description' => 'Can manage all sites'],
            'manage_admins' => ['name' => 'Manage Admins', 'description' => 'Can manage admin users'],
            'manage_markets' => ['name' => 'Manage Markets', 'description' => 'Can manage market schedules'],
            'manage_settings' => ['name' => 'Manage Settings', 'description' => 'Can manage web settings'],
            'manage_support' => ['name' => 'Manage Support', 'description' => 'Can manage support tickets'],
            'manage_results' => ['name' => 'Manage Results', 'description' => 'Can manage game results'],
            'view_all_data' => ['name' => 'View All Data', 'description' => 'Can view all site data']
        ];
    }
    
    /**
     * Get site permissions (for site admin)
     */
    private function getSitePermissions() {
        return [
            'manage_site_content' => ['name' => 'Manage Site Content', 'description' => 'Can manage site content'],
            'manage_markets' => ['name' => 'Manage Markets', 'description' => 'Can manage market schedules'],
            'manage_settings' => ['name' => 'Manage Settings', 'description' => 'Can manage web settings'],
            'manage_support' => ['name' => 'Manage Support', 'description' => 'Can manage support tickets'],
            'manage_results' => ['name' => 'Manage Results', 'description' => 'Can manage game results'],
            'view_site_data' => ['name' => 'View Site Data', 'description' => 'Can view site data']
        ];
    }
    
    /**
     * Get all markets (for master admin)
     */
    private function getAllMarkets() {
        $markets = ['SGP', 'HK', 'SDY', 'PCSO', 'PCB', 'CN', 'TWN', 'JP', 'KR'];
        $marketAccess = [];
        
        foreach ($markets as $market) {
            $marketAccess[$market] = [
                'can_view' => true,
                'can_edit' => true,
                'can_manage_results' => true
            ];
        }
        
        return $marketAccess;
    }
    
    /**
     * Get site markets (for site admin)
     */
    private function getSiteMarkets() {
        $markets = ['SGP', 'HK', 'SDY'];
        $marketAccess = [];
        
        foreach ($markets as $market) {
            $marketAccess[$market] = [
                'can_view' => true,
                'can_edit' => true,
                'can_manage_results' => false
            ];
        }
        
        return $marketAccess;
    }
    
    /**
     * Get accessible markets for current admin (public method)
     */
    public function getAccessibleMarkets($adminData = null, $accessType = 'can_view') {
        // If no admin data provided, use session data
        if (!$adminData && !isset($_SESSION['integrated_admin_data'])) {
            return [];
        }
        
        $adminData = $adminData ?: $_SESSION['integrated_admin_data'];
        
        $allMarkets = [];
        if ($adminData['is_master']) {
            $allMarkets = $this->getAllMarkets();
        } else {
            $allMarkets = $this->getSiteMarkets();
        }
        
        // Filter by access type if specified
        $accessibleMarkets = [];
        foreach ($allMarkets as $market => $permissions) {
            if ($permissions[$accessType] ?? false) {
                $accessibleMarkets[$market] = $permissions;
            }
        }
        
        return $accessibleMarkets;
    }
    
    /**
     * Check if admin has specific permission
     */
    public function hasPermission($adminData = null, $permissionKey = null) {
        // If no admin data provided, use session data
        if (!$adminData && !isset($_SESSION['integrated_admin_data'])) {
            return false;
        }
        
        $adminData = $adminData ?: $_SESSION['integrated_admin_data'];
        
        // Master admin has all permissions
        if ($adminData['is_master']) {
            return true;
        }
        
        // Check if site admin has the specific permission
        $permissions = $adminData['permissions'] ?? $this->getSitePermissions();
        
        return isset($permissions[$permissionKey]);
    }
    
    /**
     * Check if admin has market access
     */
    public function hasMarketAccess($adminData = null, $marketName = null, $accessType = 'can_view') {
        // If no admin data provided, use session data
        if (!$adminData && !isset($_SESSION['integrated_admin_data'])) {
            return false;
        }
        
        $adminData = $adminData ?: $_SESSION['integrated_admin_data'];
        
        // Master admin has access to all markets
        if ($adminData['is_master']) {
            return true;
        }
        
        // Check market access from admin data
        $marketAccess = $adminData['market_access'] ?? $this->getSiteMarkets();
        
        return isset($marketAccess[$marketName][$accessType]) && $marketAccess[$marketName][$accessType];
    }
    
    /**
     * Get admin ID from admin data
     */
    public function getAdminId($adminData = null) {
        if (!$adminData && !isset($_SESSION['integrated_admin_data'])) {
            return 0;
        }
        
        $adminData = $adminData ?: $_SESSION['integrated_admin_data'];
        return $adminData['original_id'] ?? $adminData['id'] ?? 0;
    }
    
    /**
     * Log activity
     */
    public function logActivity($adminId, $actionType, $description, $targetTable = null, $targetId = null, $adminType = 'sub') {
        error_log("Admin Activity: $adminType Admin $adminId - $actionType: $description");
        return true;
    }
    
    /**
     * Logout
     */
    public function logout($sessionId = null) {
        // Clear session data
        if (isset($_SESSION['integrated_admin_session_id'])) {
            unset($_SESSION['integrated_admin_session_id']);
        }
        if (isset($_SESSION['integrated_admin_data'])) {
            unset($_SESSION['integrated_admin_data']);
        }
        if (isset($_SESSION['integrated_login_time'])) {
            unset($_SESSION['integrated_login_time']);
        }
        
        // Clear all admin-related sessions
        session_unset();
        session_destroy();
        return true;
    }
}
?>