<?php
// data_user/dashboard.php
session_start();
require_once '../config.php';
require_once '../includes/auth.php';
require_once '../classes/DataSource.php'; // For data source related counts

// Ensure only Data Users can access this dashboard
redirect_if_not_role('Data User');

$user_id = $_SESSION['user_id'];
$person_id = $_SESSION['person_id'];
$username = $_SESSION['username'];
$user_status = $_SESSION['user_status'];

$data_source_manager = new DataSource($pdo);

// Get counts for Data User
$approved_datasources_count = 0;
try {
    $stmt = $pdo->prepare("
        SELECT COUNT(DISTINCT dp.fkdspsds_id)
        FROM dsps_tbl_datasource_permission dp
        WHERE dp.fkisp_id_of = :person_id AND dp.dspsdsp_status = 'Approved'
    ");
    $stmt->execute(['person_id' => $person_id]);
    $approved_datasources_count = $stmt->fetchColumn();
} catch (PDOException $e) {
    error_log("Error fetching approved datasources count: " . $e->getMessage());
}

$pending_requests_count = 0;
try {
    $stmt = $pdo->prepare("
        SELECT COUNT(dp.pkdspsdsp_id)
        FROM dsps_tbl_datasource_permission dp
        WHERE dp.fkisp_id_of = :person_id AND dp.dspsdsp_status = 'Pending'
    ");
    $stmt->execute(['person_id' => $person_id]);
    $pending_requests_count = $stmt->fetchColumn();
} catch (PDOException $e) {
    error_log("Error fetching pending requests count: " . $e->getMessage());
}

$my_downloads_count = 0;
try {
    $stmt = $pdo->prepare("
        SELECT COUNT(*) FROM dsps_tbl_datasource_used
        WHERE fkisp_id_of = :person_id AND dspsdspused_action = 'Downloaded'
    ");
    $stmt->execute(['person_id' => $person_id]);
    $my_downloads_count = $stmt->fetchColumn();
} catch (PDOException $e) {
    error_log("Error fetching my downloads count: " . $e->getMessage());
}

?>
<!DOCTYPE html>
<html lang="en">
<!-- Header -->
<?php
// Include header file for admin pages
include_once("../includes/header_user.php");
?>
<body>
    <div class="wrapper">
        <!-- Sidebar -->
        <?php
        // Include header file for admin pages
        include_once("../includes/nav_user.php");
        ?>
        <!-- Page Content -->
        <div class="main-content">
            <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4 rounded-3">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#"> Dashboard</a>
                    <div class="d-flex">
                        <span class="navbar-text me-3">
                            Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>!
                        </span>
                    </div>
                </div>
            </nav>

            <?php if (isset($_SESSION['message'])): ?>
                <div class="alert alert-<?= $_SESSION['message_type'] ?> alert-dismissible fade show rounded" role="alert">
                    <?= $_SESSION['message'] ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php
                unset($_SESSION['message']);
                unset($_SESSION['message_type']);
                ?>
            <?php endif; ?>

            <div class="row g-4">
                <div class="col-md-4">
                    <div class="card shadow-sm rounded">
                        <div class="card-body">
                            <h5 class="card-title text-success"><i class="fas fa-check-circle me-2"></i> Approved Data Sources</h5>
                            <p class="card-text fs-2"><?= $approved_datasources_count ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card shadow-sm rounded">
                        <div class="card-body">
                            <h5 class="card-title text-warning"><i class="fas fa-hourglass-start me-2"></i> Pending Requests</h5>
                            <p class="card-text fs-2"><?= $pending_requests_count ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card shadow-sm rounded">
                        <div class="card-body">
                            <h5 class="card-title text-info"><i class="fas fa-download me-2"></i> My Total Downloads</h5>
                            <p class="card-text fs-2"><?= $my_downloads_count ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="mt-5">
                <h3>Quick Actions</h3>
                <div class="d-flex flex-wrap gap-3">
                    <a href="browse_datasources.php" class="btn btn-primary rounded"><i class="fas fa-search me-2"></i> Browse All Data</a>
                    <a href="my_permissions.php" class="btn btn-warning rounded"><i class="fas fa-handshake me-2"></i> View My Permissions</a>
                    <a href="my_downloads.php" class="btn btn-info rounded"><i class="fas fa-download me-2"></i> My Download History</a>
                </div>
            </div>

            <!-- Placeholder for recently accessed data sources -->
            <div class="mt-5">
                <h3>Recently Accessed Data Sources</h3>
                <ul class="list-group shadow-sm rounded">
                    <?php
                    // Example recent activities (replace with actual data from dsps_tbl_datasource_used)
                    // You'd need to fetch these from the database, filtered by fkisp_id_of = $person_id
                    $recent_accesses = [
                        ['title' => 'Health Survey 2023', 'action' => 'Downloaded', 'time' => '1 hour ago'],
                        ['title' => 'Education Statistics 2022', 'action' => 'Viewed Details', 'time' => 'Yesterday'],
                        ['title' => 'Climate Data Phnom Penh', 'action' => 'Ran Analysis', 'time' => '3 days ago'],
                    ];
                    if (!empty($recent_accesses)) {
                        foreach ($recent_accesses as $access) {
                            echo '<li class="list-group-item d-flex justify-content-between align-items-center">';
                            echo htmlspecialchars($access['title']) . ' - ' . htmlspecialchars($access['action']);
                            echo '<span class="badge bg-secondary">' . htmlspecialchars($access['time']) . '</span>';
                            echo '</li>';
                        }
                    } else {
                        echo '<li class="list-group-item text-center text-muted">No recent activity.</li>';
                    }
                    ?>
                </ul>
            </div>

        </div>
    </div>
    <!-- Footer -->
    <?php
    // Include Footer file for owner pages
    include_once("../includes/footer_user.php");
    ?>   
</body>
</html>