<?php
/** WhatsApp Cloud API — settings, test send, broadcast, log. */
if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');

require_once __DIR__ . '/../config.php';

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Not signed in.']);
    exit;
}
requireModule('whatsapp_comms', true);
require_once __DIR__ . '/../includes/whatsapp_lib.php';

$conn = getDBConnection();
wa_ensure_tables($conn);
$role = $_SESSION['role'] ?? '';
$action = $_POST['action'] ?? $_GET['action'] ?? '';

/** Upsert a settings row without depending on a unique key. */
function wa_set_setting(mysqli $conn, string $key, string $value): void
{
    $stmt = $conn->prepare("SELECT id FROM settings WHERE setting_key=? LIMIT 1");
    $stmt->bind_param('s', $key); $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc(); $stmt->close();
    if ($row) {
        $u = $conn->prepare("UPDATE settings SET setting_value=? WHERE setting_key=?");
        $u->bind_param('ss', $value, $key); $u->execute(); $u->close();
    } else {
        $i = $conn->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?,?)");
        $i->bind_param('ss', $key, $value); $i->execute(); $i->close();
    }
}

switch ($action) {

    case 'get_settings': {
        if (!in_array($role, ['admin', 'headteacher'], true)) { echo json_encode(['success' => false, 'message' => 'Admins only.']); break; }
        echo json_encode([
            'success'    => true,
            'configured' => wa_is_configured(),
            'phone_id'   => wa_config('wa_phone_id'),
            'verify_token' => wa_config('wa_verify_token'),
            'recipients' => wa_config('wa_report_recipients'),
            'has_token'  => wa_config('wa_token') !== '',
            'webhook_url'=> (defined('BASE_URL') ? rtrim(BASE_URL, '/') : '') . '/webhook/whatsapp.php',
        ]);
        break;
    }

    case 'save_settings': {
        if (!in_array($role, ['admin', 'headteacher'], true)) { echo json_encode(['success' => false, 'message' => 'Admins only.']); break; }
        $phoneId    = trim($_POST['phone_id'] ?? '');
        $verify     = trim($_POST['verify_token'] ?? '');
        $recipients = trim($_POST['recipients'] ?? '');
        $token      = trim($_POST['token'] ?? '');   // only overwrite when provided
        wa_set_setting($conn, 'wa_phone_id', $phoneId);
        wa_set_setting($conn, 'wa_verify_token', $verify);
        wa_set_setting($conn, 'wa_report_recipients', $recipients);
        if ($token !== '') wa_set_setting($conn, 'wa_token', $token);
        echo json_encode(['success' => true, 'message' => 'WhatsApp settings saved.', 'configured' => wa_is_configured()]);
        break;
    }

    case 'test_send': {
        if (!in_array($role, ['admin', 'headteacher'], true)) { echo json_encode(['success' => false, 'message' => 'Admins only.']); break; }
        $to  = trim($_POST['to'] ?? '');
        $msg = trim($_POST['message'] ?? '') ?: 'EduTrack WhatsApp test message ✅';
        if ($to === '') { echo json_encode(['success' => false, 'message' => 'Enter a recipient number.']); break; }
        if (!wa_is_configured()) { echo json_encode(['success' => false, 'message' => 'Configure the token and phone number ID first.']); break; }
        $r = send_whatsapp_text($to, $msg);
        echo json_encode(['success' => $r['success'], 'message' => $r['success'] ? 'Sent.' : ('Failed: ' . $r['error'])]);
        break;
    }

    // Broadcast free-form text to many numbers (comma/newline separated).
    case 'broadcast': {
        if (!in_array($role, ['admin', 'headteacher', 'supervisor', 'director'], true)) { echo json_encode(['success' => false, 'message' => 'Not permitted.']); break; }
        $numbers = preg_split('/[,\n;]+/', trim($_POST['numbers'] ?? ''));
        $message = trim($_POST['message'] ?? '');
        if ($message === '') { echo json_encode(['success' => false, 'message' => 'Message is empty.']); break; }
        $sent = 0; $failed = 0;
        foreach (array_filter(array_map('trim', $numbers)) as $num) {
            $r = sendWhatsApp($num, $message);
            if (!empty($r['success'])) $sent++; else $failed++;
        }
        echo json_encode(['success' => true, 'message' => "Sent {$sent}, failed {$failed}."]);
        break;
    }

    case 'get_log': {
        $rows = [];
        $res = $conn->query("SELECT to_number, message_type, message_preview, status, error_message, sent_at
                             FROM whatsapp_log ORDER BY id DESC LIMIT 50");
        while ($res && $row = $res->fetch_assoc()) $rows[] = $row;
        echo json_encode(['success' => true, 'data' => $rows]);
        break;
    }

    default:
        echo json_encode(['success' => false, 'message' => 'Unknown action.']);
}
