<?php
session_start();

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

$status = false;
$suc = "";
$sender_name = "";
$recipient_name = "";

if(isset($_POST['sender_id']) && isset($_POST['recipient_id']) && isset($_POST['msg_id']))
{
    require 'db/config.php';

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

    $msg_id       = check_input($_POST['msg_id']);
    $sender_id    = check_input($_POST['sender_id']);
    $recipient_id = check_input($_POST['recipient_id']);
    $message      = check_input($_POST['message']);
    $auth         = check_input($_POST['auth']);

    $msg_id       = mysqli_real_escape_string($con, $msg_id);
    $sender_id    = mysqli_real_escape_string($con, $sender_id);
    $recipient_id = mysqli_real_escape_string($con, $recipient_id);
    $message      = mysqli_real_escape_string($con, $message);
    $auth         = mysqli_real_escape_string($con, $auth);

    // Verify sender
    $sql = "SELECT * FROM users WHERE user_id = '$sender_id' AND auth = '$auth'";
    $result = $con->query($sql) or die("error: Server error ".mysqli_error($con));
    $count = mysqli_num_rows($result);

    if ($count == 0)
    {
        $suc = "User Does Not Exist";
        $status = false;
    }
    else
    {
        // Check if either user has blocked the other
        $blockCheck = $con->query("
            SELECT *
            FROM blocked_users
            WHERE
                (user_id = '$sender_id' AND blocked_user_id = '$recipient_id')
                OR
                (user_id = '$recipient_id' AND blocked_user_id = '$sender_id')
            LIMIT 1
        ") or die("error: ".mysqli_error($con));

        if(mysqli_num_rows($blockCheck) > 0)
        {
            $blockRow = mysqli_fetch_assoc($blockCheck);

            if($blockRow['user_id'] == $sender_id)
            {
                $suc = "You have blocked this user";
            }
            else
            {
                $suc = "This user has blocked you";
            }

            $status = false;

            echo json_encode([
                'status' => false,
                'success' => $suc
            ]);
            exit;
        }

        // Get sender details
        $sql1 = "SELECT * FROM users WHERE user_id='$sender_id'";
        $result1 = $con->query($sql1) or die("error: Server error ".mysqli_error($con));

        if(mysqli_num_rows($result1) == 1)
        {
            $rows = mysqli_fetch_assoc($result1);
            $sender_name = $rows['firstname']." ".$rows['lastname'];
        }

        // Get recipient details
        $sql2 = "SELECT * FROM users WHERE user_id='$recipient_id'";
        $result2 = $con->query($sql2) or die("error: Server error ".mysqli_error($con));

        if(mysqli_num_rows($result2) == 1)
        {
            $rowsx = mysqli_fetch_assoc($result2);
            $recipient_name = $rowsx['firstname']." ".$rowsx['lastname'];
        }
        else
        {
            echo json_encode([
                'status' => false,
                'success' => 'Recipient Does Not Exist'
            ]);
            exit;
        }

        // Optional: prevent platform-blocked users from messaging
        if(isset($rows['status']) && $rows['status'] == 'Blocked')
        {
            echo json_encode([
                'status' => false,
                'success' => 'Your account has been blocked'
            ]);
            exit;
        }

        if(isset($rowsx['status']) && $rowsx['status'] == 'Blocked')
        {
            echo json_encode([
                'status' => false,
                'success' => 'This user is unavailable'
            ]);
            exit;
        }

        date_default_timezone_set("Africa/Lagos");

        $date_t  = date("d-M-Y");
        $time_t  = date("H:i");
        $date_t2 = date("d-m-Y");

        // Insert message
        $sqlx = $con->query("
            INSERT INTO messages
            (msg_id, sender, sender_id, recipient, recipient_id, message, date_t, time_t, date_t2, status)
            VALUES
            (
                '$msg_id',
                '$sender_name',
                '$sender_id',
                '$recipient_name',
                '$recipient_id',
                '$message',
                '$date_t',
                '$time_t',
                '$date_t2',
                'New'
            )
        ") or die("Error: ".mysqli_error($con));

        $suc = "Successful";
        $status = true;
    }
}
else
{
    $suc = "Required fields missing";
    $status = false;
}

$output = array(
    'status' => $status,
    'success' => $suc,
    'msg_id' => $msg_id ?? '',
    'message' => $message ?? '',
    'sender' => $sender_name,
    'sender_id' => $sender_id ?? '',
    'recipient' => $recipient_name,
    'recipient_id' => $recipient_id ?? ''
);

echo json_encode($output);
?>