<?php
session_start();
include('../../../includes/config.php');

$is_ajax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
           strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';

header('Content-Type: ' . ($is_ajax ? 'application/json' : 'text/html'));

if (!isset($_SESSION['user_id'])) {
    $msg = 'Unauthorized access.';
    echo $is_ajax ? json_encode(['success' => false, 'message' => $msg]) : $msg;
    exit;
}

$sender_id   = $_SESSION['user_id'];
$receiver_id = isset($_POST['receiver_id']) ? (int)$_POST['receiver_id'] : null;
$subject     = trim($_POST['subject'] ?? '');
$body        = trim($_POST['body'] ?? '');
$parent_id   = isset($_POST['parent_id']) ? (int)$_POST['parent_id'] : null;

$thread_id   = null; // for threading
$attachment  = null;

// Validate inputs
if (!$receiver_id || empty($subject) || empty($body)) {
    $msg = 'All fields are required.';
    echo $is_ajax ? json_encode(['success' => false, 'message' => $msg]) : $msg;
    exit;
}

// === File Upload Handling ===
$upload_dir = '../../../uploads/messages/';
$allowed_exts = ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'txt', 'zip'];
$max_file_size = 5 * 1024 * 1024; // 5MB

if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

if (!empty($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
    $tmp  = $_FILES['attachment']['tmp_name'];
    $name = basename($_FILES['attachment']['name']);
    $size = $_FILES['attachment']['size'];
    $ext  = strtolower(pathinfo($name, PATHINFO_EXTENSION));

    if (!in_array($ext, $allowed_exts)) {
        $msg = 'Unsupported file type.';
        echo $is_ajax ? json_encode(['success' => false, 'message' => $msg]) : $msg;
        exit;
    }

    if ($size > $max_file_size) {
        $msg = 'File size exceeds 5MB.';
        echo $is_ajax ? json_encode(['success' => false, 'message' => $msg]) : $msg;
        exit;
    }

    $new_name = uniqid('msg_', true) . '.' . $ext;
    $path = $upload_dir . $new_name;

    if (!move_uploaded_file($tmp, $path)) {
        $msg = 'File upload failed.';
        echo $is_ajax ? json_encode(['success' => false, 'message' => $msg]) : $msg;
        exit;
    }

    $attachment = $new_name;
}

// === If replying, set thread_id ===
$reply_to = null;
if ($parent_id) {
    $stmt = $conn->prepare("SELECT id, thread_id FROM messages WHERE id = ?");
    $stmt->bind_param("i", $parent_id);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($msgRow = $res->fetch_assoc()) {
        $reply_to = $parent_id;
        $thread_id = $msgRow['thread_id'] ?: $msgRow['id'];
    } else {
        $msg = 'Invalid reply reference.';
        echo $is_ajax ? json_encode(['success' => false, 'message' => $msg]) : $msg;
        exit;
    }
    $stmt->close();
}

// === Insert Message ===
$stmt = $conn->prepare("
    INSERT INTO messages (sender_id, receiver_id, subject, body, attachment, reply_to, thread_id, created_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
");

if (!$stmt) {
    $msg = 'Database error: ' . $conn->error;
    echo $is_ajax ? json_encode(['success' => false, 'message' => $msg]) : $msg;
    exit;
}

$stmt->bind_param(
    "iisssii",
    $sender_id,
    $receiver_id,
    $subject,
    $body,
    $attachment,
    $reply_to,
    $thread_id
);

if ($stmt->execute()) {
    $new_message_id = $stmt->insert_id;

    // For new threads (no parent), update thread_id to own id
    if (!$thread_id) {
        $update = $conn->prepare("UPDATE messages SET thread_id = ? WHERE id = ?");
        $update->bind_param("ii", $new_message_id, $new_message_id);
        $update->execute();
        $update->close();
    }

    $stmt->close();
    $conn->close();

    if ($is_ajax) {
        echo json_encode(['success' => true, 'message' => 'Message sent.']);
    } else {
        $redirect = $_POST['redirect'] ?? 'inbox.php?sent=1';
        header("Location: $redirect");
        exit;
    }
} else {
    $msg = 'Failed to send message: ' . $stmt->error;
    echo $is_ajax ? json_encode(['success' => false, 'message' => $msg]) : $msg;
    $stmt->close();
    $conn->close();
}
