<?php
session_start();
include_once '../config/connect.php';
require_once '../config/whatsapp.php';

if (!isset($_SESSION['admin'])) {
    http_response_code(403);
    exit('FORBIDDEN');
}

if (!isset($_POST['send_whatsapp_test'])) {
    header('Location: ../Settings');
    exit;
}

$rawTarget = trim((string)($_POST['whatsapp_test_target'] ?? ''));
$message = trim((string)($_POST['whatsapp_test_message'] ?? ''));
$target = wa_normalize_number($rawTarget);

if ($target === '') {
    header('Location: ../Settings?msg=56');
    exit;
}

if ($message === '') {
    header('Location: ../Settings?msg=57');
    exit;
}

if (!wa_is_configured($call)) {
    header('Location: ../Settings?msg=58');
    exit;
}

$fullMessage = $message . "\nTujuan: {$target}";

wa_log('manual_test_send', [
    'target' => $target,
    'admin' => (string)($_SESSION['admin']['agent_name'] ?? 'unknown'),
]);

if (!wa_send_message($call, $target, $fullMessage)) {
    header('Location: ../Settings?msg=59');
    exit;
}

header('Location: ../Settings?msg=60');
exit;
