<?php
require_once '../includes/constants.php';
require_once '../includes/session.php';

if (!isset($_SESSION['admin_id']) || !in_array($_SESSION['admin_role'], ['manager','superadmin'])) {
    die("Access denied");
}
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Admin Module Tracker'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<?php
$filterStatus = $_GET['status'] ?? null;
$search = $_GET['search'] ?? null;

// Handle new module or update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $stmt = $pdo->prepare("INSERT INTO admin_modules (module_name, file_path, status, audit_notes) 
        VALUES (?, ?, ?, ?) 
        ON DUPLICATE KEY UPDATE status = VALUES(status), audit_notes = VALUES(audit_notes), last_updated = NOW()");
    $stmt->execute([
        $_POST['module_name'],
        $_POST['file_path'],
        $_POST['status'],
        $_POST['audit_notes']
    ]);
    echo "<p class='success'>✅ Module saved.</p>";
}

// Fetch modules
$query = "SELECT * FROM admin_modules WHERE 1";
$params = [];

if ($filterStatus) {
    $query .= " AND status = ?";
    $params[] = $filterStatus;
}
if ($search) {
    $query .= " AND (module_name LIKE ? OR audit_notes LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$query .= " ORDER BY last_updated DESC";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$modules = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Export CSV
if (isset($_GET['export'])) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename=admin_module_tracker.csv');
    echo "Module,File,Status,Last Updated,Notes\n";
    foreach ($modules as $m) {
        echo "\"{$m['module_name']}\",\"{$m['file_path']}\",\"{$m['status']}\",\"{$m['last_updated']}\",\"{$m['audit_notes']}\"\n";
    }
    exit;
}

// UI
echo "<h2>🧩 Admin Module Tracker</h2>
<form method='post'>
    <label>Module Name: <input name='module_name' placeholder='Module name' required></label><br>
    <label>File Path: <input name='file_path' placeholder='File path (e.g. admin_affiliate_flags.php)' required></label><br>
    <label>Status:
        <select name='status'>
            <option value='done'>✅ Done</option>
            <option value='in_progress'>🚧 In Progress</option>
            <option value='needs_review'>🛠️ Needs Review</option>
        </select>
    </label><br>
    <label>Audit Notes:<br>
        <textarea name='audit_notes' placeholder='Audit notes'></textarea>
    </label><br>
    <button type='submit'>Save</button>
</form>";

echo "<form method='get' style='margin-top:20px'>
    <label>Status:
        <select name='status'>
            <option value=''>All Statuses</option>
            <option value='done'" . ($filterStatus === 'done' ? ' selected' : '') . ">✅ Done</option>
            <option value='in_progress'" . ($filterStatus === 'in_progress' ? ' selected' : '') . ">🚧 In Progress</option>
            <option value='needs_review'" . ($filterStatus === 'needs_review' ? ' selected' : '') . ">🛠️ Needs Review</option>
        </select>
    </label>
    <label>Search:
        <input name='search' placeholder='Search notes or module name' value='" . htmlspecialchars($search) . "'>
    </label>
    <button type='submit'>Filter</button>
    <button onclick=\"window.location='?status=" . urlencode($filterStatus) . "&search=" . urlencode($search) . "&export=1';return false;\">Export CSV</button>
</form>";

echo "<table><tr>
    <th>Module</th><th>File</th><th>Status</th><th>Last Updated</th><th>Notes</th>
</tr>";
foreach ($modules as $m) {
    echo "<tr>
        <td>" . htmlspecialchars($m['module_name']) . "</td>
        <td>" . htmlspecialchars($m['file_path']) . "</td>
        <td>" . htmlspecialchars($m['status']) . "</td>
        <td>{$m['last_updated']}</td>
        <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($m['audit_notes']) . "</textarea></td>
    </tr>";
}
echo "</table>";
?>
</div>
</body>
</html>