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

if (!isset($_SESSION['admin_id']) || !in_array($_SESSION['admin_role'], ['manager','superadmin'])) {
    die("Access denied");
}

$offerId = $_GET['id'] ?? 0;
$userId = $_SESSION['user_id'] ?? 0;
if (!$offerId || !$userId) die("Missing offer ID or user session");

// Handle insert
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $stmt = $pdo->prepare("INSERT INTO partners_offer_notes (offer_id, note_type, note_text, created_by)
                           VALUES (?, ?, ?, ?)");
    $stmt->execute([
        $offerId,
        $_POST['note_type'],
        $_POST['note_text'],
        $userId
    ]);
    echo "<p class='success'>✅ Note saved.</p>";
}

// Fetch notes
$stmt = $pdo->prepare("SELECT n.*, u.username FROM partners_offer_notes n 
                       JOIN users u ON n.created_by = u.id 
                       WHERE n.offer_id = ? ORDER BY n.created_at DESC");
$stmt->execute([$offerId]);
$notes = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Offer Notes'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<h2>📝 Add Note for Offer #<?php echo htmlspecialchars($offerId); ?></h2>
<form method="post">
    <label>Note Type:
        <select name="note_type">
            <option value="admin">Admin Only</option>
            <option value="advertiser">Advertiser Quick Note</option>
        </select>
    </label><br>
    <label>Note Text:<br>
        <textarea name="note_text" placeholder="Your note here..."></textarea>
    </label><br>
    <button type="submit">Save Note</button>
</form>

<hr><h3>📋 Existing Notes</h3>
<table><tr><th>Type</th><th>Note</th><th>By</th><th>Time</th></tr>
<?php
foreach ($notes as $n) {
    echo "<tr>
        <td>" . htmlspecialchars($n['note_type']) . "</td>
        <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($n['note_text']) . "</textarea></td>
        <td>" . htmlspecialchars($n['username']) . "</td>
        <td>{$n['created_at']}</td>
    </tr>";
}
?>
</table>
</div>
</body>
</html>