<?php
// data_owner/dashboard.php
session_start();
require_once '../config.php';
require_once '../includes/auth.php';
require_once '../classes/User.php';
require_once '../classes/DataSource.php'; // For counts

// Ensure only Data Owners can access this dashboard
redirect_if_not_role('Data Owner');

$user_id = $_SESSION['user_id'];
$person_id = $_SESSION['person_id']; // The fkisp_id_of for the data owner
$username = $_SESSION['username'];
$user_status = $_SESSION['user_status'];

// Instantiate classes
$user_manager = new User($pdo);
$data_source_manager = new DataSource($pdo);

// Get dynamic counts for the Data Owner
$my_data_sources_count = count($data_source_manager->getDataSources($person_id));
$pending_permissions_count = count($data_source_manager->getPermissionRequestsForOwner($person_id, 'Pending'));
$usageByUser = $data_source_manager->getUsageByUserForOwner($person_id, 6);
$data_accesses_last_30_days = 0;
if (!empty($usageByUser)) {
    foreach ($usageByUser as $row) {
        $data_accesses_last_30_days += (int) ($row['usage_count'] ?? 0);
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<!-- Header -->
<?php
// Include header file for admin pages
include_once("../includes/header_owner.php");
?>

<body>
    <div class="wrapper">
        <!-- Sidebar -->
        <?php
        // Include header file for admin pages
        include_once("../includes/nav_owner.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-primary"><i class="fas fa-database me-2"></i> My Data Sources</h5>
                            <p class="card-text fs-2"><?= $my_data_sources_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-half me-2"></i> Pending Permissions</h5>
                            <p class="card-text fs-2"><?= $pending_permissions_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-success"><i class="fas fa-download me-2"></i> Data Accesses (Last 30 Days)</h5>
                            <p class="card-text fs-2"><?= $data_accesses_last_30_days ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <?php
                $chartLabels = [];
                $chartValues = [];
                if (!empty($usageByUser)) {
                    foreach ($usageByUser as $row) {
                        $chartLabels[] = $row['username'] ?? 'Unknown';
                        $chartValues[] = (int) ($row['usage_count'] ?? 0);
                    }
                }
            ?>

            <div class="row mt-5">
                <div class="col-lg-6">
                    <div class="card shadow-sm rounded h-100">
                        <div class="card-header bg-light rounded-top">
                            <h5 class="mb-0">Usage Breakdown by User</h5>
                        </div>
                        <div class="card-body">
                            <?php if (!empty($chartValues)): ?>
                                <canvas id="usagePieChart" height="280"></canvas>
                            <?php else: ?>
                                <div class="alert alert-info rounded mb-0">No data usage recorded yet.</div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <div class="mt-5">
                <h3>Quick Actions</h3>
                <div class="d-flex flex-wrap gap-3">
                    <a href="manage_my_datasources.php?action=add" class="btn btn-primary rounded"><i class="fas fa-plus-circle me-2"></i> Add New Data Source</a>
                    <a href="manage_permissions.php" class="btn btn-warning rounded"><i class="fas fa-user-check me-2"></i> Review Permissions</a>
                    <a href="my_analytics.php" class="btn btn-info rounded"><i class="fas fa-chart-pie me-2"></i> View My Data Usage</a>
                </div>
            </div>

            <!-- Placeholder for recent activity related to their data sources -->
            <div class="mt-5">
                <h3>Recent Activity on My Data Sources</h3>
                <ul class="list-group shadow-sm rounded">
                    <?php
                    // Example recent activities (replace with actual data from dsps_tbl_datasource_used and dsps_tbl_anonymous)
                    // You'd need to fetch these from the database, potentially joining with dsps_tbl_datasource
                    $recent_activities = [
                        ['text' => 'User John Doe requested access to \'Population Census 2023\'.', 'time' => 'Just now', 'type' => 'info'],
                        ['text' => '\'Health Data Q1 2024\' was downloaded 5 times today.', 'time' => '2 hours ago', 'type' => 'success'],
                        ['text' => 'You updated \'Education Statistics 2022\'.', 'time' => 'Yesterday', 'type' => 'secondary'],
                    ];
                    foreach ($recent_activities as $activity) {
                        echo '<li class="list-group-item d-flex justify-content-between align-items-center">';
                        echo htmlspecialchars($activity['text']);
                        echo '<span class="badge bg-' . htmlspecialchars($activity['type']) . '">' . htmlspecialchars($activity['time']) . '</span>';
                        echo '</li>';
                    }
                    ?>
                </ul>
            </div>

        </div>
    </div>
<!-- Footer -->
<?php
// Include Footer file for owner pages
include_once("../includes/footer_owner.php");
?>    
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.6/dist/chart.umd.min.js" integrity="sha256-VjZ1tcHTul3e8DqRL3OjaxAg/P070MqxsVXni4eWh05=" crossorigin="anonymous"></script>
<script>
    (function () {
        const labels = <?= json_encode(array_map('htmlspecialchars', $chartLabels)) ?>;
        const values = <?= json_encode($chartValues) ?>;

        if (!Array.isArray(labels) || !Array.isArray(values) || labels.length === 0) {
            return;
        }

        const ctx = document.getElementById('usagePieChart');
        if (!ctx) {
            return;
        }

        const backgroundColors = [
            '#0d6efd', '#198754', '#dc3545', '#fd7e14', '#6f42c1', '#20c997', '#0dcaf0'
        ];

        new Chart(ctx, {
            type: 'pie',
            data: {
                labels: labels,
                datasets: [{
                    data: values,
                    backgroundColor: backgroundColors,
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: { position: 'bottom' },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const label = context.label || '';
                                const value = context.parsed || 0;
                                return `${label}: ${value}`;
                            }
                        }
                    }
                }
            }
        });
    })();
</script>
</body>
</html>
