<?php
session_start();

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");


require_once 'db/config.php'; // should set $con (mysqli)

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

$user_id    = $_POST['user_id'] ?? '';
$auth       = $_POST['auth'] ?? '';
$message_id = $_POST['id'] ?? '';

if ($user_id == '' || $auth == '' || $message_id == '') {
    echo json_encode([
        'status' => 'error',
        'success' => false,
        'message' => 'Missing required fields'
    ]);
    exit;
}

// Verify user & check package
$stmt = $con->prepare("SELECT package FROM users WHERE user_id = ? AND auth = ? LIMIT 1");
$stmt->bind_param("ss", $user_id, $auth);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if (!$user) {
    echo json_encode([
        'status' => 'error',
        'success' => false,
        'message' => 'Invalid user'
    ]);
    exit;
}

if (strtolower($user['package']) !== 'platinum') {
    echo json_encode([
        'status' => 'error',
        'success' => false,
        'message' => 'Only Platinum users can unsend messages'
    ]);
    exit;
}

// Verify that message belongs to the user
$stmt = $con->prepare("SELECT id FROM messages WHERE id = ? AND sender_id = ? LIMIT 1");
$stmt->bind_param("ss", $message_id, $user_id);
$stmt->execute();
$result = $stmt->get_result();

if (!$result->fetch_assoc()) {
    echo json_encode([
        'status' => 'error',
        'success' => false,
        'message' => 'Message not found or not sent by you'
    ]);
    exit;
}

// Delete message
$stmt = $con->prepare("DELETE FROM messages WHERE id = ? AND sender_id = ? LIMIT 1");
$stmt->bind_param("ss", $message_id, $user_id);

if ($stmt->execute()) {
    echo json_encode([
        'status' => 'success',
        'success' => true,
        'message' => 'Message deleted successfully'
    ]);
} else {
    echo json_encode([
        'status' => 'error',
        'success' => false,
        'message' => 'Failed to delete message'
    ]);
}
?>