<?php
session_start();

require_once '../includes/database.php';
require_once '../includes/site-manager.php';
require_once '../includes/multi-tenant-auth.php';

$database = new Database();
$pdo = $database->getConnection();
$siteManager = new SiteManager($database);
$auth = new MultiTenantAuth($pdo);

// Check if logged in
if (!isset($_SESSION['admin_session_id'])) {
    header('Location: login-multi.php');
    exit;
}

// Validate session and get admin data
$adminData = $_SESSION['admin_data'] ?? null;
if (!$adminData) {
    header('Location: login-multi.php');
    exit;
}

$currentSite = $siteManager->getCurrentSite();

// Get admin permissions for menu display
$isMaster = isset($adminData['is_master']) && $adminData['is_master'];
$permissions = $adminData['permissions'] ?? [];
$marketAccess = $adminData['market_access'] ?? [];

// Get some stats for dashboard
try {
    // Count total sites (master admin only)
    $totalSites = 0;
    if ($isMaster) {
        $stmt = $pdo->query("SELECT COUNT(*) FROM sites");
        $totalSites = $stmt->fetchColumn();
    }
    
    // Count sub-admins for current site (master admin only)
    $totalSubAdmins = 0;
    if ($isMaster) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM site_admins WHERE site_id = ?");
        $stmt->execute([$adminData['site_id']]);
        $totalSubAdmins = $stmt->fetchColumn();
    }
    
    // Count accessible markets
    $accessibleMarkets = $isMaster ? 9 : count($marketAccess); // Assuming 9 total markets
    
    // Recent activity (if has permission)
    $recentActivity = [];
    if ($auth->hasPermission($adminData, 'view_analytics') || $isMaster) {
        $stmt = $pdo->prepare("
            SELECT action_type, action_description, created_at 
            FROM admin_activity_log_multi 
            WHERE admin_id = ? 
            ORDER BY created_at DESC 
            LIMIT 5
        ");
        $stmt->execute([$adminData['id'] ?? 0]);
        $recentActivity = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
} catch (Exception $e) {
    error_log("Dashboard error: " . $e->getMessage());
    $totalSites = $totalSubAdmins = $accessibleMarkets = 0;
    $recentActivity = [];
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Admin - <?= htmlspecialchars($currentSite['site_name'] ?? 'Autoprediksi') ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: <?= htmlspecialchars($currentSite['primary_color'] ?? '#25d366') ?>;
        }
        .sidebar {
            background: var(--primary-color);
            min-height: 100vh;
            position: fixed;
            top: 0;
            left: 0;
            width: 250px;
            z-index: 1000;
        }
        .main-content {
            margin-left: 250px;
            padding: 20px;
        }
        .stat-card {
            background: linear-gradient(135deg, var(--primary-color), rgba(37, 211, 102, 0.8));
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .stat-card h3 {
            font-size: 2.5rem;
            font-weight: bold;
            margin: 0;
        }
        .admin-info {
            background: rgba(255,255,255,0.1);
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .permission-badge {
            font-size: 0.8rem;
            margin: 2px;
        }
        .nav-link {
            color: rgba(255,255,255,0.8) !important;
            padding: 10px 20px;
            border-radius: 8px;
            margin: 2px 10px;
            transition: all 0.3s ease;
        }
        .nav-link:hover {
            background: rgba(255,255,255,0.1);
            color: white !important;
        }
        .nav-link.active {
            background: rgba(255,255,255,0.2);
            color: white !important;
        }
        .nav-link.disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        @media (max-width: 768px) {
            .sidebar {
                position: relative;
                width: 100%;
                min-height: auto;
            }
            .main-content {
                margin-left: 0;
            }
        }
    </style>
</head>
<body>
    <div class="sidebar text-white">
        <div class="p-3">
            <!-- Admin Info -->
            <div class="admin-info">
                <div class="d-flex align-items-center mb-2">
                    <?php if ($isMaster): ?>
                        <i class="bi bi-crown me-2 text-warning"></i>
                        <strong>Master Admin</strong>
                    <?php else: ?>
                        <i class="bi bi-person me-2"></i>
                        <strong><?= htmlspecialchars($adminData['username']) ?></strong>
                    <?php endif; ?>
                </div>
                <small class="text-light">
                    <?= htmlspecialchars($adminData['full_name'] ?? $adminData['email']) ?>
                </small>
                <div class="mt-2">
                    <small class="text-light">
                        <i class="bi bi-globe2 me-1"></i>
                        <?= htmlspecialchars($currentSite['site_name'] ?? 'Autoprediksi') ?>
                    </small>
                </div>
            </div>
            
            <!-- Navigation Menu -->
            <nav class="nav flex-column">
                <a href="dashboard-multi.php" class="nav-link active">
                    <i class="bi bi-house me-2"></i>Dashboard
                </a>
                
                <!-- Master Admin Only -->
                <?php if ($isMaster): ?>
                    <a href="sites.php" class="nav-link">
                        <i class="bi bi-globe me-2"></i>Kelola Situs
                    </a>
                    <a href="sub-admins.php" class="nav-link">
                        <i class="bi bi-people me-2"></i>Kelola Sub Admin
                    </a>
                    <hr class="text-white-50">
                <?php endif; ?>
                
                <!-- Color Management -->
                <?php if ($auth->hasPermission($adminData, 'manage_colors')): ?>
                    <a href="sites.php#colors" class="nav-link">
                        <i class="bi bi-palette me-2"></i>Kelola Warna
                    </a>
                <?php else: ?>
                    <span class="nav-link disabled">
                        <i class="bi bi-palette me-2"></i>Kelola Warna
                    </span>
                <?php endif; ?>
                
                <!-- Content Management -->
                <?php if ($auth->hasPermission($adminData, 'manage_content')): ?>
                    <a href="content-manager.php" class="nav-link">
                        <i class="bi bi-file-text me-2"></i>Kelola Konten
                    </a>
                <?php else: ?>
                    <span class="nav-link disabled">
                        <i class="bi bi-file-text me-2"></i>Kelola Konten
                    </span>
                <?php endif; ?>
                
                <!-- Results Management -->
                <?php if ($auth->hasPermission($adminData, 'manage_results')): ?>
                    <a href="results-manager.php" class="nav-link">
                        <i class="bi bi-trophy me-2"></i>Kelola Hasil
                    </a>
                <?php else: ?>
                    <span class="nav-link disabled">
                        <i class="bi bi-trophy me-2"></i>Kelola Hasil
                    </span>
                <?php endif; ?>
                
                <!-- Markets Management -->
                <?php if ($auth->hasPermission($adminData, 'manage_markets')): ?>
                    <a href="markets.php" class="nav-link">
                        <i class="bi bi-shop me-2"></i>Kelola Pasaran
                    </a>
                    <!-- Assign Pasaran to Site (visible to those who can manage markets) -->
                    <a href="site-markets.php" class="nav-link">
                        <i class="bi bi-diagram-3 me-2"></i>Assign Pasaran ke Situs
                    </a>
                <?php else: ?>
                    <span class="nav-link disabled">
                        <i class="bi bi-shop me-2"></i>Kelola Pasaran
                    </span>
                <?php endif; ?>
                
                <!-- Buku Mimpi -->
                <?php if ($auth->hasPermission($adminData, 'manage_buku_mimpi')): ?>
                    <a href="buku-mimpi-manager.php" class="nav-link">
                        <i class="bi bi-book me-2"></i>Buku Mimpi
                    </a>
                <?php else: ?>
                    <span class="nav-link disabled">
                        <i class="bi bi-book me-2"></i>Buku Mimpi
                    </span>
                <?php endif; ?>
                
                <!-- Live Draw -->
                <?php if ($auth->hasPermission($adminData, 'manage_livedraw')): ?>
                    <a href="livedraw-manager.php" class="nav-link">
                        <i class="bi bi-broadcast me-2"></i>Live Draw
                    </a>
                <?php else: ?>
                    <span class="nav-link disabled">
                        <i class="bi bi-broadcast me-2"></i>Live Draw
                    </span>
                <?php endif; ?>
                
                <!-- Prediksi -->
                <?php if ($auth->hasPermission($adminData, 'manage_prediksi')): ?>
                    <a href="prediksi-manager.php" class="nav-link">
                        <i class="bi bi-lightbulb me-2"></i>Prediksi
                    </a>
                <?php else: ?>
                    <span class="nav-link disabled">
                        <i class="bi bi-lightbulb me-2"></i>Prediksi
                    </span>
                <?php endif; ?>
                
                <!-- Analytics -->
                <?php if ($auth->hasPermission($adminData, 'view_analytics')): ?>
                    <a href="analytics.php" class="nav-link">
                        <i class="bi bi-graph-up me-2"></i>Analytics
                    </a>
                <?php else: ?>
                    <span class="nav-link disabled">
                        <i class="bi bi-graph-up me-2"></i>Analytics
                    </span>
                <?php endif; ?>
                
                <hr class="text-white-50">
                <a href="logout-multi.php" class="nav-link">
                    <i class="bi bi-box-arrow-right me-2"></i>Logout
                </a>
            </nav>
        </div>
    </div>
    
    <div class="main-content">
        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
            <h1 class="h2">Dashboard</h1>
            <div class="btn-toolbar mb-2 mb-md-0">
                <div class="btn-group me-2">
                    <button type="button" class="btn btn-sm btn-outline-secondary">
                        <i class="bi bi-calendar3"></i>
                        <?= date('d M Y') ?>
                    </button>
                </div>
            </div>
        </div>
        
        <!-- Stats Cards -->
        <div class="row">
            <?php if ($isMaster): ?>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h3><?= $totalSites ?></h3>
                                <p class="mb-0">Total Situs</p>
                            </div>
                            <i class="bi bi-globe display-4 opacity-50"></i>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h3><?= $totalSubAdmins ?></h3>
                                <p class="mb-0">Sub Admin</p>
                            </div>
                            <i class="bi bi-people display-4 opacity-50"></i>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h3><?= $accessibleMarkets ?></h3>
                            <p class="mb-0">Pasaran Akses</p>
                        </div>
                        <i class="bi bi-shop display-4 opacity-50"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h3><?= count($permissions) ?></h3>
                            <p class="mb-0">Permissions</p>
                        </div>
                        <i class="bi bi-shield-check display-4 opacity-50"></i>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Main Content Row -->
        <div class="row">
            <!-- Permissions Overview -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="bi bi-shield-check me-2"></i>
                            Permissions Anda
                        </h5>
                    </div>
                    <div class="card-body">
                        <?php if ($isMaster): ?>
                            <div class="alert alert-success">
                                <i class="bi bi-crown me-2"></i>
                                <strong>Master Admin:</strong> Anda memiliki akses penuh ke semua fitur
                            </div>
                        <?php elseif (!empty($permissions)): ?>
                            <?php foreach ($permissions as $key => $permission): ?>
                                <span class="badge bg-primary permission-badge">
                                    <?= htmlspecialchars($permission['name']) ?>
                                </span>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="text-muted text-center py-3">
                                <i class="bi bi-exclamation-triangle display-1 mb-3"></i>
                                <p>Tidak ada permissions yang diberikan</p>
                                <small>Hubungi Master Admin untuk mengatur akses Anda</small>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Market Access -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="bi bi-shop me-2"></i>
                            Akses Pasaran
                        </h5>
                    </div>
                    <div class="card-body">
                        <?php if ($isMaster): ?>
                            <div class="alert alert-info">
                                <i class="bi bi-globe2 me-2"></i>
                                <strong>Master Admin:</strong> Akses ke semua pasaran tersedia
                            </div>
                        <?php elseif (!empty($marketAccess)): ?>
                            <?php foreach ($marketAccess as $market => $access): ?>
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <span class="fw-bold"><?= htmlspecialchars($market) ?></span>
                                    <div>
                                        <?php if ($access['can_view']): ?>
                                            <span class="badge bg-info">View</span>
                                        <?php endif; ?>
                                        <?php if ($access['can_edit']): ?>
                                            <span class="badge bg-warning">Edit</span>
                                        <?php endif; ?>
                                        <?php if ($access['can_manage_results']): ?>
                                            <span class="badge bg-success">Results</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="text-muted text-center py-3">
                                <i class="bi bi-ban display-1 mb-3"></i>
                                <p>Tidak ada akses pasaran yang diberikan</p>
                                <small>Hubungi Master Admin untuk mengatur akses pasaran</small>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Recent Activity -->
        <?php if (!empty($recentActivity)): ?>
            <div class="row mt-4">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="bi bi-clock me-2"></i>
                                Aktivitas Terbaru
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="list-group list-group-flush">
                                <?php foreach ($recentActivity as $activity): ?>
                                    <div class="list-group-item">
                                        <div class="d-flex w-100 justify-content-between">
                                            <h6 class="mb-1"><?= htmlspecialchars($activity['action_type']) ?></h6>
                                            <small><?= date('d/m/Y H:i', strtotime($activity['created_at'])) ?></small>
                                        </div>
                                        <p class="mb-1"><?= htmlspecialchars($activity['action_description']) ?></p>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>