<?php

include_once __DIR__ . '/../secrets.php';
include '../db_connect.php';

$sender   = $_POST['sender_id'];
$receiver = $_POST['receiver_id'];
$time     = $_POST['time'];
$type     = $_POST['type']; // Add Friend | Cancel
$key      = $_POST['key'];

$security_key = decrypData($key);

if ($security_key === false) {
    echo 'Invalid encryption data';
    exit;
}

if ($security_key == SECURITY_KEY_PLAIN) {

    $con = dbConnect();

    // =================================================
    // CANCEL → delete any relation (any direction, any status)
    // =================================================
    if ($type === 'Cancel') {

        $sql = "
            DELETE FROM friends_request
            WHERE 
                (
                    sender_id = '$sender' AND receiver_id = '$receiver'
                )
                OR
                (
                    sender_id = '$receiver' AND receiver_id = '$sender'
                )
        ";

        if (mysqli_query($con, $sql)) {
            echo "cancelled";
        } else {
            echo "error";
        }

        mysqli_close($con);
        exit;
    }

    // =================================================
    // ADD FRIEND
    // =================================================
    if ($type === 'Add Friend') {


        // insert new request
        $sql = "
            INSERT INTO friends_request (sender_id, receiver_id, status, time)
            VALUES ('$sender', '$receiver', 'accepted', '$time')
        ";

        if (mysqli_query($con, $sql)) {
            echo "request_sent";
        } else {
            echo "error";
        }
    }

    mysqli_close($con);
}

?>
