<?php
session_start();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json; charset=utf-8');

include 'db/config.php';

// Helper function
function check_input($par) {
    return htmlspecialchars(stripslashes(trim($par)));
}

// Validate input
if (empty($_POST['user_id']) || empty($_POST['auth']) || empty($_POST['match_id'])) {
    echo json_encode(['status' => false, 'success' => 'Missing required parameters']);
    exit;
}

$user_id  = check_input($_POST['user_id']);
$auth     = check_input($_POST['auth']);
$match_id = check_input($_POST['match_id']);
$date_t   = date("Y-m-d H:i:s");


if ($user_id === $match_id) {
    echo json_encode(['status' => false, 'success' => 'You cannot unmatch yourself']);
    exit;
}

// Authenticate user
$stmt = $con->prepare("SELECT user_id, img FROM users WHERE user_id = ? AND auth = ?");
$stmt->bind_param("ss", $user_id, $auth);
$stmt->execute();
$userRes = $stmt->get_result();

if ($userRes->num_rows !== 1) {
    echo json_encode(['status' => false, 'success' => 'Invalid user ID or authentication token']);
    exit;
}
$userData = $userRes->fetch_assoc();

// Check if match exists
$stmt = $con->prepare("SELECT * FROM matches WHERE 
    (user_id = ? AND match_id = ?) OR (user_id = ? AND match_id = ?)");
$stmt->bind_param("ssss", $user_id, $match_id, $match_id, $user_id);
$stmt->execute();
$matchRes = $stmt->get_result();

if ($matchRes->num_rows === 0) {
    echo json_encode(['status' => false, 'success' => 'No match found to unmatch']);
    exit;
}

$con->begin_transaction();

try {
    // Delete match both ways
    $delStmt = $con->prepare("DELETE FROM matches WHERE 
        (user_id = ? AND match_id = ?) OR (user_id = ? AND match_id = ?)");
    $delStmt->bind_param("ssss", $user_id, $match_id, $match_id, $user_id);
    $delStmt->execute();

    // Optionally log activity
    $details = "You unmatched with user ID {$match_id}";
    $actStmt = $con->prepare("INSERT INTO activities (user_id, title, img, details, date_t) VALUES (?, 'Unmatch', ?, ?, ?)");
    $actStmt->bind_param("ssss", $user_id, $userData['img'], $details, $date_t);
    $actStmt->execute();

    $con->commit();
    echo json_encode(['status' => true, 'success' => 'Unmatched successfully']);
} catch (Exception $e) {
    $con->rollback();
    echo json_encode(['status' => false, 'success' => 'Error: ' . $e->getMessage()]);
}

$con->close();
?>
