<?php
session_start();
include '../db/koneksi.php';
header('Content-Type: application/json');

// Pastikan user login
if (!isset($_SESSION['id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Sesi login tidak ditemukan.']);
    exit;
}

$user_id = $_SESSION['id'];
$username = $_SESSION['username'];

$subject = trim($_POST['subject']);
$message = trim($_POST['message']);

$errors = [];

if (empty($subject)) {
    $errors['subject'] = 'Subjek wajib diisi.';
}
if (empty($message)) {
    $errors['message'] = 'Pesan tidak boleh kosong.';
}

if (!empty($errors)) {
    echo json_encode(['status' => 'error', 'errors' => $errors]);
    exit;
}

$stmt = $koneksi->prepare("INSERT INTO tb_memo (user_id, subject, message, from_user, type) VALUES (?, ?, ?, ?, 'sent')");
$stmt->bind_param('isss', $user_id, $subject, $message, $username);

if ($stmt->execute()) {
    echo json_encode(['status' => 'success', 'message' => 'Pesan berhasil dikirim.']);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Gagal mengirim pesan.']);
}
?>
