<?php
// data_user/my_downloads.php
session_start();
require_once '../config.php';
require_once '../includes/auth.php';
require_once '../classes/DataSource.php';

// Ensure only Data Users can access this page
redirect_if_not_role('Data Contributor');

$user_id = $_SESSION['user_id'];
$person_id = $_SESSION['person_id']; // This is the correct ID to use for the join
$username = $_SESSION['username'];

$data_source_manager = new DataSource($pdo);

// Fetch download history for the current user
$download_history = [];
try {
    $stmt = $pdo->prepare("
        SELECT dsu.*,
               ds.dspsds_title_en,
               ds.dspsds_filename,
               tds.dspstds_name_en
        FROM dsps_tbl_datasource_used dsu
        JOIN dsps_tbl_datasource ds
            ON dsu.fkdspsdsused_id = ds.pkdspsds_id
        JOIN dsps_tbl_typedatasource tds
            ON ds.fkdspstds_id = tds.pkdspstds_id
        WHERE dsu.fkisp_id_of = :person_id
          AND dsu.dspsdspused_action = 'Downloaded'
        ORDER BY dsu.dspsdspused_datetime DESC
    ");
    $stmt->execute(['person_id' => $person_id]);
    $download_history = $stmt->fetchAll();
} catch (PDOException $e) {
    error_log("Error fetching download history: " . $e->getMessage());
    set_message("Error fetching download history.", "danger");
}

?>
<!DOCTYPE html>
<html lang="en">
<!-- Header -->
<?php
// Include header file for admin pages
include_once("../includes/header_contributor.php");
?>
<body>
    <div class="wrapper">
        <!-- Sidebar -->
        <?php
        // Include header file for admin pages
        include_once("../includes/nav_contributor.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="#"> My Downloads History</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="card shadow-sm rounded">
                <div class="card-header bg-light rounded-top">
                    <h5 class="mb-0">Downloaded Data Sources</h5>
                </div>
                <div class="card-body">
                    <?php if (!empty($download_history)): ?>
                        <div class="table-responsive">
                            <table class="table table-hover table-striped">
                                <thead>
                                    <tr>
                                        <th>Data Source</th>
                                        <th>Type</th>
                                        <th>Download Date</th>
                                        <th>File</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($download_history as $item): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($item['dspsds_title_en']) ?></td>
                                            <td><?= htmlspecialchars($item['dspstds_name_en']) ?></td>
                                            <td><?= date('Y-m-d H:i', strtotime($item['dspsdspused_datetime'])) ?></td>
                                            <td>
                                                <?php if (!empty($item['dspsds_filename'])): ?>
                                                    <!--
                                                        This is the CORRECTED line. It now points to download.php
                                                        and passes the ID of the data source.
                                                    -->
                                                    <a href="download.php?dspsds_id=<?= htmlspecialchars($item['fkdspsdsused_id']) ?>" class="btn btn-sm btn-outline-primary text-dark badge">
                                                        <i class="fas fa-download me-1"></i> Download Again
                                                    </a>
                                                <?php else: ?>
                                                    N/A (API or no direct file)
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-info rounded mb-0">You have not downloaded any data sources yet.</div>
                    <?php endif; ?>
                </div>
            </div>

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