<?php
/**
 * Dashboard Controller
 * Uses layout files for consistent design
 */
class DashboardController {
    
    public function index() {
        // Check if user is logged in
        if (!isset($_SESSION['user_id'])) {
            header('Location: ' . BASE_URL . '/index.php?error=' . urlencode('Please login to access the dashboard'));
            exit;
        }
        
        // Get user info from session
        $user = [
            'full_name' => $_SESSION['full_name'] ?? 'User',
            'roles' => $_SESSION['roles'] ?? ['Staff']
        ];
        
        $userName = $_SESSION['full_name'] ?? 'User';
        $userRole = $_SESSION['roles'][0] ?? 'Staff';
        $isSuperAdmin = isset($_SESSION['is_super_admin']) && $_SESSION['is_super_admin'] === true;
        $userPermissions = $_SESSION['permissions'] ?? [];
        
        // Set variables for the view
        $active = 'dashboard';
        $title = 'Dashboard';
        $init_charts = true;
        
        // Get database connection for statistics
        $pdo = null;
        if (function_exists('getDBConnection')) {
            $pdo = getDBConnection();
        }
        
        // Initialize stats array with default values
        $stats = [
            'total_weapons' => 0,
            'weapons_issued' => 0,
            'total_ammunition' => 0,
            'ammunition_balance' => 0,
            'total_land' => 0,
            'total_buildings' => 0,
            'total_rented' => 0,
            'total_projects' => 0,
            'total_movable' => 0,
            'total_ict' => 0,
            'total_vehicles' => 0,
            'total_aircraft' => 0,
            'total_marine' => 0,
            'total_motorcycles' => 0,
            'total_users' => 1,
            'pending_requisitions' => 0,
            'expiring_ammunition' => 0,
            'unserviceable_weapons' => 0
        ];
        
        $activities = [];
        
        // Try to get real data if database is connected
        if ($pdo) {
            try {
                // Get total weapons
                $stmt = $pdo->query("SELECT COUNT(*) as count FROM weapons_inventory");
                $stats['total_weapons'] = $stmt->fetch()['count'] ?? 0;
                
                // Get issued weapons
                $stmt = $pdo->query("SELECT COUNT(*) as count FROM weapons_inventory WHERE current_location = 'Issued'");
                $stats['weapons_issued'] = $stmt->fetch()['count'] ?? 0;
                
                // ============================================================
                // AMMUNITION AND REQUISITION QUERIES - ADDED HERE
                // ============================================================
                
                // Get total ammunition types
                $stmt = $pdo->query("SELECT COUNT(*) as count FROM ammunition_inventory");
                $stats['total_ammunition'] = $stmt->fetch()['count'] ?? 0;
                
                // Get ammunition balance (total rounds)
                $stmt = $pdo->query("SELECT SUM(balance) as total FROM ammunition_inventory");
                $stats['ammunition_balance'] = $stmt->fetch()['total'] ?? 0;
                
                // Get pending requisitions
                $stmt = $pdo->query("SELECT COUNT(*) as count FROM requisitions WHERE status = 'Pending'");
                $stats['pending_requisitions'] = $stmt->fetch()['count'] ?? 0;
                
                // ============================================================
                // CONTINUE WITH EXISTING QUERIES
                // ============================================================
                
                // Get land assets
                $stmt = $pdo->query("SELECT COUNT(*) as count FROM land_assets");
                $stats['total_land'] = $stmt->fetch()['count'] ?? 0;
                
                // Get buildings
                $stmt = $pdo->query("SELECT COUNT(*) as count FROM building_assets");
                $stats['total_buildings'] = $stmt->fetch()['count'] ?? 0;
                
                // Get rented properties
                $stmt = $pdo->query("SELECT COUNT(*) as count FROM rented_properties");
                $stats['total_rented'] = $stmt->fetch()['count'] ?? 0;
                
                // Get ongoing projects
                $stmt = $pdo->query("SELECT COUNT(*) as count FROM ongoing_projects");
                $stats['total_projects'] = $stmt->fetch()['count'] ?? 0;
                
                // Get movable assets
                $stmt = $pdo->query("SELECT COUNT(*) as count FROM movable_assets");
                $stats['total_movable'] = $stmt->fetch()['count'] ?? 0;
                
                // Get ICT assets
                $stmt = $pdo->query("SELECT COUNT(*) as count FROM ict_assets");
                $stats['total_ict'] = $stmt->fetch()['count'] ?? 0;
                
                // Get vehicles
                $stmt = $pdo->query("SELECT COUNT(*) as count FROM vehicle_assets");
                $stats['total_vehicles'] = $stmt->fetch()['count'] ?? 0;
                
                // Get aircraft (real-time data)
                $stmt = $pdo->query("SELECT COUNT(*) as count FROM aircraft_assets");
                $stats['total_aircraft'] = $stmt->fetch()['count'] ?? 0;
                
                // Get marine assets (real-time data)
                $stmt = $pdo->query("SELECT COUNT(*) as count FROM marine_assets");
                $stats['total_marine'] = $stmt->fetch()['count'] ?? 0;
                
                // Get motorcycles (real-time data)
                $stmt = $pdo->query("SELECT COUNT(*) as count FROM motorcycle_assets");
                $stats['total_motorcycles'] = $stmt->fetch()['count'] ?? 0;
                
                // Get users count
                $stmt = $pdo->query("SELECT COUNT(*) as count FROM users WHERE is_active = 1");
                $stats['total_users'] = $stmt->fetch()['count'] ?? 1;
                
                // Get expiring ammunition (within 30 days)
                $stmt = $pdo->query("
                    SELECT COUNT(*) as count FROM ammunition_inventory 
                    WHERE expiry_date IS NOT NULL 
                    AND expiry_date <= DATE_ADD(CURDATE(), INTERVAL 30 DAY)
                    AND expiry_date >= CURDATE()
                ");
                $stats['expiring_ammunition'] = $stmt->fetch()['count'] ?? 0;
                
                // Get unserviceable weapons
                try {
                    $stmt = $pdo->query("SELECT COUNT(*) as count FROM weapons_inventory WHERE `condition` = 'Unserviceable'");
                    $stats['unserviceable_weapons'] = $stmt->fetch()['count'] ?? 0;
                } catch (Exception $e) {
                    error_log("Error counting unserviceable weapons: " . $e->getMessage());
                    $stats['unserviceable_weapons'] = 0;
                }
                
                // Get recent activities
                $stmt = $pdo->query("
                    SELECT al.*, u.full_name 
                    FROM audit_logs al 
                    LEFT JOIN users u ON al.user_id = u.id 
                    ORDER BY al.created_at DESC 
                    LIMIT 10
                ");
                $activities = $stmt->fetchAll();
                
            } catch (Exception $e) {
                // Tables might not exist yet
                error_log("Dashboard stats error: " . $e->getMessage());
            }
        }
      
        // Include the header layout
        require_once BASE_PATH . '/views/layouts/header.php';
        
        // Include the sidebar layout
        require_once BASE_PATH . '/views/layouts/sidebar.php';
        
        // Display any alerts
        if (file_exists(BASE_PATH . '/views/layouts/alerts.php')) {
            require_once BASE_PATH . '/views/layouts/alerts.php';
        }
        
        // Include the main dashboard content
        $this->renderDashboardContent($stats, $activities, $user, $isSuperAdmin, $userPermissions);
        
        // Include the footer layout
        require_once BASE_PATH . '/views/layouts/footer.php';
    }
    
    private function renderDashboardContent($stats, $activities, $user, $isSuperAdmin, $userPermissions) {
        ?>
        <div class="container-fluid">
            <!-- Page Header -->
            <div class="page-header">
                <div class="header-content">
                    <h1>
                        <i class="fas fa-tachometer-alt"></i>
                        Dashboard
                    </h1>
                    <p>Welcome back, <?php echo htmlspecialchars($user['full_name'] ?? 'User'); ?>! Here's your system overview.</p>
                </div>
                <div class="header-actions">
                    <button class="btn btn-outline" onclick="refreshDashboard()">
                        <i class="fas fa-sync-alt"></i> Refresh
                    </button>
                </div>
            </div>

            <!-- Statistics Cards -->
            <div class="dashboard-grid">
                <!-- Weapons Card -->
                <div class="stat-card">
                    <div class="card-icon" style="background: #e74c3c;">
                        <i class="fas fa-gun"></i>
                    </div>
                    <div class="card-content">
                        <div class="card-value"><?php echo number_format($stats['total_weapons'] ?? 0); ?></div>
                        <div class="card-label">Total Weapons</div>
                        <div class="card-trend">
                            <span class="text-muted"><?php echo $stats['weapons_issued'] ?? 0; ?> issued</span>
                        </div>
                    </div>
                    <div class="card-action">
                        <a href="<?php echo BASE_URL; ?>/weapons" class="btn-link">
                            <i class="fas fa-arrow-right"></i> View Weapons
                        </a>
                    </div>
                </div>

                <!-- Ammunition Card -->
                <div class="stat-card">
                    <div class="card-icon" style="background: #f39c12;">
                        <i class="fas fa-bullseye"></i>
                    </div>
                    <div class="card-content">
                        <div class="card-value"><?php echo number_format($stats['total_ammunition'] ?? 0); ?></div>
                        <div class="card-label">Ammunition Types</div>
                        <div class="card-trend">
                            <span class="text-muted"><?php echo number_format($stats['ammunition_balance'] ?? 0); ?> rounds total</span>
                        </div>
                    </div>
                    <div class="card-action">
                        <a href="<?php echo BASE_URL; ?>/ammunition" class="btn-link">
                            <i class="fas fa-arrow-right"></i> View Ammo
                        </a>
                    </div>
                </div>

                <!-- Land Assets Card -->
                <div class="stat-card">
                    <div class="card-icon" style="background: #27ae60;">
                        <i class="fas fa-map-marked-alt"></i>
                    </div>
                    <div class="card-content">
                        <div class="card-value"><?php echo number_format($stats['total_land'] ?? 0); ?></div>
                        <div class="card-label">Land Assets</div>
                    </div>
                    <div class="card-action">
                        <a href="<?php echo BASE_URL; ?>/land" class="btn-link">
                            <i class="fas fa-arrow-right"></i> View Land
                        </a>
                    </div>
                </div>

                <!-- Buildings Card -->
                <div class="stat-card">
                    <div class="card-icon" style="background: #3498db;">
                        <i class="fas fa-building"></i>
                    </div>
                    <div class="card-content">
                        <div class="card-value"><?php echo number_format($stats['total_buildings'] ?? 0); ?></div>
                        <div class="card-label">Buildings</div>
                    </div>
                    <div class="card-action">
                        <a href="<?php echo BASE_URL; ?>/buildings" class="btn-link">
                            <i class="fas fa-arrow-right"></i> View Buildings
                        </a>
                    </div>
                </div>

                <!-- Rented Properties Card -->
                <div class="stat-card">
                    <div class="card-icon" style="background: #e67e22;">
                        <i class="fas fa-house-user"></i>
                    </div>
                    <div class="card-content">
                        <div class="card-value"><?php echo number_format($stats['total_rented'] ?? 0); ?></div>
                        <div class="card-label">Rented Properties</div>
                    </div>
                    <div class="card-action">
                        <a href="<?php echo BASE_URL; ?>/rented" class="btn-link">
                            <i class="fas fa-arrow-right"></i> View Rented
                        </a>
                    </div>
                </div>

                <!-- Projects Card -->
                <div class="stat-card">
                    <div class="card-icon" style="background: #9b59b6;">
                        <i class="fas fa-hard-hat"></i>
                    </div>
                    <div class="card-content">
                        <div class="card-value"><?php echo number_format($stats['total_projects'] ?? 0); ?></div>
                        <div class="card-label">Ongoing Projects</div>
                    </div>
                    <div class="card-action">
                        <a href="<?php echo BASE_URL; ?>/projects" class="btn-link">
                            <i class="fas fa-arrow-right"></i> View Projects
                        </a>
                    </div>
                </div>

                <!-- Movable Assets Card -->
                <div class="stat-card">
                    <div class="card-icon" style="background: #1abc9c;">
                        <i class="fas fa-tools"></i>
                    </div>
                    <div class="card-content">
                        <div class="card-value"><?php echo number_format($stats['total_movable'] ?? 0); ?></div>
                        <div class="card-label">Movable Assets</div>
                    </div>
                    <div class="card-action">
                        <a href="<?php echo BASE_URL; ?>/movable" class="btn-link">
                            <i class="fas fa-arrow-right"></i> View Movable
                        </a>
                    </div>
                </div>

                <!-- ICT Assets Card -->
                <div class="stat-card">
                    <div class="card-icon" style="background: #34495e;">
                        <i class="fas fa-server"></i>
                    </div>
                    <div class="card-content">
                        <div class="card-value"><?php echo number_format($stats['total_ict'] ?? 0); ?></div>
                        <div class="card-label">ICT Assets</div>
                    </div>
                    <div class="card-action">
                        <a href="<?php echo BASE_URL; ?>/ict" class="btn-link">
                            <i class="fas fa-arrow-right"></i> View ICT
                        </a>
                    </div>
                </div>

                <!-- Vehicles Card -->
                <div class="stat-card">
                    <div class="card-icon" style="background: #e67e22;">
                        <i class="fas fa-car"></i>
                    </div>
                    <div class="card-content">
                        <div class="card-value"><?php echo number_format($stats['total_vehicles'] ?? 0); ?></div>
                        <div class="card-label">Vehicles</div>
                    </div>
                    <div class="card-action">
                        <a href="<?php echo BASE_URL; ?>/fleet/vehicles" class="btn-link">
                            <i class="fas fa-arrow-right"></i> View Vehicles
                        </a>
                    </div>
                </div>

                <!-- Aircraft Card -->
                <div class="stat-card">
                    <div class="card-icon" style="background: #2980b9;">
                        <i class="fas fa-fighter-jet"></i>
                    </div>
                    <div class="card-content">
                        <div class="card-value"><?php echo number_format($stats['total_aircraft'] ?? 0); ?></div>
                        <div class="card-label">Aircraft</div>
                    </div>
                    <div class="card-action">
                        <a href="<?php echo BASE_URL; ?>/fleet/aircraft" class="btn-link">
                            <i class="fas fa-arrow-right"></i> View Aircraft
                        </a>
                    </div>
                </div>

                <!-- Marine Card -->
                <div class="stat-card">
                    <div class="card-icon" style="background: #16a085;">
                        <i class="fas fa-ship"></i>
                    </div>
                    <div class="card-content">
                        <div class="card-value"><?php echo number_format($stats['total_marine'] ?? 0); ?></div>
                        <div class="card-label">Marine Assets</div>
                    </div>
                    <div class="card-action">
                        <a href="<?php echo BASE_URL; ?>/fleet/marine" class="btn-link">
                            <i class="fas fa-arrow-right"></i> View Marine
                        </a>
                    </div>
                </div>

                <!-- Motorcycles Card -->
                <div class="stat-card">
                    <div class="card-icon" style="background: #d35400;">
                        <i class="fas fa-motorcycle"></i>
                    </div>
                    <div class="card-content">
                        <div class="card-value"><?php echo number_format($stats['total_motorcycles'] ?? 0); ?></div>
                        <div class="card-label">Motorcycles</div>
                    </div>
                    <div class="card-action">
                        <a href="<?php echo BASE_URL; ?>/fleet/motorcycles" class="btn-link">
                            <i class="fas fa-arrow-right"></i> View Motorcycles
                        </a>
                    </div>
                </div>

                <!-- Pending Requisitions Card -->
                <div class="stat-card <?php echo ($stats['pending_requisitions'] ?? 0) > 0 ? 'stat-warning' : ''; ?>">
                    <div class="card-icon" style="background: #f39c12;">
                        <i class="fas fa-file-signature"></i>
                    </div>
                    <div class="card-content">
                        <div class="card-value"><?php echo number_format($stats['pending_requisitions'] ?? 0); ?></div>
                        <div class="card-label">Pending Requisitions</div>
                        <div class="card-trend">
                            <span class="text-muted">Awaiting approval</span>
                        </div>
                    </div>
                    <div class="card-action">
                        <a href="<?php echo BASE_URL; ?>/requisition" class="btn-link">
                            <i class="fas fa-arrow-right"></i> Review Requisitions
                        </a>
                    </div>
                </div>

                <!-- Users Card -->
                <div class="stat-card">
                    <div class="card-icon" style="background: #2c3e50;">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="card-content">
                        <div class="card-value"><?php echo number_format($stats['total_users'] ?? 0); ?></div>
                        <div class="card-label">Active Users</div>
                    </div>
                    <div class="card-action">
                        <a href="<?php echo BASE_URL; ?>/users" class="btn-link">
                            <i class="fas fa-arrow-right"></i> Manage Users
                        </a>
                    </div>
                </div>

                <!-- Alerts Card -->
                <div class="stat-card <?php echo (($stats['expiring_ammunition'] ?? 0) > 0 || ($stats['unserviceable_weapons'] ?? 0) > 0) ? 'stat-danger' : ''; ?>">
                    <div class="card-icon" style="background: #e74c3c;">
                        <i class="fas fa-exclamation-triangle"></i>
                    </div>
                    <div class="card-content">
                        <div class="card-value"><?php echo ($stats['expiring_ammunition'] ?? 0) + ($stats['unserviceable_weapons'] ?? 0); ?></div>
                        <div class="card-label">System Alerts</div>
                        <div class="card-trend">
                            <span><?php echo $stats['expiring_ammunition'] ?? 0; ?> expiring | <?php echo $stats['unserviceable_weapons'] ?? 0; ?> unserviceable</span>
                        </div>
                    </div>
                    <div class="card-action">
                        <a href="<?php echo BASE_URL; ?>/weapons?filter=unserviceable" class="btn-link">
                            <i class="fas fa-arrow-right"></i> View Alerts
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <style>
        /* Dashboard Grid Layout */
        .dashboard-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        /* Stat Card Styles */
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            display: flex;
            align-items: center;
            gap: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .stat-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        }

        .stat-card.stat-warning {
            background: linear-gradient(135deg, #fff8e1 0%, #fff3cd 100%);
            border-left: 4px solid #f39c12;
        }

        .stat-card.stat-danger {
            background: linear-gradient(135deg, #fee2e2 0%, #f8d7da 100%);
            border-left: 4px solid #e74c3c;
        }

        .card-icon {
            width: 60px;
            height: 60px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.8rem;
            color: white;
            flex-shrink: 0;
        }

        .card-content {
            flex: 1;
        }

        .card-value {
            font-size: 1.8rem;
            font-weight: 700;
            color: #2c3e50;
            line-height: 1.2;
            margin-bottom: 5px;
        }

        .card-label {
            font-size: 0.85rem;
            color: #7f8c8d;
            font-weight: 500;
            margin-bottom: 5px;
        }

        .card-trend {
            font-size: 0.75rem;
            color: #95a5a6;
        }

        .card-trend .text-muted {
            color: #95a5a6;
        }

        .card-action {
            position: absolute;
            bottom: 15px;
            right: 15px;
        }

        .btn-link {
            color: #7f8c8d;
            font-size: 0.8rem;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            transition: all 0.3s;
        }

        .btn-link:hover {
            color: #27ae60;
        }

        /* Page Header */
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e2e8f0;
        }

        .header-content h1 {
            margin: 0 0 5px 0;
            font-size: 1.2rem;
            color: #2c3e50;
        }

        .header-content p {
            margin: 0;
            color: #7f8c8d;
        }

        .header-actions {
            display: flex;
            gap: 10px;
        }

        .btn-outline {
            background: transparent;
            border: 1px solid #cbd5e0;
            color: #4a5568;
            padding: 8px 16px;
            border-radius: 6px;
            font-size: 0.9rem;
            cursor: pointer;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-outline:hover {
            background: #f7fafc;
            border-color: #27ae60;
            color: #27ae60;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .dashboard-grid {
                grid-template-columns: 1fr;
            }
            
            .page-header {
                flex-direction: column;
                gap: 15px;
            }
            
            .header-actions {
                width: 100%;
            }
            
            .btn-outline {
                width: 100%;
                justify-content: center;
            }
            
            .stat-card {
                padding: 15px;
            }
            
            .card-icon {
                width: 50px;
                height: 50px;
                font-size: 1.5rem;
            }
            
            .card-value {
                font-size: 1.5rem;
            }
        }

        @media print {
            .header-actions,
            .btn-outline,
            .card-action {
                display: none !important;
            }
            
            .stat-card {
                break-inside: avoid;
                box-shadow: none;
                border: 1px solid #ddd;
            }
        }
        </style>

        <script>
        function refreshDashboard() {
            const btn = event.target.closest('button');
            const originalHtml = btn.innerHTML;
            
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Refreshing...';
            btn.disabled = true;
            
            setTimeout(() => {
                location.reload();
            }, 1000);
        }
        </script>
        <?php
    }
}