<?php
session_start();
require_once 'inc/functions.php';
check404();
securityCheck();
if (!isLoggedIn()) {
    header('Location: index.php');
    exit;
}

$currentUser = getUserById($_SESSION['user_id']);
if (!$currentUser) {
    session_destroy();
    header('Location: index.php');
    exit;
}

if (!isset($_POST['admin_send']) || $currentUser['role'] !== 'admin') {
    header('Location: profile.php');
    exit;
}

$recipientInput = trim($_POST['recipient']);
$subject = trim($_POST['subject']);
$body = trim($_POST['body']);
$attachType = $_POST['attach_type'] ?: null;
$attachValue = (int)$_POST['attach_value'];

if (empty($recipientInput) || empty($subject) || empty($body)) {
    $_SESSION['mail_error'] = 'Заполните все поля.';
    header('Location: profile.php');
    exit;
}

$toUser = is_numeric($recipientInput) ? getUserById($recipientInput) : getUserByUsername($recipientInput);
if (!$toUser) {
    $_SESSION['mail_error'] = 'Получатель не найден.';
    header('Location: profile.php');
    exit;
}

// Admin can send to any side
$success = sendMail($currentUser['id'], $toUser['id'], $subject, $body, $attachType, $attachValue);
if ($success) {
    $_SESSION['mail_success'] = 'Письмо с бонусом отправлено.';
} else {
    $_SESSION['mail_error'] = 'Ошибка отправки.';
}
header('Location: profile.php');
exit;