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

// Check admin access
if (!isAuthenticated() || !$_SESSION['is_admin']) {
    redirect(APP_URL . '/login.php');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(APP_URL . '/admin/chats.php');
}

$action = $_POST['action'] ?? '';
$user1 = intval($_POST['user1'] ?? 0);
$user2 = intval($_POST['user2'] ?? 0);

if (!$user1 || !$user2) {
    redirect(APP_URL . '/admin/chats.php?error=invalid_users');
}

$db = getDB();

if ($action === 'delete_conversation') {
    // Soft delete all messages between these users
    $stmt = $db->prepare("
        UPDATE messages 
        SET is_deleted_for_all = 1, deleted_at = NOW()
        WHERE ((sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?))
    ");
    $stmt->execute([$user1, $user2, $user2, $user1]);
    
    // Log activity
    $stmt = $db->prepare("INSERT INTO activity_logs (user_id, action, details, ip_address) VALUES (?, 'delete_conversation', 'Deleted conversation between users $user1 and $user2', ?)");
    $stmt->execute([$_SESSION['user_id'], $_SERVER['REMOTE_ADDR']]);
    
    redirect(APP_URL . '/admin/chats.php?message=Conversation deleted');
}

redirect(APP_URL . '/admin/chats.php');
?>
