<?php
session_start();
require_once 'includes/auth_check.php';
require_once '../config/database.php';
require_once '../includes/functions.php';

// Security checks
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    $_SESSION['error_message'] = 'Invalid request or session expired.';
    header('Location: wire_transactions.php');
    exit;
}

$transfer_id = filter_input(INPUT_POST, 'transfer_id', FILTER_VALIDATE_INT);
$status = $_POST['status'];
$admin_id = $_SESSION['admin_id'];

if (!$transfer_id || !in_array($status, ['approved', 'rejected', 'hold'])) {
    $_SESSION['error_message'] = 'Invalid action.';
    header('Location: wire_transactions.php');
    exit;
}

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

try {
    // Start transaction
    $db->beginTransaction();
    
    // Get the wire transfer details
    $stmt = $db->prepare("
        SELECT wt.*, u.email, u.first_name, u.last_name, u.account_number 
        FROM wire_transfers wt
        JOIN users u ON wt.user_id = u.id
        WHERE wt.id = ?
    ");
    $stmt->execute([$transfer_id]);
    $transfer = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$transfer) {
        throw new Exception("Transfer not found.");
    }

    // Check if the transfer can be updated
    $current_status = strtolower(trim($transfer['status']));
    if ($current_status !== 'pending' && $current_status !== 'hold') {
        throw new Exception("Transfer cannot be updated because it is already " . ucfirst($current_status));
    }

    // Debug log
    error_log("Processing transfer ID: $transfer_id, Current status: $current_status, New status: $status");

    if ($status === 'approved') {
        // Update wire transfer status to 'approved'
        $update_wire = $db->prepare("UPDATE wire_transfers SET status = 'approved', approved_by = ?, approved_at = NOW() WHERE id = ?");
        $update_wire->execute([$admin_id, $transfer_id]);
        
        // Verify the update
        $check = $db->prepare("SELECT status FROM wire_transfers WHERE id = ?");
        $check->execute([$transfer_id]);
        $new_status = $check->fetchColumn();
        error_log("After update, status is: $new_status");

        // Update the corresponding transaction log to 'completed'
        $update_txn = $db->prepare("UPDATE transactions SET status = 'completed' WHERE reference = ?");
        $update_txn->execute([$transfer['reference'] . '_D']);

        $_SESSION['success_message'] = "Wire transfer #{$transfer['reference']} has been approved.";

        // Send email notification for approved transfer
        if (!empty($transfer['email'])) {
            $userName = $transfer['first_name'] . ' ' . $transfer['last_name'];
            
            // Send email notification
            $subject = "Wire Transfer #{$transfer['reference']} Approved";
            $message = "
                <p>Dear {$userName},</p>
                <p>Your wire transfer request has been approved and is now being processed.</p>
                <p><strong>Reference:</strong> {$transfer['reference']}<br>
                <strong>Amount:</strong> {$transfer['currency']} " . number_format($transfer['amount'], 2) . "<br>
                <strong>Recipient:</strong> {$transfer['recipient_name']}<br>
                <strong>Bank:</strong> {$transfer['bank_name']}</p>
                <p>The funds will be sent to the beneficiary shortly.</p>
                <p>Thank you for using our services.</p>
            ";
            
            if (sendEmail($transfer['email'], $subject, $message)) {
                $_SESSION['success_message'] .= " Email notification has been sent to the user.";
            }
        }

    } elseif ($status === 'rejected') {
        $reason = trim($_POST['rejection_reason']);
        if (empty($reason)) {
            throw new Exception("A reason is required for rejection.");
        }

        // Update wire transfer status to 'rejected'
        $update_wire = $db->prepare("UPDATE wire_transfers SET status = 'rejected', rejected_reason = ?, rejected_by = ?, rejected_at = NOW() WHERE id = ?");
        $update_wire->execute([$reason, $admin_id, $transfer_id]);
        
        // Verify the update
        $check = $db->prepare("SELECT status FROM wire_transfers WHERE id = ?");
        $check->execute([$transfer_id]);
        $new_status = $check->fetchColumn();
        error_log("After update, status is: $new_status");

        // Update the corresponding transaction log to 'rejected'
        $update_txn = $db->prepare("UPDATE transactions SET status = 'rejected' WHERE reference = ?");
        $update_txn->execute([$transfer['reference'] . '_D']);

        // **CRITICAL: Refund the money to the user's account**
        $total_refund = $transfer['amount'] + $transfer['fee'];
        $refund_balance = $db->prepare("UPDATE account_balances SET balance = balance + ? WHERE user_id = ?");
        $refund_balance->execute([$total_refund, $transfer['user_id']]);

        // Create a new transaction log for the refund
        $refund_txn = $db->prepare("INSERT INTO transactions (user_id, type, amount, currency, description, reference, status, transaction_type) VALUES (?, 'credit', ?, ?, ?, ?, 'completed', 'refund')");
        $refund_txn->execute([$transfer['user_id'], $total_refund, $transfer['currency'], "Refund for rejected wire #" . $transfer['reference'], 'REFUND_' . $transfer['reference']]);

        $_SESSION['success_message'] = "Wire transfer #{$transfer['reference']} has been rejected and funds returned to the user.";

        // Send email notification for rejected transfer
        if (!empty($transfer['email'])) {
            $userName = $transfer['first_name'] . ' ' . $transfer['last_name'];
            
            // Send email notification
            $subject = "Wire Transfer #{$transfer['reference']} Rejected";
            $message = "
                <p>Dear {$userName},</p>
                <p>Unfortunately, your wire transfer request has been rejected.</p>
                <p><strong>Reference:</strong> {$transfer['reference']}<br>
                <strong>Amount:</strong> {$transfer['currency']} " . number_format($transfer['amount'], 2) . "<br>
                <strong>Recipient:</strong> {$transfer['recipient_name']}<br>
                <strong>Reason for rejection:</strong> {$reason}</p>
                <p>The funds have been returned to your account.</p>
                <p>If you have any questions, please contact our support team.</p>
            ";
            
            if (sendEmail($transfer['email'], $subject, $message)) {
                $_SESSION['success_message'] .= " Email notification has been sent to the user.";
            }
        }
    } elseif ($status === 'hold') {
        $reason = trim($_POST['hold_reason']);
        if (empty($reason)) {
            throw new Exception("A reason is required for placing a transfer on hold.");
        }

        // Update wire transfer status to 'hold'
        $update_wire = $db->prepare("UPDATE wire_transfers SET status = 'hold', hold_by = ? WHERE id = ?");
        $update_wire->execute([$admin_id, $transfer_id]);
        
        // Verify the update
        $check = $db->prepare("SELECT status FROM wire_transfers WHERE id = ?");
        $check->execute([$transfer_id]);
        $new_status = $check->fetchColumn();
        error_log("After update, status is: $new_status");

        // Store the hold reason in a separate note or comment
        try {
            // Check if wire_transfer_notes table exists
            $check_table = $db->query("SHOW TABLES LIKE 'wire_transfer_notes'");
            if ($check_table->rowCount() > 0) {
                // If table exists, add a note
                $note_stmt = $db->prepare("INSERT INTO wire_transfer_notes (transfer_id, admin_id, note_type, note, created_at) VALUES (?, ?, 'hold', ?, NOW())");
                $note_stmt->execute([$transfer_id, $admin_id, $reason]);
            } else {
                // If table doesn't exist, create it and add the note
                $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
                    )
                ");
                $note_stmt = $db->prepare("INSERT INTO wire_transfer_notes (transfer_id, admin_id, note_type, note, created_at) VALUES (?, ?, 'hold', ?, NOW())");
                $note_stmt->execute([$transfer_id, $admin_id, $reason]);
            }
        } catch (Exception $e) {
            // Just log the error but continue with the process
            error_log("Failed to save hold reason: " . $e->getMessage());
        }

        // Update the corresponding transaction log to 'on_hold'
        $update_txn = $db->prepare("UPDATE transactions SET status = 'on_hold' WHERE reference = ?");
        $update_txn->execute([$transfer['reference'] . '_D']);

        $_SESSION['success_message'] = "Wire transfer #{$transfer['reference']} has been placed on hold.";

        // Send email notification for hold transfer
        if (!empty($transfer['email'])) {
            $userName = $transfer['first_name'] . ' ' . $transfer['last_name'];
            
            // Send email notification
            $subject = "Wire Transfer #{$transfer['reference']} On Hold";
            $message = "
                <p>Dear {$userName},</p>
                <p>Your wire transfer request has been temporarily placed on hold for further review.</p>
                <p><strong>Reference:</strong> {$transfer['reference']}<br>
                <strong>Amount:</strong> {$transfer['currency']} " . number_format($transfer['amount'], 2) . "<br>
                <strong>Recipient:</strong> {$transfer['recipient_name']}<br>
                <strong>Reason:</strong> {$reason}</p>
                <p>We will notify you once the review is complete.</p>
                <p>If you have any questions, please contact our support team.</p>
            ";
            
            if (sendEmail($transfer['email'], $subject, $message)) {
                $_SESSION['success_message'] .= " Email notification has been sent to the user.";
            }
        }
    }

    // Commit the transaction
    $db->commit();

} catch (Exception $e) {
    if (isset($db) && $db->inTransaction()) {
        $db->rollBack();
    }
    error_log("Wire Transfer Error: " . $e->getMessage());
    $_SESSION['error_message'] = "An error occurred: " . $e->getMessage();
}

header('Location: wire_transactions.php');
exit;

/**
 * Send an email notification
 */
function sendEmail($to, $subject, $message) {
    // Set content-type header for sending HTML email
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    
    // Additional headers
    $fromName = defined('BANK_NAME') ? BANK_NAME : 'Our Banking Platform';
    $fromEmail = defined('MAIL_FROM_ADDRESS') ? MAIL_FROM_ADDRESS : 'info@oceanbankcooperation.com';
    $headers .= "From: $fromName <$fromEmail>" . "\r\n";
    
    // Try to send email
    try {
        $result = mail($to, $subject, $message, $headers);
        error_log("PHP mail() result: " . ($result ? "Success" : "Failed"));
        return $result;
    } catch (Exception $e) {
        error_log("Error sending email: " . $e->getMessage());
        return false;
    }
}
?>
