<?php
// hold_wire.php - A simple script to put a wire transfer on hold
require_once 'includes/auth_check.php';
require_once '../config/database.php';

// Check if this is a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo "This script only accepts POST requests";
    exit;
}

// Get parameters
$transfer_id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$reason = isset($_POST['reason']) ? trim($_POST['reason']) : '';

if (!$transfer_id || empty($reason)) {
    echo "Missing required parameters";
    exit;
}

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

try {
    // Start transaction
    $db->beginTransaction();
    
    // Get current status
    $stmt = $db->prepare("SELECT status FROM wire_transfers WHERE id = ?");
    $stmt->execute([$transfer_id]);
    $current_status = $stmt->fetchColumn();
    
    echo "Current status: '$current_status'<br>";
    
    if (strtolower(trim($current_status)) !== 'pending') {
        echo "Transfer must be in 'pending' status to be put on hold";
        exit;
    }
    
    // Update status to 'hold'
    $stmt = $db->prepare("UPDATE wire_transfers SET status = 'hold' WHERE id = ?");
    $stmt->execute([$transfer_id]);
    
    echo "Updated status to 'hold'<br>";
    
    // Create notes table if it doesn't exist
    $db->exec("
        CREATE TABLE IF NOT EXISTS wire_transfer_notes (
            id INT AUTO_INCREMENT PRIMARY KEY,
            transfer_id INT NOT NULL,
            admin_id INT NOT NULL,
            note_type VARCHAR(50) NOT NULL,
            note TEXT NOT NULL,
            created_at DATETIME NOT NULL
        )
    ");
    
    // Store the reason
    $stmt = $db->prepare("INSERT INTO wire_transfer_notes (transfer_id, admin_id, note_type, note, created_at) VALUES (?, ?, 'hold', ?, NOW())");
    $stmt->execute([$transfer_id, $_SESSION['admin_id'], $reason]);
    
    echo "Added note with reason<br>";
    
    // Commit transaction
    $db->commit();
    
    echo "Transaction committed<br>";
    echo "Transfer successfully put on hold.<br>";
    echo "<a href='wire_status_check.php?id=$transfer_id'>Check Status</a><br>";
    echo "<a href='wire_transactions.php'>Back to Wire Transactions</a>";
    
} catch (Exception $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    echo "Error: " . $e->getMessage();
}
?>
