<?php include 'includes/header.php'; ?>
<?php include 'includes/sidebar.php'; ?>
<?php require 'includes/db_connect.php'; ?>

<?php
if (isset($_POST['send_sms'])) {
    $staff_phone = $_POST['staff_phone'];
    $message = $_POST['message'];

    $api_key = 'YOUR_TERMI_API_KEY';
    $sender_id = 'OfficeMail';

    $payload = array(
        'to' => $staff_phone,
        'from' => $sender_id,
        'sms' => $message,
        'type' => 'plain',
        'channel' => 'generic',
        'api_key' => $api_key
    );

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://api.ng.termii.com/api/sms/send",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_HTTPHEADER => array(
            "Content-Type: application/json"
        ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        echo "<script>alert('Error sending SMS: $err');</script>";
    } else {
        echo "<script>alert('SMS sent successfully.'); window.location='staff_list.php';</script>";
    }
}
?>

<div class="container mt-4">
    <h4 class="text-orange">Send SMS to Staff</h4>

    <form method="post" class="mt-3">
        <div class="mb-3">
            <label>Select Staff</label>
            <select name="staff_phone" class="form-control" required>
                <option value="">-- Select Staff --</option>
                <?php
                $staffs = $conn->query("SELECT * FROM staff ORDER BY fullname ASC");
                while ($staff = $staffs->fetch_assoc()) {
                    echo "<option value='{$staff['phone']}'>{$staff['name']}  {$staff['phone']}</option>";
                }
                ?>
            </select>
        </div>

        <div class="mb-3">
            <label>Message</label>
            <textarea name="message" class="form-control" rows="3" required></textarea>
        </div>

        <button type="submit" name="send_sms" class="btn btn-warning text-white">Send SMS</button>
    </form>
</div>

<?php include 'includes/footer.php'; ?>
