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

// Enable error logging
ini_set('display_errors', 0);
error_reporting(E_ALL);
error_log("Wire action processing started");

// Function to send transaction notification email - copied from your working code
function sendTransactionEmail($to, $name, $type, $amount, $currency, $reference, $description, $newBalance = null, $date = null) {
    $bankName = defined('BANK_NAME') ? BANK_NAME : 'Our Banking Platform';
    $bankLogo = defined('BANK_LOGO_URL') ? BANK_LOGO_URL : 'https://online.firstnationalbankinc.com/logo.png';
    $bankColor = defined('BANK_PRIMARY_COLOR') ? BANK_PRIMARY_COLOR : '#0066cc';
    $currentYear = date('Y');
    
    // Determine if it's a credit or debit for styling and wording
    $isCredit = ($type == 'credit' || $type == 'approved');
    $transactionColor = $isCredit ? '#28a745' : '#dc3545';
    $transactionIcon = $isCredit ? '↑' : '↓';
    $transactionType = $type;
    
    // Capitalize first letter of transaction type
    $transactionType = ucfirst($transactionType);
    
    if (!$date) {
        $date = date('F j, Y, g:i a');
    }
    
    $subject = "Wire Transfer $transactionType - $currency $amount";
    
    $message = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wire Transfer $transactionType</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333333;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }
        .email-container {
            max-width: 600px;
            margin: 0 auto;
            background-color: #ffffff;
            border: 1px solid #dddddd;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .email-header {
            background-color: $bankColor;
            padding: 20px;
            text-align: center;
        }
        .email-header img {
            max-width: 200px;
            height: auto;
        }
        .email-body {
            padding: 20px 30px;
        }
        .email-footer {
            background-color: #f8f8f8;
            padding: 15px;
            text-align: center;
            font-size: 12px;
            color: #666666;
            border-top: 1px solid #dddddd;
        }
        h1 {
            color: $bankColor;
            margin-top: 0;
        }
        .transaction-details {
            background-color: #f9f9f9;
            border-left: 4px solid $transactionColor;
            padding: 15px;
            margin: 20px 0;
        }
        .transaction-amount {
            font-size: 24px;
            font-weight: bold;
            color: $transactionColor;
            margin: 10px 0;
        }
        .transaction-icon {
            font-size: 20px;
            margin-right: 5px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 10px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
            width: 40%;
        }
        .help-text {
            background-color: #e8f4fd;
            border-left: 4px solid #0066cc;
            padding: 15px;
            margin: 20px 0;
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="email-header">
            <img src="$bankLogo" alt="$bankName Logo">
        </div>
        <div class="email-body">
            <h1>Wire Transfer $transactionType</h1>
            <p>Dear $name,</p>
            <p>This is to inform you that your wire transfer has been $transactionType.</p>
            
            <div class="transaction-amount">
                <span class="transaction-icon">$transactionIcon</span>
                $currency $amount
            </div>
            
            <div class="transaction-details">
                <h2>Transaction Details</h2>
                <table>
                    <tr>
                        <th>Status</th>
                        <td>$transactionType</td>
                    </tr>
                    <tr>
                        <th>Amount</th>
                        <td>$currency $amount</td>
                    </tr>
                    <tr>
                        <th>Reference</th>
                        <td>$reference</td>
                    </tr>
                    <tr>
                        <th>Description</th>
                        <td>$description</td>
                    </tr>
                    <tr>
                        <th>Date & Time</th>
                        <td>$date</td>
                    </tr>
HTML;

    if ($newBalance !== null) {
        $message .= <<<HTML
                    <tr>
                        <th>Current Balance</th>
                        <td>$currency $newBalance</td>
                    </tr>
HTML;
    }

    $message .= <<<HTML
                </table>
            </div>
            
            <div class="help-text">
                <p>If you did not authorize this transaction or have any questions, please contact our customer support team immediately.</p>
            </div>
            
            <p>Thank you for banking with us.</p>
            
            <p>Best regards,<br>The $bankName Team</p>
        </div>
        <div class="email-footer">
            <p>This is an automated message. Please do not reply to this email.</p>
            <p>© $currentYear $bankName. All rights reserved.</p>
            <p>For security reasons, please ensure that you keep your account details confidential.</p>
        </div>
    </div>
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
HTML;

    // 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";
    
    // Use specific sender information instead of relying on constants
    $fromName = defined('MAIL_FROM_NAME') ? MAIL_FROM_NAME : 'First National Bank Incorporated';
    $fromEmail = defined('MAIL_FROM_ADDRESS') ? MAIL_FROM_ADDRESS : 'noreply@yourdomain.com';
    $headers .= "From: $fromName <$fromEmail>" . "\r\n";
    
    // Log email attempt for debugging
    error_log("Attempting to send email to: $to, Subject: $subject");
    
    // Try to send email
    try {
        // Direct mail function - simplest approach
        $result = mail($to, $subject, $message, $headers);
        error_log("Mail function result: " . ($result ? "Success" : "Failed"));
        
        // Save a copy of the email to a file for debugging
        $logDir = "../logs";
        if (!is_dir($logDir)) {
            mkdir($logDir, 0755, true);
        }
        
        $emailLog = fopen("$logDir/email_" . time() . ".html", "w");
        if ($emailLog) {
            fwrite($emailLog, "To: $to\nSubject: $subject\nHeaders: $headers\n\n$message");
            fclose($emailLog);
            error_log("Email content saved to log file");
        }
        
        return $result;
    } catch (Exception $e) {
        error_log("Email sending error: " . $e->getMessage());
        return false;
    }
}

// Security checks
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error_message'] = 'Invalid request method.';
    header('Location: wire_transactions.php');
    exit;
}

// Get and validate inputs
$transfer_id = filter_input(INPUT_POST, 'transfer_id', FILTER_VALIDATE_INT);
$action = $_POST['action'] ?? '';
$reason = $_POST['reason'] ?? '';
$admin_id = $_SESSION['admin_id'] ?? 1; // Default to 1 if not set

error_log("Action: $action, Transfer ID: $transfer_id, Reason: $reason");

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

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

try {
    // Get the wire transfer details first (outside of transaction)
    $stmt = $db->prepare("
        SELECT wt.*, u.email, u.first_name, u.last_name 
        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.");
    }

    // Determine the effective status based on various fields
    $effective_status = 'pending';
    if (!empty($transfer['hold_reason'])) {
        $effective_status = 'hold';
    } elseif (!empty($transfer['approved_at'])) {
        $effective_status = 'approved';
    } elseif (!empty($transfer['rejected_reason'])) {
        $effective_status = 'rejected';
    }
    
    error_log("Effective status: '$effective_status'");
    
    if ($effective_status !== 'pending' && $effective_status !== 'hold' && $action !== 'approve') {
        throw new Exception("Transfer cannot be updated because it is already " . ucfirst($effective_status));
    }

    // Process based on action
    if ($action === 'approve') {
        error_log("Approving transfer");
        
        // Start transaction for approve action
        $db->beginTransaction();
        
        // Update approved fields
        $stmt = $db->prepare("
            UPDATE wire_transfers 
            SET 
                approved_by = ?, 
                approved_at = NOW(),
                hold_reason = NULL,
                hold_by = NULL,
                hold_at = NULL
            WHERE id = ?
        ");
        $stmt->execute([$admin_id, $transfer_id]);
        
        // Verify the update worked
        $check_stmt = $db->prepare("SELECT approved_at FROM wire_transfers WHERE id = ?");
        $check_stmt->execute([$transfer_id]);
        $approved_at = $check_stmt->fetchColumn();
        error_log("Approved at: '$approved_at'");
        
        if (empty($approved_at)) {
            throw new Exception("Failed to update approved_at field.");
        }
        
        // Update the corresponding transaction log to 'completed'
        $update_txn = $db->prepare("UPDATE transactions SET status = 'completed' WHERE reference = ?");
        $update_txn->execute([$transfer['reference'] . '_D']);
        
        // Commit the transaction
        $db->commit();
        
        $_SESSION['success_message'] = "Wire transfer #{$transfer['reference']} has been approved.";
        
        // Send email notification using the working function
        if (!empty($transfer['email'])) {
            try {
                $userName = $transfer['first_name'] . ' ' . $transfer['last_name'];
                $formattedAmount = number_format($transfer['amount'], 2);
                $date = date('F j, Y, g:i a');
                
                $emailResult = sendTransactionEmail(
                    $transfer['email'],
                    $userName,
                    'approved',
                    $formattedAmount,
                    $transfer['currency'],
                    $transfer['reference'],
                    "Your wire transfer to {$transfer['recipient_name']} has been approved.",
                    null,
                    $date
                );
                
                error_log("Approval email result: " . ($emailResult ? "Success" : "Failed"));
            } catch (Exception $e) {
                error_log("Error sending approval email: " . $e->getMessage());
            }
        }
        
    } elseif ($action === 'reject') {
        error_log("Rejecting transfer");
        
        if (empty($reason)) {
            throw new Exception("A reason is required for rejection.");
        }
        
        // Start transaction for reject action
        $db->beginTransaction();
        
        // Check if rejected_by column exists
        $checkColumn = $db->prepare("
            SELECT COUNT(*) 
            FROM information_schema.COLUMNS 
            WHERE TABLE_SCHEMA = DATABASE() 
            AND TABLE_NAME = 'wire_transfers' 
            AND COLUMN_NAME = 'rejected_by'
        ");
        $checkColumn->execute();
        $rejectedByExists = (bool)$checkColumn->fetchColumn();
        
        // Check if rejected_at column exists
        $checkColumn = $db->prepare("
            SELECT COUNT(*) 
            FROM information_schema.COLUMNS 
            WHERE TABLE_SCHEMA = DATABASE() 
            AND TABLE_NAME = 'wire_transfers' 
            AND COLUMN_NAME = 'rejected_at'
        ");
        $checkColumn->execute();
        $rejectedAtExists = (bool)$checkColumn->fetchColumn();
        
        // Build the SQL query based on which columns exist
        $sql = "UPDATE wire_transfers SET rejected_reason = ?";
        $params = [$reason];
        
        if ($rejectedByExists) {
            $sql .= ", rejected_by = ?";
            $params[] = $admin_id;
        }
        
        if ($rejectedAtExists) {
            $sql .= ", rejected_at = NOW()";
        }
        
        $sql .= ", hold_reason = NULL, hold_by = NULL, hold_at = NULL WHERE id = ?";
        $params[] = $transfer_id;
        
        // Execute the update
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        
        // Verify the update worked
        $check_stmt = $db->prepare("SELECT rejected_reason FROM wire_transfers WHERE id = ?");
        $check_stmt->execute([$transfer_id]);
        $rejected_reason = $check_stmt->fetchColumn();
        error_log("Rejected reason: '$rejected_reason'");
        
        if (empty($rejected_reason)) {
            throw new Exception("Failed to update rejected_reason field.");
        }
        
        // Update the corresponding transaction log to 'rejected'
        $update_txn = $db->prepare("UPDATE transactions SET status = 'rejected' WHERE reference = ?");
        $update_txn->execute([$transfer['reference'] . '_D']);
        
        // 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 #" . $transfer['reference'], 
            'REFUND_' . $transfer['reference']
        ]);
        
        // Commit the transaction
        $db->commit();
        
        $_SESSION['success_message'] = "Wire transfer #{$transfer['reference']} has been rejected and funds returned to the user.";
        
        // Send email notification using the working function
        if (!empty($transfer['email'])) {
            try {
                $userName = $transfer['first_name'] . ' ' . $transfer['last_name'];
                $formattedAmount = number_format($total_refund, 2);
                $date = date('F j, Y, g:i a');
                
                $emailResult = sendTransactionEmail(
                    $transfer['email'],
                    $userName,
                    'rejected',
                    $formattedAmount,
                    $transfer['currency'],
                    'REFUND_' . $transfer['reference'],
                    "Your wire transfer has been rejected. Reason: " . $reason,
                    null,
                    $date
                );
                
                error_log("Rejection email result: " . ($emailResult ? "Success" : "Failed"));
            } catch (Exception $e) {
                error_log("Error sending rejection email: " . $e->getMessage());
            }
        }
        
    } elseif ($action === 'hold') {
        error_log("Placing transfer on hold");
        
        if (empty($reason)) {
            throw new Exception("A reason is required for placing a transfer on hold.");
        }
        
        // Update hold fields
        $stmt = $db->prepare("
            UPDATE wire_transfers 
            SET 
                hold_reason = ?, 
                hold_by = ?, 
                hold_at = NOW() 
            WHERE id = ?
        ");
        $result = $stmt->execute([$reason, $admin_id, $transfer_id]);
        error_log("Hold update result: " . ($result ? "Success" : "Failed"));
        
        // Verify the update worked
        $check_stmt = $db->prepare("SELECT hold_reason FROM wire_transfers WHERE id = ?");
        $check_stmt->execute([$transfer_id]);
        $hold_reason = $check_stmt->fetchColumn();
        error_log("Hold reason after update: '$hold_reason'");
        
        if (empty($hold_reason)) {
            // Try a direct SQL approach if the prepared statement failed
            error_log("Prepared statement failed, trying direct SQL");
            $safe_reason = $db->quote($reason);
            $db->exec("UPDATE wire_transfers SET hold_reason = $safe_reason, hold_by = $admin_id, hold_at = NOW() WHERE id = $transfer_id");
            
            // Check again
            $check_stmt->execute([$transfer_id]);
            $hold_reason = $check_stmt->fetchColumn();
            error_log("Hold reason after direct SQL: '$hold_reason'");
            
            if (empty($hold_reason)) {
                throw new Exception("Failed to update hold_reason field after multiple attempts.");
            }
        }
        
        // Update the corresponding transaction log to 'on_hold'
        try {
            $update_txn = $db->prepare("UPDATE transactions SET status = 'on_hold' WHERE reference = ?");
            $update_txn->execute([$transfer['reference'] . '_D']);
        } catch (Exception $e) {
            error_log("Failed to update transaction status: " . $e->getMessage());
            // Continue anyway
        }
        
        $_SESSION['success_message'] = "Wire transfer #{$transfer['reference']} has been placed on hold.";
        
        // Send email notification using the working function
        if (!empty($transfer['email'])) {
            try {
                $userName = $transfer['first_name'] . ' ' . $transfer['last_name'];
                $formattedAmount = number_format($transfer['amount'], 2);
                $date = date('F j, Y, g:i a');
                
                $emailResult = sendTransactionEmail(
                    $transfer['email'],
                    $userName,
                    'hold',
                    $formattedAmount,
                    $transfer['currency'],
                    $transfer['reference'],
                    "Your wire transfer has been placed on hold. Reason: " . $reason,
                    null,
                    $date
                );
                
                error_log("Hold email result: " . ($emailResult ? "Success" : "Failed"));
            } catch (Exception $e) {
                error_log("Error sending hold email: " . $e->getMessage());
            }
        }
    }
    
    // Final status check
    $check_stmt = $db->prepare("
        SELECT 
            hold_reason, 
            approved_at, 
            rejected_reason 
        FROM wire_transfers 
        WHERE id = ?
    ");
    $check_stmt->execute([$transfer_id]);
    $final_check = $check_stmt->fetch(PDO::FETCH_ASSOC);
    
    $final_status = 'pending';
    if (!empty($final_check['hold_reason'])) {
        $final_status = 'hold';
    } elseif (!empty($final_check['approved_at'])) {
        $final_status = 'approved';
    } elseif (!empty($final_check['rejected_reason'])) {
        $final_status = 'rejected';
    }
    
    error_log("Final effective status: '$final_status'");
    
    // Determine where to redirect
    $redirect_url = isset($_POST['from_details']) ? "view_wire_transfer.php?id=$transfer_id" : "wire_transactions.php";
    header("Location: $redirect_url");
    exit;
    
} catch (Exception $e) {
    // Rollback the transaction if there's an error and a transaction is active
    if (isset($db) && $db->inTransaction()) {
        $db->rollBack();
        error_log("Transaction rolled back due to error");
    }
    
    error_log("Wire Transfer Action Error: " . $e->getMessage());
    $_SESSION['error_message'] = "An error occurred: " . $e->getMessage();
    
    // Determine where to redirect
    $redirect_url = isset($_POST['from_details']) ? "view_wire_transfer.php?id=$transfer_id" : "wire_transactions.php";
    header("Location: $redirect_url");
    exit;
}
?>
