<?php
session_start();
include 'config.php';

if (!isset($_SESSION['logged_in'])) {
    header("Location: login");
    exit;
}

$type = $_POST['type'] ?? '';
$paymentID = $_POST['paymentID'] ?? '';
$email = $_SESSION['SID'] ?? '';
$response = ['valid' => false, 'message' => 'Invalid transaction.', 'status' => ''];

if ($type === 'PAYMENT') {
    // Check if there's already an active complaint with the status 'PENDING'
    $ticketCheckSql = "SELECT status FROM ticketList WHERE accountID = ? AND paymentID = ? AND status = 'PENDING'";
    $stmt = $conn->prepare($ticketCheckSql);
    $stmt->bind_param('ss', $email, $paymentID); // 'ss' means two string parameters
    $stmt->execute();
    $ticketCheckResult = $stmt->get_result();

    if ($ticketCheckResult->num_rows > 0) {
        $response['message'] = "You already have an active complaint with this paymentID, and its status is pending.";
        echo json_encode($response);
        exit;
    }

    $sql = "SELECT status FROM p2cBD WHERE accountID = ? AND paymentID = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ss', $email, $paymentID); 
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        if ($row['status'] === 'REJECTED') {
            $response['valid'] = true;
            $response['status'] = $row['status'];
        } else {
            $response['message'] = "Complaint allowed only for REJECTED payments. Current status: " . $row['status'];
        }
    }
} elseif ($type === 'PAYOUT') {
    $ticketCheckSql = "SELECT status FROM ticketList WHERE accountID = ? AND paymentID = ? AND status = 'PENDING'";
    $stmt = $conn->prepare($ticketCheckSql);
    $stmt->bind_param('ss', $email, $paymentID); 
    $stmt->execute();
    $ticketCheckResult = $stmt->get_result();

    if ($ticketCheckResult->num_rows > 0) {
        $response['message'] = "You already have an active complaint with this paymentID, and its status is pending.";
        echo json_encode($response);
        exit;
    }

    $sql = "SELECT status FROM payoutBD WHERE accountID = ? AND paymentID = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ss', $email, $paymentID);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        if (in_array($row['status'], ['REJECTED', 'PENDING'])) {
            $response['valid'] = true;
            $response['status'] = $row['status'];
        } else {
            $response['message'] = "Complaint allowed only for REJECTED or PENDING payouts. Current status: " . $row['status'];
        }
    }
}

echo json_encode($response);
?>
