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

redirect_if_not_logged_in('../index.php');
redirect_if_not_role('DAC Staff', '../index.php');

$dataSourceManager = new DataSource($pdo);
$search_query = trim($_GET['search'] ?? '');
$status_filter = trim($_GET['status_filter'] ?? '');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $datasourceId = isset($_POST['datasource_id']) ? (int)$_POST['datasource_id'] : 0;

    if ($action === 'change_status' && $datasourceId > 0) {
        $newStatus = trim($_POST['new_status'] ?? '');
        try {
            $dataSourceManager->updateDataSourceStatus($datasourceId, $newStatus, (int) $_SESSION['user_id']);
            set_message('Data source status updated successfully.', 'success');
        } catch (Exception $e) {
            set_message('Failed to update status: ' . $e->getMessage(), 'danger');
        }
    } elseif ($action === 'delete' && $datasourceId > 0) {
        try {
            if ($dataSourceManager->deleteDataSource($datasourceId)) {
                set_message('Data source deleted.', 'success');
            } else {
                set_message('Unable to delete data source.', 'danger');
            }
        } catch (Exception $e) {
            set_message('Deletion failed: ' . $e->getMessage(), 'danger');
        }
    }

    $redirectUrl = 'manage_datasources.php';
    $params = [];
    if ($search_query !== '') {
        $params['search'] = urlencode($search_query);
    }
    if ($status_filter !== '') {
        $params['status_filter'] = urlencode($status_filter);
    }
    if (!empty($params)) {
        $redirectUrl .= '?' . http_build_query($params);
    }
    header('Location: ' . $redirectUrl);
    exit();
}

$dataSources = $dataSourceManager->getAllDataSourcesDetailed(
    $search_query !== '' ? $search_query : null,
    $status_filter !== '' ? $status_filter : null
);

$statuses = ['Active', 'Inactive', 'Pending Review', 'Published'];
$uploadsWebPath = '../uploads/datasources/';
?>
<!DOCTYPE html>
<html lang="en">
<?php include_once("../includes/header_admin.php"); ?>
<body>
    <div class="wrapper">
        <?php include_once("../includes/nav_admin.php"); ?>
        <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="#">Manage Data Sources</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'])) {
                echo '<div class="alert alert-' . $_SESSION['message_type'] . ' alert-dismissible fade show rounded" role="alert">'
                    . htmlspecialchars($_SESSION['message']) .
                    '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>';
                unset($_SESSION['message'], $_SESSION['message_type']);
            }
            ?>

            <div class="card mb-4">
                <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">All Data Sources</h5>
                </div>
                <div class="card-body">
                    <form class="row g-3 align-items-end mb-4" method="GET" action="manage_datasources.php">
                        <div class="col-md-5">
                            <label for="searchDataSource" class="form-label">Search</label>
                            <input type="text" class="form-control rounded" id="searchDataSource" name="search" value="<?= htmlspecialchars($search_query) ?>" placeholder="Title, owner, or type">
                        </div>
                        <div class="col-md-4">
                            <label for="statusFilter" class="form-label">Status</label>
                            <select class="form-select rounded" id="statusFilter" name="status_filter">
                                <option value="">All statuses</option>
                                <?php foreach ($statuses as $status): ?>
                                    <option value="<?= htmlspecialchars($status) ?>" <?= $status_filter === $status ? 'selected' : '' ?>><?= htmlspecialchars($status) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <button type="submit" class="btn btn-info rounded me-2"><i class="fas fa-filter me-2"></i>Apply</button>
                            <a href="manage_datasources.php" class="btn btn-outline-secondary rounded"><i class="fas fa-sync-alt me-2"></i>Reset</a>
                        </div>
                    </form>

                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th>ID</th>
                                    <th>Title</th>
                                    <th>Owner</th>
                                    <th>Type</th>
                                    <th>Category</th>
                                    <th>Status</th>
                                    <th>Files</th>
                                    <th>Registered</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($dataSources)): ?>
                                    <?php foreach ($dataSources as $ds): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($ds['pkdspsds_id']) ?></td>
                                            <td><?= htmlspecialchars($ds['dspsds_title_en']) ?></td>
                                            <td><?= htmlspecialchars($ds['owner_name']) ?></td>
                                            <td><?= htmlspecialchars($ds['data_type_name']) ?></td>
                                            <td><?= htmlspecialchars($ds['category_name']) ?></td>
                                            <td>
                                                <form class="d-flex align-items-center gap-2" method="POST">
                                                    <input type="hidden" name="datasource_id" value="<?= (int)$ds['pkdspsds_id'] ?>">
                                                    <input type="hidden" name="action" value="change_status">
                                                    <select class="form-select form-select-sm" name="new_status">
                                                        <?php foreach ($statuses as $status): ?>
                                                            <option value="<?= htmlspecialchars($status) ?>" <?= $ds['dspsds_status'] === $status ? 'selected' : '' ?>><?= htmlspecialchars($status) ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <button type="submit" class="btn btn-sm btn-outline-primary rounded">Update</button>
                                                </form>
                                            </td>
                                            <td>
                                                <?php
                                                $fileColumns = [
                                                    'dspsds_filename' => 'Primary',
                                                    'dspsds_filename1' => 'Doc 1',
                                                    'dspsds_filename2' => 'Doc 2',
                                                    'dspsds_filename3' => 'Doc 3',
                                                ];
                                                $links = [];
                                                foreach ($fileColumns as $column => $label) {
                                                    $fileName = $ds[$column] ?? '';
                                                    if ($fileName === '') {
                                                        continue;
                                                    }
                                                    $isUrl = preg_match('/^https?:\\/\\//i', $fileName) === 1;
                                                    $target = $isUrl ? $fileName : $uploadsWebPath . rawurlencode($fileName);
                                                    $links[] = '<a class="btn btn-sm btn-outline-secondary rounded-pill me-1 mb-1" href="' . htmlspecialchars($target) . '" target="_blank" rel="noopener" title="' . htmlspecialchars($label) . '"><i class="fas fa-paperclip"></i></a>';
                                                }
                                                echo !empty($links) ? implode('', $links) : '<span class="text-muted">—</span>';
                                                ?>
                                            </td>
                                            <td><?= htmlspecialchars(date('Y-m-d', strtotime($ds['dspsds_reg_datetime'] ?? 'now'))) ?></td>
                                            <td>
                                                <form method="POST" onsubmit="return confirm('Delete this data source? This cannot be undone.');">
                                                    <input type="hidden" name="datasource_id" value="<?= (int)$ds['pkdspsds_id'] ?>">
                                                    <input type="hidden" name="action" value="delete">
                                                    <button type="submit" class="btn btn-sm btn-outline-danger rounded"><i class="fas fa-trash-alt"></i></button>
                                                </form>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="9" class="text-center text-muted py-4">No data sources found.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
<?php include_once("../includes/footer_admin.php"); ?>
</body>
</html>
