<?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 . ' | Affiliate Notes'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<?php
$adminId = $_SESSION['admin_id'];
$affiliateId = $_GET['affiliate_id'] ?? null;
$page = max(1, intval($_GET['page'] ?? 1));
$limit = 25;
$offset = ($page - 1) * $limit;

// Handle new note
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['note'], $_POST['affiliate_id'])) {
    $stmt = $pdo->prepare("INSERT INTO affiliate_notes (affiliate_id, admin_id, note) VALUES (?, ?, ?)");
    $stmt->execute([$_POST['affiliate_id'], $adminId, $_POST['note']]);
    log_admin_action($pdo, 'add_affiliate_note', "Note added for affiliate #{$_POST['affiliate_id']}");
    echo "<p class='success'>✅ Note added.</p>";
}

// Build query
$query = "SELECT n.*, a.name AS affiliate_name, u.username AS admin_name 
          FROM affiliate_notes n 
          JOIN affiliates a ON n.affiliate_id = a.id 
          JOIN admin_users u ON n.admin_id = u.id";
$params = [];

if ($affiliateId) {
    $query .= " WHERE n.affiliate_id = ?";
    $params[] = $affiliateId;
}

$countQuery = str_replace("n.*, a.name AS affiliate_name, u.username AS admin_name", "COUNT(*)", $query);
$countStmt = $pdo->prepare($countQuery);
$countStmt->execute($params);
$totalNotes = $countStmt->fetchColumn();
$totalPages = ceil($totalNotes / $limit);

$query .= " ORDER BY n.created_at DESC LIMIT $limit OFFSET $offset";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$notes = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Export CSV
if (isset($_GET['export'])) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename=affiliate_notes.csv');
    echo "Affiliate,Note,By,Time\n";
    foreach ($notes as $n) {
        echo "\"{$n['affiliate_name']}\",\"".str_replace('"','""',$n['note'])."\",\"{$n['admin_name']}\",\"{$n['created_at']}\"\n";
    }
    exit;
}

// UI
echo "<h2>🧾 Affiliate Notes</h2>
<form method='post'>
    <input name='affiliate_id' placeholder='Affiliate ID' required>
    <textarea name='note' placeholder='Internal note' required></textarea>
    <button type='submit'>Add Note</button>
</form>";

echo "<form method='get'>
    <input name='affiliate_id' placeholder='Affiliate ID' value='" . htmlspecialchars($affiliateId) . "'>
    <button type='submit'>Filter</button>
    <button onclick=\"window.location='?affiliate_id=$affiliateId&export=1';return false;\">Export CSV</button>
</form>";

echo "<table><tr>
    <th>Affiliate</th><th>Note</th><th>By</th><th>Time</th>
</tr>";
foreach ($notes as $n) {
    echo "<tr>
        <td>" . htmlspecialchars($n['affiliate_name']) . " (#" . htmlspecialchars($n['affiliate_id']) . ")</td>
        <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($n['note']) . "</textarea></td>
        <td>" . htmlspecialchars($n['admin_name']) . "</td>
        <td>{$n['created_at']}</td>
    </tr>";
}
echo "</table>";

// Pagination
if ($totalPages > 1) {
    echo "<div style='margin-top:20px'><strong>Pages:</strong> ";
    for ($i = 1; $i <= $totalPages; $i++) {
        $link = "?affiliate_id=$affiliateId&page=$i";
        echo "<a href='$link' style='margin-right:10px'>" . ($i == $page ? "<strong>$i</strong>" : $i) . "</a>";
    }
    echo "</div>";
}
?>
</div>
</body>
</html>