<?php
require_once 'includes/auth_check.php';
require_once '../config/database.php';

$transfer_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$transfer_id) {
    die("Please provide a valid transfer ID in the URL: check_wire_status.php?id=123");
}

$database = new Database();
$db = $database->getConnection();

try {
    // Get raw status from database
    $stmt = $db->prepare("SELECT id, status, BINARY status as binary_status FROM wire_transfers WHERE id = ?");
    $stmt->execute([$transfer_id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$result) {
        die("Transfer not found with ID: $transfer_id");
    }
    
    echo "<h2>Wire Transfer Status Check</h2>";
    echo "<p>Transfer ID: " . $result['id'] . "</p>";
    echo "<p>Raw Status: '" . $result['status'] . "'</p>";
    echo "<p>Status Length: " . strlen($result['status']) . " characters</p>";
    echo "<p>Binary Status (hex): " . bin2hex($result['binary_status']) . "</p>";
    echo "<p>ASCII Values: ";
    
    for ($i = 0; $i < strlen($result['status']); $i++) {
        echo ord($result['status'][$i]) . " ";
    }
    echo "</p>";
    
    // Try to update the status directly
    echo "<h3>Fix Status</h3>";
    echo "<p>Attempting to set status to 'hold'...</p>";
    $update = $db->prepare("UPDATE wire_transfers SET status = 'hold' WHERE id = ?");
    $result = $update->execute([$transfer_id]);
    
    if ($result) {
        echo "<p style='color: green;'>Status updated successfully to 'hold'</p>";
    } else {
        echo "<p style='color: red;'>Failed to update status</p>";
    }
    
    // Check the status again after update
    $stmt = $db->prepare("SELECT id, status, BINARY status as binary_status FROM wire_transfers WHERE id = ?");
    $stmt->execute([$transfer_id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    echo "<p>New Raw Status: '" . $result['status'] . "'</p>";
    echo "<p>New Status Length: " . strlen($result['status']) . " characters</p>";
    echo "<p>New Binary Status (hex): " . bin2hex($result['binary_status']) . "</p>";
    
    echo "<h3>Actions</h3>";
    echo "<p><a href='view_wire_transfer.php?id=$transfer_id'>Go back to view transfer</a></p>";
    
} catch (PDOException $e) {
    echo "<p style='color: red;'>Database Error: " . $e->getMessage() . "</p>";
}
?>