<?php include '../db.php'; ?>

<h2>Manual Notification Sender</h2>
<form method="post">
    <label>Client:</label>
    <select name="client_id" required>
        <?php
        $clients = $conn->query("SELECT id, name FROM clients")->fetchAll();
        foreach ($clients as $c) {
            echo "<option value='{$c['id']}'>{$c['name']}</option>";
        }
        ?>
    </select><br>

    <label>Type:</label>
    <select name="type" required>
        <option value="email">Email</option>
        <option value="whatsapp">WhatsApp</option>
    </select><br>

    <label>Subject:</label><br>
    <input type="text" name="subject" required><br>

    <label>Message:</label><br>
    <textarea name="message" rows="5" required></textarea><br>

    <button type="submit">Send Notification</button>
</form>

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $client_id = $_POST['client_id'];
    $type = $_POST['type'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];

    // Get client contact
    $client = $conn->prepare("SELECT email, phone FROM clients WHERE id=?");
    $client->execute([$client_id]);
    $c = $client->fetch();

    $sent = false;
    if ($type === 'email') {
        $sent = mail($c['email'], $subject, $message, "From: admin@yourdomain.com");
    } elseif ($type === 'whatsapp') {
        include 'whatsapp_api.php';
        $sent = sendWhatsApp($c['phone'], $message);
    }

    // Log it
    $stmt = $conn->prepare("INSERT INTO notification_logs (client_id, type, subject, message, status) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$client_id, $type, $subject, $message, $sent ? 'success' : 'failed']);

    echo $sent ? "<p>Notification sent successfully!</p>" : "<p>Failed to send notification.</p>";
}
?>
