<?php
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);
session_start();
include 'config.php';

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

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $email = $_SESSION['SID'];
    $pay_mode = $_POST['pay_mode'] ?? '';
    $paymentID = $_POST['paymentID'] ?? '';
    $wallet = $_POST['wallet'] ?? '';
    $txid = $_POST['txid'] ?? '';
    $description = $_POST['description'] ?? '';
    $proof = $_FILES['proof'] ?? null;

    if (!$pay_mode || !$paymentID || !$wallet || !$description) {
        die("❌ All required fields must be filled.");
    }

    $table = ($pay_mode === 'PAYMENT') ? 'p2cBD' : 'payoutBD';
    $statusCondition = ($pay_mode === 'PAYMENT')
    ? "status = 'REJECTED'"
    : "status IN ('REJECTED','PENDING')";


    $ticketCheckSql = $conn->prepare("SELECT * 
                                      FROM ticketList 
                                      WHERE paymentID = ? AND accountID = ? AND status IN ('RESOLVED', 'PENDING')");
    $ticketCheckSql->bind_param("ss", $paymentID, $email);
    $ticketCheckSql->execute();
    $ticketCheckResult = $ticketCheckSql->get_result();

    if ($ticketCheckResult->num_rows > 0) {
        die("❌ You have already submitted a complaint for this payment ID. Please check the status or try again later.");
    }

    $stmt = $conn->prepare("SELECT accountID, email, channel, vendor_acid, vendor_email, amount 
                            FROM $table 
                            WHERE paymentID = ? AND accountID = ? AND $statusCondition");
    $stmt->bind_param("ss", $paymentID, $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        die("❌ Invalid payment ID or unauthorized access.");
    }

    $data = $result->fetch_assoc();

    $imgPath = '';
    if ($proof && $proof['name']) {
        $allowedTypes = ['image/jpeg', 'image/png', 'image/jpg'];
        if (!in_array($proof['type'], $allowedTypes)) {
            die("❌ Only JPG and PNG images are allowed.");
        }

        $uploadDir = 'uploads/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

        $newName = uniqid('proof_', true) . '.' . pathinfo($proof['name'], PATHINFO_EXTENSION);
        $imgPath = $uploadDir . $newName;

        if (!move_uploaded_file($proof['tmp_name'], $imgPath)) {
            die("❌ Failed to upload file.");
        }
    }

    // ✅ Prepare values for insertion
    $amount = $data['amount'];
    $accountID = $data['accountID'];
    $emailID = $data['email'];
    $channel = $data['channel'];
    $vendor_acid = $data['vendor_acid'];
    $vendor_email = $data['vendor_email'];
    $complaintID = 'CMP-' . strtoupper(bin2hex(random_bytes(4))); // e.g. CMP-5A1B3C9D
    $rcv_amount = "0";
    // ✅ Insert securely into ticketList
    $insert = $conn->prepare("INSERT INTO ticketList 
        (complaintID, accountID, email, channel, vendor_acid, vendor_email, amount,rcv_amount, pay_mode, paymentID, wallet, txid, description, img, status) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING')");

    $insert->bind_param(
        "ssssssddssssss",
        $complaintID,
        $accountID,
        $emailID,
        $channel,
        $vendor_acid,
        $vendor_email,
        $amount,
        $rcv_amount,
        $pay_mode,
        $paymentID,
        $wallet,
        $txid,
        $description,
        $imgPath
    );

    if ($insert->execute()) {
        if($pay_mode == "PAYMENT"){
              $update = $conn->prepare("UPDATE p2cBD 
            SET push = 1 
            WHERE paymentID = ? AND status = 'REJECTED'");

        $update->bind_param("s", $paymentID);
        $update->execute();  
        }
 echo "✅ Complaint submitted successfully! Complaint ID: <strong>$complaintID</strong>".'<a href="complaints_history" style="display: inline-block; margin-bottom: 15px; color: #007bff; text-decoration: none; font-weight: bold;">
    ← Return to Home
</a>';
    } else {
        echo "❌ Error submitting complaint: " . $conn->error. '<a href="complaints_history" style="display: inline-block; margin-bottom: 15px; color: #007bff; text-decoration: none; font-weight: bold;">
    ← Return to Home
</a>';
    }
}
?>
