<?php
require_once '../../config.php';
require_once '../../functions.php';

header('Content-Type: application/json');

if (!isset($_SESSION['admin_id']) && !isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'POST only']);
    exit;
}

$title = trim($_POST['title'] ?? '');
$message = trim($_POST['message'] ?? '');
$owner_type = isset($_SESSION['admin_id']) ? 'admin' : 'user';
$owner_id = $_SESSION['admin_id'] ?? $_SESSION['user_id'] ?? null;

if (empty($title) || empty($message)) {
    echo json_encode(['success' => false, 'error' => 'Title and message required']);
    exit;
}

try {
    $stmt = $pdo->prepare("INSERT INTO sms_templates (title, message, owner_type, owner_id) VALUES (?, ?, ?, ?)");
    $stmt->execute([$title, $message, $owner_type, $owner_id]);
    echo json_encode(['success' => true, 'id' => $pdo->lastInsertId()]);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>