<?php
/**
 * Dashboard View
 * GHAMECC Choir Management Platform
 */

// This file should only be included when user is authenticated
if (!isLoggedIn()) {
    header('Location: login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - GHAMECC Choir Management</title>
    
    <?php include 'includes/favicon.php'; ?>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Custom CSS -->
    <link href="assets/css/style.css" rel="stylesheet">
</head>
<body>

    <!-- Navigation -->
    <?php include 'includes/navbar.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include 'includes/sidebar.php'; ?>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <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">Share</button>
                            <button type="button" class="btn btn-sm btn-outline-secondary">Export</button>
                        </div>
                        <button type="button" class="btn btn-sm btn-outline-secondary dropdown-toggle">
                            <i class="fas fa-calendar me-1"></i>
                            This week
                        </button>
                    </div>
                </div>
                
                <!-- Welcome Card -->
                <div class="card shadow mb-4">
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col-auto">
                                <?php if (isset($_SESSION['profile_image']) && !empty($_SESSION['profile_image'])): ?>
                                    <img src="uploads/profile/<?php echo $_SESSION['profile_image']; ?>" alt="Profile" class="rounded-circle" width="64" height="64">
                                <?php else: ?>
                                    <div class="avatar-circle-lg">
                                        <?php
                                        $initials = "";
                                        if (isset($_SESSION['full_name'])) {
                                            $nameParts = explode(" ", $_SESSION['full_name']);
                                            if (count($nameParts) >= 2) {
                                                $initials = strtoupper(substr($nameParts[0], 0, 1) . substr($nameParts[count($nameParts) - 1], 0, 1));
                                            } else {
                                                $initials = strtoupper(substr($_SESSION['full_name'], 0, 2));
                                            }
                                        } elseif (isset($_SESSION['email'])) {
                                            $initials = strtoupper(substr($_SESSION['email'], 0, 2));
                                        }
                                        echo $initials;
                                        ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="col">
                                <h4>Welcome, <?php echo htmlspecialchars($userFullName); ?>!</h4>
                                <p class="text-muted mb-0">
                                    <?php
                                    // Display user's roles
                                    $roles = [];
                                    
                                    // Get user role from the users and roles tables
                                    $userRole = fetchRow("SELECT r.name as role_name, u.society_id, u.circuit_id, u.diocese_id 
                                                       FROM users u 
                                                       JOIN roles r ON u.role_id = r.id 
                                                       WHERE u.id = $userId");
                                    
                                    if ($userRole) {
                                        // If user has a society_id, get the society name
                                        if ($userRole['society_id']) {
                                            $society = fetchRow("SELECT name FROM societies WHERE id = " . $userRole['society_id']);
                                            if ($society) {
                                                $roles[] = $userRole['role_name'] . " at " . $society['name'] . " Society";
                                            }
                                        }
                                        // If user has a circuit_id, get the circuit name
                                        else if ($userRole['circuit_id']) {
                                            $circuit = fetchRow("SELECT name FROM circuits WHERE id = " . $userRole['circuit_id']);
                                            if ($circuit) {
                                                $roles[] = $userRole['role_name'] . " at " . $circuit['name'] . " Circuit";
                                            }
                                        }
                                        // If user has a diocese_id, get the diocese name
                                        else if ($userRole['diocese_id']) {
                                            $diocese = fetchRow("SELECT name FROM dioceses WHERE id = " . $userRole['diocese_id']);
                                            if ($diocese) {
                                                $roles[] = $userRole['role_name'] . " at " . $diocese['name'] . " Diocese";
                                            }
                                        }
                                        else {
                                            $roles[] = $userRole['role_name'];
                                        }
                                    }
                                    
                                    // Check for admin role
                                    if (hasRole(['admin'])) {
                                        $roles[] = "Administrator";
                                    }
                                    
                                    echo !empty($roles) ? implode(" | ", $roles) : "Member";
                                    ?>
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <?php 
                $ads = [];
                if (function_exists('fetchRows')) {
                    $ads = fetchRows("SELECT * FROM ads WHERE status = 'approved' AND (starts_at IS NULL OR starts_at <= NOW()) AND (ends_at IS NULL OR ends_at >= NOW()) ORDER BY created_at DESC LIMIT 10");
                }
                ?>
                <div class="card shadow mb-4">
                    <div class="card-header py-3 d-flex justify-content-between align-items-center">
                        <h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-bullhorn me-2"></i>Member Adverts</h6>
                        <?php if (hasRole(['admin', 'diocesan_chairman', 'diocese_chairman', 'diocesan_secretary', 'diocesan_treasurer', 'diocesan_dom', 'diocesan_music_director'])): ?>
                            <a href="ads/submit.php" class="btn btn-sm btn-outline-primary">Submit Advert</a>
                        <?php endif; ?>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($ads)): ?>
                            <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 row-cols-lg-4 g-3">
                                <?php foreach ($ads as $ad): ?>
                                    <?php 
                                        $descText = isset($ad['description']) ? strip_tags($ad['description']) : '';
                                        $short = strlen($descText) > 90 ? substr($descText, 0, 90) . '...' : $descText;
                                    ?>
                                    <div class="col">
                                        <a href="ads/view.php?id=<?php echo (int)$ad['id']; ?>" class="text-decoration-none text-reset">
                                            <div class="card h-100 shadow-sm">
                                                <div class="ratio ratio-4x3">
                                                    <img src="uploads/ads/<?php echo htmlspecialchars($ad['image_path']); ?>" class="card-img-top" alt="<?php echo htmlspecialchars($ad['title']); ?>" style="object-fit:cover;">
                                                </div>
                                                <div class="card-body">
                                                    <?php if ((float)$ad['price'] > 0): ?>
                                                        <div class="text-success fw-bold mb-1">GHS <?php echo number_format((float)$ad['price'], 2); ?></div>
                                                    <?php endif; ?>
                                                    <h6 class="card-title mb-1"><?php echo htmlspecialchars($ad['title']); ?></h6>
                                                    <?php if ($short): ?><p class="card-text text-muted small mb-0"><?php echo htmlspecialchars($short); ?></p><?php endif; ?>
                                                </div>
                                            </div>
                                        </a>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <div class="text-end mt-3">
                                <a href="ads/list.php" class="btn btn-sm btn-outline-secondary">View all adverts</a>
                            </div>
                        <?php else: ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-images fa-2x mb-2"></i>
                                <div>No adverts available at the moment.</div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="row">
                    <!-- Statistics Cards -->
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="card border-left-primary shadow h-100 py-2">
                            <div class="card-body">
                                <div class="row no-gutters align-items-center">
                                    <div class="col mr-2">
                                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                            Total Members</div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                                            <?php 
                                            $memberCount = fetchRow("SELECT COUNT(*) as count FROM members");
                                            echo isset($memberCount['count']) ? $memberCount['count'] : 0;
                                            ?>
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <i class="fas fa-users fa-2x text-gray-300"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="card border-left-success shadow h-100 py-2">
                            <div class="card-body">
                                <div class="row no-gutters align-items-center">
                                    <div class="col mr-2">
                                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                            Societies</div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                                            <?php 
                                            $societyCount = fetchRow("SELECT COUNT(*) as count FROM societies");
                                            echo isset($societyCount['count']) ? $societyCount['count'] : 0;
                                            ?>
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <i class="fas fa-home fa-2x text-gray-300"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="card border-left-info shadow h-100 py-2">
                            <div class="card-body">
                                <div class="row no-gutters align-items-center">
                                    <div class="col mr-2">
                                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                            Circuits</div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                                            <?php 
                                            $circuitCount = fetchRow("SELECT COUNT(*) as count FROM circuits");
                                            echo isset($circuitCount['count']) ? $circuitCount['count'] : 0;
                                            ?>
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <i class="fas fa-sitemap fa-2x text-gray-300"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="card border-left-warning shadow h-100 py-2">
                            <div class="card-body">
                                <div class="row no-gutters align-items-center">
                                    <div class="col mr-2">
                                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                            Dioceses</div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                                            <?php 
                                            $dioceseCount = fetchRow("SELECT COUNT(*) as count FROM dioceses");
                                            echo isset($dioceseCount['count']) ? $dioceseCount['count'] : 0;
                                            ?>
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <i class="fas fa-church fa-2x text-gray-300"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <!-- Pending Reports Widget -->
                    <div class="col-lg-6">
                        <?php 
                        if (file_exists($widgetsDir . '/pending_reports.php')) {
                            include $widgetsDir . '/pending_reports.php';
                        }
                        ?>
                    </div>
                    
                    <!-- Recent Activities -->
                    <div class="col-lg-6">
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Recent Activities</h6>
                            </div>
                            <div class="card-body">
                                <div class="timeline">
                                    <?php
                                    // Get recent report activities - simplified to avoid SQL errors
                                    $query = "SELECT r.id, r.status, r.updated_at as activity_date, 
                                              u.full_name, 'report' as activity_type
                                              FROM reports r
                                              JOIN users u ON r.user_id = u.id
                                              WHERE r.updated_at IS NOT NULL
                                              ORDER BY activity_date DESC
                                              LIMIT 5";
                                    
                                    $recentActivities = fetchRows($query);
                                    
                                    if (empty($recentActivities)):
                                    ?>
                                        <div class="text-center text-muted py-4">
                                            <i class="fas fa-history fa-3x mb-3"></i>
                                            <p>No recent activities found.</p>
                                        </div>
                                    <?php else: ?>
                                        <ul class="list-unstyled">
                                            <?php foreach ($recentActivities as $activity): ?>
                                                <li class="timeline-item mb-3">
                                                    <div class="timeline-marker 
                                                        <?php if ($activity['activity_type'] === 'report'): ?>
                                                            <?php if ($activity['status'] === 'approved'): ?>
                                                                bg-success
                                                            <?php elseif ($activity['status'] === 'rejected'): ?>
                                                                bg-danger
                                                            <?php elseif ($activity['status'] === 'completed'): ?>
                                                                bg-info
                                                            <?php else: ?>
                                                                bg-primary
                                                            <?php endif; ?>
                                                        <?php else: ?>
                                                            bg-primary
                                                        <?php endif; ?>
                                                    "></div>
                                                    <div class="timeline-content">
                                                        <h6 class="mb-0">Report Activity</h6>
                                                        <p class="text-muted mb-0 small">
                                                            <?php if ($activity['activity_type'] === 'report'): ?>
                                                                Report 
                                                                <?php if ($activity['status'] === 'approved'): ?>
                                                                    approved
                                                                <?php elseif ($activity['status'] === 'rejected'): ?>
                                                                    rejected
                                                                <?php elseif ($activity['status'] === 'completed'): ?>
                                                                    completed
                                                                <?php else: ?>
                                                                    updated
                                                                <?php endif; ?>
                                                                by <?php echo htmlspecialchars($activity['full_name']); ?>
                                                            <?php else: ?>
                                                                Response added by <?php echo htmlspecialchars($activity['full_name']); ?>
                                                            <?php endif; ?>
                                                        </p>
                                                        <small class="text-muted">
                                                            <?php 
                                                            echo date('M d, Y h:i A', strtotime($activity['activity_date'])); 
                                                            ?>
                                                        </small>
                                                    </div>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Session Timeout Warning Modal -->
    <div class="modal fade" id="session-timeout-warning" tabindex="-1" aria-labelledby="sessionTimeoutLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-warning">
                    <h5 class="modal-title" id="sessionTimeoutLabel">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        Session Timeout Warning
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Your session is about to expire due to inactivity.</p>
                    <p>You will be automatically logged out in <strong>1 minute</strong>.</p>
                    <p>Do you want to stay logged in?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" id="session-logout-now">Logout Now</button>
                    <button type="button" class="btn btn-primary" id="session-stay-logged-in" data-bs-dismiss="modal">Stay Logged In</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Check if Bootstrap is loaded correctly
        if (typeof bootstrap === 'undefined') {
            console.error('Bootstrap JavaScript is not loaded. Loading local fallback.');
            // Create and append a new script element with local fallback
            var bootstrapScript = document.createElement('script');
            bootstrapScript.src = '<?php echo $basePath; ?>/assets/js/bootstrap.bundle.min.js';
            document.head.appendChild(bootstrapScript);
        } else {
            console.log('Bootstrap JavaScript is loaded correctly.');
        }
    </script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Custom JS -->
    <script>
        // Add any dashboard-specific JavaScript here
    </script>
    
    <!-- Session Manager -->
    <script>
        // Create assets/js directory if it doesn't exist
        const assetsJsDir = '<?php echo __DIR__ . "/assets/js"; ?>';
        if (!file_exists(assetsJsDir)) {
            mkdir(assetsJsDir, 0777, true);
        }
    </script>
    <script src="assets/js/session-manager.js"></script>
    
    <style>
    /* Timeline styles */
    .timeline {
        position: relative;
        padding-left: 30px;
    }
    
    .timeline-item {
        position: relative;
    }
    
    .timeline-marker {
        position: absolute;
        left: -30px;
        top: 0;
        width: 15px;
        height: 15px;
        border-radius: 50%;
    }
    
    .timeline-content {
        padding-bottom: 15px;
        border-bottom: 1px solid #e9ecef;
    }
    
    .timeline-item:last-child .timeline-content {
        border-bottom: none;
    }
    
    .avatar-circle-lg {
        width: 64px;
        height: 64px;
        background-color: #007bff;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        font-size: 24px;
        font-weight: 600;
    }
    
    /* Card border styles */
    .border-left-primary {
        border-left: 4px solid #4e73df !important;
    }
    
    .border-left-success {
        border-left: 4px solid #1cc88a !important;
    }
    
    .border-left-info {
        border-left: 4px solid #36b9cc !important;
    }
    
    .border-left-warning {
        border-left: 4px solid #f6c23e !important;
    }
    </style>
</body>
</html>
