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

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../classes/Messaging.php';

define('CHAT_UPLOAD_DIR', __DIR__ . '/../uploads/messages/');

define('CHAT_EXTENSION_BY_MIME', [
    'image/jpeg' => 'jpg',
    'image/png' => 'png',
    'image/gif' => 'gif',
    'image/webp' => 'webp',
    'application/pdf' => 'pdf',
    'application/msword' => 'doc',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
    'application/vnd.ms-excel' => 'xls',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
    'audio/webm' => 'webm',
    'audio/ogg' => 'ogg',
    'audio/mp4' => 'm4a',
    'audio/mpeg' => 'mp3',
]);

try {
    session_start();
    if (empty($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'Login required.']);
        exit;
    }

    $userId = (int)$_SESSION['user_id'];
    $conversationId = (int)($_POST['conversation_id'] ?? 0);
    $body = trim((string)($_POST['body'] ?? ''));
    $kind = ($_POST['kind'] ?? 'file') === 'voice' ? 'voice' : 'file';

    $database = new Database();
    $conn = $database->getConnection();

    $messaging = new Messaging($conn);
    if (!$conversationId || !$messaging->isParticipant($conversationId, $userId)) {
        echo json_encode(['success' => false, 'message' => 'Conversation not found.']);
        exit;
    }

    if (empty($_FILES['attachment']) || $_FILES['attachment']['error'] === UPLOAD_ERR_NO_FILE) {
        echo json_encode(['success' => false, 'message' => 'No file was uploaded.']);
        exit;
    }

    $file = $_FILES['attachment'];
    if ($file['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['success' => false, 'message' => 'Upload failed (error code ' . $file['error'] . ').']);
        exit;
    }

    if ($file['size'] > MAX_FILE_SIZE) {
        echo json_encode(['success' => false, 'message' => 'File exceeds the ' . (MAX_FILE_SIZE / 1024 / 1024) . 'MB limit.']);
        exit;
    }

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    $allowedTypes = $kind === 'voice' ? CHAT_ALLOWED_VOICE_TYPES : ALLOWED_FILE_TYPES;
    if (!in_array($mimeType, $allowedTypes, true) || !isset(CHAT_EXTENSION_BY_MIME[$mimeType])) {
        echo json_encode(['success' => false, 'message' => 'File type not allowed.']);
        exit;
    }

    if (!is_dir(CHAT_UPLOAD_DIR)) {
        mkdir(CHAT_UPLOAD_DIR, 0755, true);
    }

    $extension = CHAT_EXTENSION_BY_MIME[$mimeType];
    $storedName = bin2hex(random_bytes(16)) . '.' . $extension;
    $destination = CHAT_UPLOAD_DIR . $storedName;

    if (!move_uploaded_file($file['tmp_name'], $destination)) {
        echo json_encode(['success' => false, 'message' => 'Unable to save uploaded file.']);
        exit;
    }

    $originalName = $kind === 'voice'
        ? ('Voice message.' . $extension)
        : basename($file['name']);

    $message = $messaging->sendMessage($conversationId, $userId, $body, [
        'path' => $storedName,
        'name' => $originalName,
        'type' => $mimeType,
        'size' => $file['size'],
        'kind' => $kind,
    ]);

    echo json_encode(['success' => true, 'message_data' => $message]);
} catch (InvalidArgumentException $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
} catch (Throwable $e) {
    error_log('Chat attachment upload failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Unable to upload attachment.']);
}
