<?php
define('ADMIN_ACCESS', true);
require_once 'config.php';
require_once '../includes/database.php';
require_once '../includes/site-manager.php';
require_once '../includes/multi-tenant-auth.php';
require_once '../includes/integrated-admin-auth.php';
require_once '../includes/permission-middleware.php';

$integratedAuth = new IntegratedAdminAuth();
$database = new Database();
$pdo = $database->getConnection();
$siteManager = new SiteManager($database);

// Check if logged in with integrated system
if (!isset($_SESSION['integrated_admin_session_id'])) {
    header('Location: login.php');
    exit;
}

// Validate session and get admin data
$adminData = $integratedAuth->validateSession($_SESSION['integrated_admin_session_id']);
if (!$adminData) {
    session_destroy();
    header('Location: login.php');
    exit;
}

// Update session data
$_SESSION['integrated_admin_data'] = $adminData;
$_SESSION['admin_data'] = $adminData;

// CRITICAL: Set current site ID for proper data isolation
$_SESSION['current_site_id'] = $adminData['site_id'] ?? 1; // For template compatibility

// Create permission middleware
$permissionMiddleware = new PermissionMiddleware($integratedAuth, $adminData);

// Handle logout
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    $integratedAuth->logout($_SESSION['integrated_admin_session_id']);
    session_destroy();
    header('Location: login.php');
    exit;
}

$currentSite = $siteManager->getCurrentSite();
$isMaster = isset($adminData['is_master']) && $adminData['is_master'];

// Get statistics for dashboard
$stats = [
    'sites' => 0,
    'sub_admins' => 0,
    'markets' => 0,
    'today_results' => 0,
    'total_results' => 0,
    'accessible_markets' => count($permissionMiddleware->getAccessibleMarkets()),
    'permissions' => count($adminData['permissions'] ?? [])
];

try {
    // Master admin stats
    if ($isMaster) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM sites");
        $stmt->execute();
        $stats['sites'] = $stmt->fetchColumn();
        
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM site_admins WHERE is_active = 1");
        $stmt->execute();
        $stats['sub_admins'] = $stmt->fetchColumn();
    }
    
    // Common stats
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM " . SiteConfig::getTableName('market_schedules'));
    $stmt->execute();
    $stats['markets'] = $stmt->fetchColumn();
    
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM " . SiteConfig::getTableName('live_draw_results') . " WHERE DATE(created_at) = CURDATE()");
    $stmt->execute();
    $stats['today_results'] = $stmt->fetchColumn();
    
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM " . SiteConfig::getTableName('live_draw_results'));
    $stmt->execute();
    $stats['total_results'] = $stmt->fetchColumn();
    
} catch (Exception $e) {
    error_log("Dashboard stats error: " . $e->getMessage());
}

// Get recent activity
$recentActivity = [];
try {
    if ($isMaster) {
        $table = 'admin_activity_log';
        $adminIdField = 'admin_id';
        $adminId = $adminData['original_id'] ?? $adminData['id'] ?? 0;
    } else {
        $table = 'admin_activity_log_multi';
        $adminIdField = 'admin_id';
        $adminId = $adminData['original_id'] ?? $adminData['id'] ?? 0;
    }
    
    $stmt = $pdo->prepare("
        SELECT action_type, action_description, created_at 
        FROM $table 
        WHERE $adminIdField = ? 
        ORDER BY created_at DESC 
        LIMIT 10
    ");
    $stmt->execute([$adminId]);
    $recentActivity = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Recent activity error: " . $e->getMessage());
    $recentActivity = [];
}

// Set page variables for template
$pageTitle = 'Dashboard';
$pageDescription = 'Overview dan statistik sistem admin';
$headerActions = '
    <div class="d-flex gap-2">
        <button class="btn btn-outline-primary btn-sm" onclick="location.reload()">
            <i class="bi bi-arrow-clockwise me-1"></i>
            Refresh
        </button>
    </div>
';

// Include sidebar template
include 'admin-sidebar-template.php';
?>

<!-- Dashboard Content -->
<div class="row">
    <!-- Statistics Cards -->
    <div class="col-12 mb-4">
        <div class="row g-3">
            <?php if ($isMaster): ?>
            <!-- Sites Count -->
            <div class="col-lg-3 col-md-6">
                <div class="card bg-primary text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title mb-0">Total Situs</h6>
                                <h2 class="mt-2 mb-0"><?php echo number_format($stats['sites']); ?></h2>
                            </div>
                            <i class="bi bi-globe fs-1 opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Sub Admins Count -->
            <div class="col-lg-3 col-md-6">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title mb-0">Sub Admin</h6>
                                <h2 class="mt-2 mb-0"><?php echo number_format($stats['sub_admins']); ?></h2>
                            </div>
                            <i class="bi bi-people fs-1 opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
            <?php else: ?>
            <!-- Accessible Markets -->
            <div class="col-lg-3 col-md-6">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title mb-0">Pasaran Akses</h6>
                                <h2 class="mt-2 mb-0"><?php echo number_format($stats['accessible_markets']); ?></h2>
                            </div>
                            <i class="bi bi-shop fs-1 opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Permissions -->
            <div class="col-lg-3 col-md-6">
                <div class="card bg-warning text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title mb-0">Permission</h6>
                                <h2 class="mt-2 mb-0"><?php echo number_format($stats['permissions']); ?></h2>
                            </div>
                            <i class="bi bi-shield-check fs-1 opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Markets Count -->
            <div class="col-lg-3 col-md-6">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title mb-0">Total Pasaran</h6>
                                <h2 class="mt-2 mb-0"><?php echo number_format($stats['markets']); ?></h2>
                            </div>
                            <i class="bi bi-shop fs-1 opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Today Results -->
            <div class="col-lg-3 col-md-6">
                <div class="card bg-warning text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title mb-0">Hasil Hari Ini</h6>
                                <h2 class="mt-2 mb-0"><?php echo number_format($stats['today_results']); ?></h2>
                            </div>
                            <i class="bi bi-calendar-check fs-1 opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Quick Actions -->
    <div class="col-lg-6 mb-4">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="bi bi-lightning-charge me-2"></i>
                    Quick Actions
                </h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <?php if ($isMaster): ?>
                    <div class="col-md-6">
                        <a href="sub-admins.php" class="btn btn-outline-primary w-100">
                            <i class="bi bi-person-plus me-2"></i>
                            Tambah Sub Admin
                        </a>
                    </div>
                    <div class="col-md-6">
                        <a href="sites.php" class="btn btn-outline-success w-100">
                            <i class="bi bi-globe-americas me-2"></i>
                            Kelola Situs
                        </a>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($permissionMiddleware->hasPermission('manage_markets')): ?>
                    <div class="col-md-6">
                        <a href="markets.php" class="btn btn-outline-info w-100">
                            <i class="bi bi-shop me-2"></i>
                            Kelola Pasaran
                        </a>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($permissionMiddleware->hasPermission('manage_results')): ?>
                    <div class="col-md-6">
                        <a href="livedraw.php" class="btn btn-outline-warning w-100">
                            <i class="bi bi-broadcast me-2"></i>
                            Input Hasil
                        </a>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- System Info -->
    <div class="col-lg-6 mb-4">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="bi bi-info-circle me-2"></i>
                    System Information
                </h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-12">
                        <div class="d-flex justify-content-between">
                            <span>Admin Type:</span>
                            <span class="badge bg-<?php echo $isMaster ? 'primary' : 'secondary'; ?>">
                                <?php echo $isMaster ? 'Master Admin' : 'Sub Admin'; ?>
                            </span>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="d-flex justify-content-between">
                            <span>Username:</span>
                            <strong><?php echo htmlspecialchars($adminData['username']); ?></strong>
                        </div>
                    </div>
                    <?php if (!$isMaster && $currentSite): ?>
                    <div class="col-12">
                        <div class="d-flex justify-content-between">
                            <span>Current Site:</span>
                            <strong><?php echo htmlspecialchars($currentSite['site_name']); ?></strong>
                        </div>
                    </div>
                    <?php endif; ?>
                    <div class="col-12">
                        <div class="d-flex justify-content-between">
                            <span>Login Time:</span>
                            <small><?php echo date('d/m/Y H:i', strtotime($adminData['login_time'] ?? 'now')); ?></small>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="d-flex justify-content-between">
                            <span>Server Time:</span>
                            <small><?php echo date('d/m/Y H:i:s'); ?></small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Recent Activity -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">
                    <i class="bi bi-activity me-2"></i>
                    Recent Activity
                </h5>
                <small class="text-muted">Last 10 actions</small>
            </div>
            <div class="card-body">
                <?php if (empty($recentActivity)): ?>
                <div class="text-center py-4">
                    <i class="bi bi-inbox display-4 text-muted"></i>
                    <p class="text-muted mt-2">No recent activity</p>
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>Action</th>
                                <th>Description</th>
                                <th>Time</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recentActivity as $activity): ?>
                            <tr>
                                <td>
                                    <span class="badge bg-light text-dark">
                                        <?php echo htmlspecialchars($activity['action_type']); ?>
                                    </span>
                                </td>
                                <td><?php echo htmlspecialchars($activity['action_description']); ?></td>
                                <td>
                                    <small class="text-muted">
                                        <?php echo date('d/m/Y H:i', strtotime($activity['created_at'])); ?>
                                    </small>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Performance Stats -->
<div class="row mt-4">
    <div class="col-lg-4">
        <div class="card text-center">
            <div class="card-body">
                <h2 class="text-primary"><?php echo number_format($stats['total_results']); ?></h2>
                <p class="card-text">Total Results</p>
                <div class="progress" style="height: 6px;">
                    <div class="progress-bar bg-primary" style="width: 85%"></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="card text-center">
            <div class="card-body">
                <h2 class="text-success"><?php echo number_format($stats['markets']); ?></h2>
                <p class="card-text">Active Markets</p>
                <div class="progress" style="height: 6px;">
                    <div class="progress-bar bg-success" style="width: 70%"></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="card text-center">
            <div class="card-body">
                <h2 class="text-warning"><?php echo $isMaster ? number_format($stats['sub_admins']) : number_format($stats['permissions']); ?></h2>
                <p class="card-text"><?php echo $isMaster ? 'Sub Admins' : 'Permissions'; ?></p>
                <div class="progress" style="height: 6px;">
                    <div class="progress-bar bg-warning" style="width: 60%"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
// Additional JavaScript for dashboard
$additionalJS = '
<script>
    // Auto-refresh stats every 5 minutes
    setInterval(function() {
        // Refresh page statistics
        location.reload();
    }, 300000);

    // Real-time clock
    function updateTime() {
        const now = new Date();
        const timeString = now.toLocaleString("id-ID");
        // Update any time display elements
    }
    
    setInterval(updateTime, 1000);
</script>';

include 'admin-sidebar-footer.php';
?>