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

// Get transfer ID from query string
$transfer_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$transfer_id) {
    echo "No transfer ID provided";
    exit;
}

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

try {
    // Get the raw status from database
    $stmt = $db->prepare("SELECT id, status, reference FROM wire_transfers WHERE id = ?");
    $stmt->execute([$transfer_id]);
    $transfer = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$transfer) {
        echo "Transfer not found";
        exit;
    }
    
    // Display the raw status
    echo "<h2>Transfer Status Check</h2>";
    echo "<p>Transfer ID: " . $transfer['id'] . "</p>";
    echo "<p>Reference: " . $transfer['reference'] . "</p>";
    echo "<p>Raw Status: '" . $transfer['status'] . "'</p>";
    echo "<p>Status Length: " . strlen($transfer['status']) . " characters</p>";
    echo "<p>Trimmed Status: '" . trim($transfer['status']) . "'</p>";
    echo "<p>Lowercase Status: '" . strtolower($transfer['status']) . "'</p>";
    echo "<p>Normalized Status: '" . strtolower(trim($transfer['status'])) . "'</p>";
    
    // Check if status equals 'hold'
    echo "<p>Status == 'hold': " . ($transfer['status'] == 'hold' ? 'true' : 'false') . "</p>";
    echo "<p>trim(Status) == 'hold': " . (trim($transfer['status']) == 'hold' ? 'true' : 'false') . "</p>";
    echo "<p>strtolower(Status) == 'hold': " . (strtolower($transfer['status']) == 'hold' ? 'true' : 'false') . "</p>";
    echo "<p>strtolower(trim(Status)) == 'hold': " . (strtolower(trim($transfer['status'])) == 'hold' ? 'true' : 'false') . "</p>";
    
    // Display status as hex bytes to check for hidden characters
    echo "<p>Status as hex: ";
    for ($i = 0; $i < strlen($transfer['status']); $i++) {
        echo bin2hex($transfer['status'][$i]) . " ";
    }
    echo "</p>";
    
    // Update form to fix the status
    echo "<h3>Update Status</h3>";
    echo "<form method='post' action='fix_wire_status.php'>";
    echo "<input type='hidden' name='id' value='" . $transfer['id'] . "'>";
    echo "<select name='status'>";
    echo "<option value='pending'" . ($transfer['status'] == 'pending' ? " selected" : "") . ">pending</option>";
    echo "<option value='hold'" . ($transfer['status'] == 'hold' ? " selected" : "") . ">hold</option>";
    echo "<option value='approved'" . ($transfer['status'] == 'approved' ? " selected" : "") . ">approved</option>";
    echo "<option value='rejected'" . ($transfer['status'] == 'rejected' ? " selected" : "") . ">rejected</option>";
    echo "</select>";
    echo "<button type='submit'>Update Status</button>";
    echo "</form>";
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>
