<?php
require_once __DIR__ . '/../config.php'; // adjust path as needed
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/layout.php';  // auth + header + sidebar + topbar

if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    header('Location: /login.php');
    exit;
}

$userId = $_SESSION['admin_user_id'];

$error = '';
$success = '';

// Fetch all users except self for recipient dropdown
$stmt = $pdo->prepare("SELECT id, username FROM admin_users WHERE id != ? ORDER BY username ASC");
$stmt->execute([$userId]);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $recipient_id = (int)($_POST['recipient_id'] ?? 0);
    $subject = trim($_POST['subject'] ?? '');
    $body = trim($_POST['body'] ?? '');

    // Basic server-side validation
    if ($recipient_id <= 0 || !$subject || !$body) {
        $error = 'Please fill in all fields.';
    } else {
        // Confirm recipient exists
        $exists = $pdo->prepare("SELECT COUNT(*) FROM admin_users WHERE id = ?");
        $exists->execute([$recipient_id]);
        if ($exists->fetchColumn() == 0) {
            $error = 'Invalid recipient selected.';
        }
    }

    if (!$error) {
        try {
            $stmt = $pdo->prepare("INSERT INTO messages (sender_id, recipient_id, subject, body, sent_at, is_read) VALUES (?, ?, ?, ?, NOW(), 0)");
            $stmt->execute([$userId, $recipient_id, $subject, $body]);
            $success = 'Message sent successfully!';
            // Clear form fields after success
            $subject = '';
            $body = '';
            $recipient_id = 0;
        } catch (Exception $e) {
            $error = 'Error sending message: ' . $e->getMessage();
        }
    }
}

$pageTitle = 'Create New Message';
require_once __DIR__ . '/includes/header.php';
?>

<h1><?= htmlspecialchars($pageTitle) ?></h1>

<?php if ($error): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
<?php elseif ($success): ?>
    <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
<?php endif; ?>

<form method="post" id="messageForm" novalidate class="w-75">
    <div class="mb-3">
        <label for="recipient_id" class="form-label">Recipient</label>
        <select name="recipient_id" id="recipient_id" class="form-select" required>
            <option value="">-- Select recipient --</option>
            <?php foreach ($users as $user): ?>
                <option value="<?= (int)$user['id'] ?>" <?= (isset($recipient_id) && $recipient_id == $user['id']) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($user['username']) ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>

    <div class="mb-3">
        <label for="subject" class="form-label">Subject</label>
        <input type="text" id="subject" name="subject" class="form-control" value="<?= htmlspecialchars($subject ?? '') ?>" required />
    </div>

    <div class="mb-3">
        <label for="body" class="form-label">Message Body</label>
        <textarea id="body" name="body" class="form-control" rows="10"><?= htmlspecialchars($body ?? '') ?></textarea>
    </div>

    <button type="submit" class="btn btn-primary">Send Message</button>
</form>

<script src="https://cdn.tiny.cloud/1/w4vz3wunp3pewnc7bavv3u16ollglu4nimw1v7tfm35g302r/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
tinymce.init({
    selector: '#body',
    height: 250,
    menubar: false,
    plugins: 'lists link',
    toolbar: 'undo redo | bold italic | bullist numlist | link',
    branding: false
});

document.getElementById('messageForm').addEventListener('submit', function(e) {
    const subject = document.getElementById('subject').value.trim();
    const body = tinymce.get('body').getContent({ format: 'text' }).trim();
    const recipient = document.getElementById('recipient_id').value;

    if (!recipient) {
        alert('Please select a recipient.');
        e.preventDefault();
        return;
    }
    if (!subject) {
        alert('Please enter a subject.');
        e.preventDefault();
        return;
    }
    if (!body) {
        alert('Please enter a message.');
        e.preventDefault();
    }
});
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
