<?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 Profile'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<?php
$affId = $_GET['id'] ?? 0;
if (!$affId) die("Missing affiliate ID");

$adminId = $_SESSION['admin_id'];

// Update status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_affiliate'])) {
    $stmt = $pdo->prepare("UPDATE users SET email = ?, is_active = ? WHERE id = ?");
    $stmt->execute([
        $_POST['email'],
        isset($_POST['is_active']) ? 1 : 0,
        $affId
    ]);
    echo "<p class='success'>✅ Affiliate updated.</p>";
}

// Add note
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_note'])) {
    $stmt = $pdo->prepare("INSERT INTO affiliate_notes (affiliate_id, note, added_by) VALUES (?, ?, ?)");
    $stmt->execute([$affId, $_POST['note'], $adminId]);
    echo "<p class='success'>📝 Note added.</p>";
}

// Fetch affiliate
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$affId]);
$aff = $stmt->fetch(PDO::FETCH_ASSOC);

// Fetch notes
$stmt = $pdo->prepare("SELECT n.*, a.username FROM affiliate_notes n 
                       JOIN admin_users a ON n.added_by = a.id 
                       WHERE affiliate_id = ? ORDER BY added_at DESC");
$stmt->execute([$affId]);
$notes = $stmt->fetchAll(PDO::FETCH_ASSOC);

// UI
echo "<h2>👤 Affiliate Profile: " . htmlspecialchars($aff['username']) . " (#" . htmlspecialchars($affId) . ")</h2>
<form method='post'>
    <label>Email: <input name='email' value='" . htmlspecialchars($aff['email']) . "'></label><br>
    <label><input type='checkbox' name='is_active'" . ($aff['is_active'] ? ' checked' : '') . "> Active</label><br>
    <button name='update_affiliate' type='submit'>Update</button>
</form>";

echo "<hr><h3>📝 Internal Notes</h3>
<form method='post'>
    <textarea name='note' placeholder='Add note'></textarea><br>
    <button name='add_note' type='submit'>Add Note</button>
</form>";

echo "<table><tr><th>Note</th><th>By</th><th>Time</th></tr>";
foreach ($notes as $n) {
    echo "<tr>
        <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($n['note']) . "</textarea></td>
        <td>" . htmlspecialchars($n['username']) . "</td>
        <td>{$n['added_at']}</td>
    </tr>";
}
echo "</table>";
?>
</div>
</body>
</html>