<?php
require_once '../includes/init.php';

if (!isAuthenticated()) {
    jsonResponse(false, 'Not authenticated');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Invalid request method');
}

// Handle file upload
$message = sanitizeInput($_POST['message'] ?? '');
$receiverId = intval($_POST['receiver_id'] ?? 0);
$replyTo = intval($_POST['reply_to'] ?? 0);
$selfDestruct = intval($_POST['self_destruct'] ?? 0);
$gifUrl = sanitizeInput($_POST['gif_url'] ?? '');

if (!$receiverId) {
    jsonResponse(false, 'Invalid receiver');
}

$db = getDB();
$senderId = $_SESSION['user_id'];

// Verify receiver exists and is approved
$stmt = $db->prepare("SELECT id FROM users WHERE id = ? AND status = 'approved'");
$stmt->execute([$receiverId]);
if (!$stmt->fetch()) {
    jsonResponse(false, 'User not found or not approved');
}

$fileUrl = null;
$messageType = 'text';

// Handle voice message
if (isset($_FILES['voice_message']) && $_FILES['voice_message']['error'] === UPLOAD_ERR_OK) {
    $file = $_FILES['voice_message'];
    $fileExt = 'webm'; // Voice messages are recorded as webm
    $messageType = 'voice';
    $uploadDir = UPLOAD_PATH . 'voice/';
    
    // Check file size (max 5MB for voice messages)
    if ($file['size'] > 5 * 1024 * 1024) {
        jsonResponse(false, 'Voice message too large');
    }
    
    // Generate unique filename
    $fileName = uniqid() . '_voice_' . bin2hex(random_bytes(8)) . '.' . $fileExt;
    $uploadPath = $uploadDir . $fileName;
    
    if (!move_uploaded_file($file['tmp_name'], $uploadPath)) {
        jsonResponse(false, 'Failed to upload voice message');
    }
    
    $fileUrl = 'uploads/voice/' . $fileName;
}
// Handle GIF from URL
elseif (!empty($gifUrl)) {
    $messageType = 'gif';
    $fileUrl = $gifUrl;
}
// Handle file upload
elseif (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
    $file = $_FILES['attachment'];
    $fileExt = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    
    // Determine file type
    if (in_array($fileExt, ['jpg', 'jpeg', 'png', 'webp'])) {
        $messageType = 'image';
        $uploadDir = UPLOAD_PATH . 'images/';
    } elseif (in_array($fileExt, ['mp4', 'mov'])) {
        $messageType = 'video';
        $uploadDir = UPLOAD_PATH . 'videos/';
    } elseif ($fileExt === 'gif') {
        $messageType = 'gif';
        $uploadDir = UPLOAD_PATH . 'gifs/';
    } else {
        jsonResponse(false, 'Invalid file type');
    }
    
    // Check file size
    if ($file['size'] > MAX_UPLOAD_SIZE) {
        jsonResponse(false, 'File too large');
    }
    
    // Generate unique filename
    $fileName = uniqid() . '_' . bin2hex(random_bytes(8)) . '.' . $fileExt;
    $uploadPath = $uploadDir . $fileName;
    
    if (!move_uploaded_file($file['tmp_name'], $uploadPath)) {
        jsonResponse(false, 'Failed to upload file');
    }
    
    $fileUrl = 'uploads/' . ($messageType === 'image' ? 'images/' : ($messageType === 'video' ? 'videos/' : 'gifs/')) . $fileName;
}

// If no message and no file, return error
if (empty($message) && !$fileUrl) {
    jsonResponse(false, 'Message cannot be empty');
}

// Calculate self-destruct time
$selfDestructAt = null;
if ($selfDestruct > 0) {
    $selfDestructAt = date('Y-m-d H:i:s', time() + ($selfDestruct * 3600));
}

// Insert message
$stmt = $db->prepare("
    INSERT INTO messages (sender_id, receiver_id, reply_to_id, message, message_type, file_url, file_name, file_size, is_self_destruct, self_destruct_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
$stmt->execute([
    $senderId,
    $receiverId,
    $replyTo > 0 ? $replyTo : null,
    $message,
    $messageType,
    $fileUrl,
    $fileUrl ? basename($fileUrl) : null,
    null, // Skip file size for now to avoid errors
    $selfDestruct > 0 ? 1 : 0,
    $selfDestructAt
]);

$messageId = $db->lastInsertId();

// Add initial message status
$stmt = $db->prepare("INSERT INTO message_status (message_id, user_id, status) VALUES (?, ?, 'sent')");
$stmt->execute([$messageId, $receiverId]);

// Log activity
$stmt = $db->prepare("INSERT INTO activity_logs (user_id, action, details, ip_address) VALUES (?, 'send_message', ?, ?)");
$stmt->execute([$senderId, "Sent {$messageType} message to user $receiverId", $_SERVER['REMOTE_ADDR']]);

jsonResponse(true, 'Message sent', [
    'id' => $messageId,
    'message' => $message,
    'message_type' => $messageType,
    'file_url' => $fileUrl,
    'created_at' => date('Y-m-d H:i:s'),
    'self_destruct_at' => $selfDestructAt
]);
?>
