<?php
session_start();

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

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

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

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

    $sender_id     = mysqli_escape_string($con, $sender_id);
    $recipient_id  = mysqli_escape_string($con, $recipient_id);
    $message       = mysqli_escape_string($con, $message);
    $auth          = mysqli_escape_string($con, $auth);

    // Check if sender exists & get their package
    $sql = "SELECT * FROM users WHERE user_id = '$sender_id' AND auth = '$auth'";
    $result = $con->query($sql) or die("error: Server error " . mysqli_error($con));
    if (mysqli_num_rows($result) == 0) {
        echo json_encode(['status' => false, 'success' => 'User Does Not Exist']);
        exit;
    }
    $sender_row = mysqli_fetch_assoc($result);
    $sender_package = $sender_row['package']; // Assuming column name is 'package'
    $sender_name = $sender_row['firstname'] . " " . $sender_row['lastname'];
    
    
    
    
    $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
");

if (mysqli_num_rows($blockCheck) > 0) {

    $blockRow = mysqli_fetch_assoc($blockCheck);

    if ($blockRow['user_id'] == $sender_id) {

        echo json_encode([
            'status' => false,
            'success' => 'You have blocked this user'
        ]);

    } else {

        echo json_encode([
            'status' => false,
            'success' => 'This user has blocked you'
        ]);

    }

    exit;
}




    // Restriction for Free package
    if ($sender_package === 'Free') {
        echo json_encode(['status' => false, 'success' => 'Free users cannot send messages']);
        exit;
    }

    // If Gold package, check if they are matched
    if (strtoupper($sender_package) === 'Gold') {
        $match_sql = "SELECT * FROM matches 
                      WHERE ((user_id = '$sender_id' AND match_id = '$recipient_id') 
                      OR (user_id = '$recipient_id' AND match_id = '$sender_id'))
                      AND status = 'Matched'";
        $match_result = $con->query($match_sql) or die("error: Match check error " . mysqli_error($con));
        if (mysqli_num_rows($match_result) == 0) {
            echo json_encode(['status' => false, 'success' => 'You must be matched with this user to send messages']);
            exit;
        }
    }

    // Get recipient details
    $sql = "SELECT * FROM users WHERE user_id = '$recipient_id'";
    $recipient_res = $con->query($sql) or die("error: Server error " . mysqli_error($con));
    if (mysqli_num_rows($recipient_res) == 0) {
        echo json_encode(['status' => false, 'success' => 'Recipient Does Not Exist']);
        exit;
    }
    $recipient_row = mysqli_fetch_assoc($recipient_res);
    $recipient_name = $recipient_row['firstname'] . " " . $recipient_row['lastname'];


// Check if conversation already exists between both users
$checkMsg = $con->query("
    SELECT msg_id FROM messages 
    WHERE 
        (sender_id = '$sender_id' AND recipient_id = '$recipient_id')
        OR 
        (sender_id = '$recipient_id' AND recipient_id = '$sender_id')
    ORDER BY id ASC LIMIT 1
");

if ($checkMsg && mysqli_num_rows($checkMsg) > 0) {
    // ✅ Use existing msg_id
    $row = mysqli_fetch_assoc($checkMsg);
    $msg_id = $row['msg_id'];
} else {
    // ❌ No conversation → generate new msg_id
    function check_number($con) {
        $unique_number = rand(1000000000, 9999999999);
        $sqlx = $con->query("SELECT * FROM messages WHERE msg_id = '$unique_number'");
        if (mysqli_num_rows($sqlx) > 0) {
            return check_number($con);
        }
        return $unique_number;
    }
    $msg_id = check_number($con);
}
 
 
 
    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
    $sql2 = $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));

    echo json_encode([
        'status' => true,
        'success' => 'Successful',
        'msg_id' => $msg_id,
        'message' => $message,
        'sender' => $sender_name,
        'sender_id' => $sender_id,
        'recipient' => $recipient_name,
        'recipient_id' => $recipient_id
    ]);
}






/*session_start();

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

if (isset($_POST['sender_id']) && isset($_POST['recipient_id'])) {

    require 'db/config.php';

    function clean($data) {
        return htmlspecialchars(stripslashes(trim($data)));
    }

    $sender_id    = mysqli_real_escape_string($con, clean($_POST['sender_id']));
    $recipient_id = mysqli_real_escape_string($con, clean($_POST['recipient_id']));
    $message      = mysqli_real_escape_string($con, clean($_POST['message']));
    $auth         = mysqli_real_escape_string($con, clean($_POST['auth']));

    // ✅ Validate sender
    $sql = "SELECT * FROM users WHERE user_id = '$sender_id' AND auth = '$auth'";
    $result = $con->query($sql);

    if ($result->num_rows === 0) {
        echo json_encode(['status' => false, 'success' => 'User does not exist']);
        exit;
    }

    $sender_row = $result->fetch_assoc();
    $sender_package = $sender_row['package'];
    $sender_name = $sender_row['firstname'] . " " . $sender_row['lastname'];

    // ❌ Free restriction
    if ($sender_package === 'Free') {
        echo json_encode(['status' => false, 'success' => 'Free users cannot send messages']);
        exit;
    }

    // ✅ Gold match check
    if (strtoupper($sender_package) === 'GOLD') {
        $match_sql = "SELECT * FROM matches 
                      WHERE ((user_id = '$sender_id' AND match_id = '$recipient_id') 
                      OR (user_id = '$recipient_id' AND match_id = '$sender_id'))
                      AND status = 'Matched'";
        $match_result = $con->query($match_sql);

        if ($match_result->num_rows === 0) {
            echo json_encode(['status' => false, 'success' => 'You must be matched to chat']);
            exit;
        }
    }

    // ✅ Validate recipient
    $sql = "SELECT * FROM users WHERE user_id = '$recipient_id'";
    $recipient_res = $con->query($sql);

    if ($recipient_res->num_rows === 0) {
        echo json_encode(['status' => false, 'success' => 'Recipient does not exist']);
        exit;
    }

    $recipient_row = $recipient_res->fetch_assoc();
    $recipient_name = $recipient_row['firstname'] . " " . $recipient_row['lastname'];

    // ✅ Time (keep Lagos as you prefer)
    date_default_timezone_set("Africa/Lagos");
    $date_t  = date("d-M-Y");
    $time_t  = date("H:i");
    $date_t2 = date("d-m-Y");

    // ✅ Insert WITHOUT msg_id
    $sql2 = $con->query("
        INSERT INTO messages 
        (sender, sender_id, recipient, recipient_id, message, date_t, time_t, date_t2, status)
        VALUES 
        ('$sender_name', '$sender_id', '$recipient_name', '$recipient_id', '$message', '$date_t', '$time_t', '$date_t2', 'New')
    ");

    if (!$sql2) {
        echo json_encode(['status' => false, 'success' => 'Failed to send message']);
        exit;
    }

    echo json_encode([
        'status' => true,
        'success' => 'Message sent',
        'message' => $message,
        'sender' => $sender_name,
        'sender_id' => $sender_id,
        'recipient' => $recipient_name,
        'recipient_id' => $recipient_id
    ]);
}*/
?>