<?php
require_once 'includes/auth_check.php';
$page = 'credit_debit';
require_once '../config/database.php';

// For debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Function to send transaction notification email
function sendTransactionEmail($to, $name, $type, $amount, $currency, $reference, $description, $newBalance, $date) {
    $bankName = defined('BANK_NAME') ? BANK_NAME : 'Our Banking Platform';
    $bankLogo = defined('BANK_LOGO_URL') ? BANK_LOGO_URL : 'https://online.oceanbankcooperation.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');
    $transactionColor = $isCredit ? '#28a745' : '#dc3545';
    $transactionIcon = $isCredit ? '↑' : '↓';
    $transactionType = $isCredit ? 'Credit' : 'Debit';
    
    $subject = "$transactionType Transaction Notification - $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>$transactionType Transaction Notification</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>$transactionType Transaction Notification</h1>
            <p>Dear $name,</p>
            <p>This is to inform you that a $transactionType transaction has been processed on your account.</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>Transaction Type</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>
                    <tr>
                        <th>Current Balance</th>
                        <td>$currency $newBalance</td>
                    </tr>
                </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>
</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 : 'Ocean Bank Cooperation';
    $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;
    }
}

// Function to format currency based on type
function formatCurrency($amount, $currency) {
    if ($currency == 'BTC' || $currency == 'ETH') {
        // For cryptocurrencies, show 8 decimal places
        return number_format($amount, 8, '.', ',');
    } else {
        // For fiat currencies, show 2 decimal places
        return number_format($amount, 2, '.', ',');
    }
}

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

// --- Handle Form Submission (POST Request) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $_SESSION['error_message'] = "Invalid security token. Action denied.";
    } else {
        $errors = [];
        $user_id = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT);
        $type = $_POST['type'] ?? '';
        $currency = $_POST['currency'] ?? '';
        $description = trim($_POST['description'] ?? '');
        $amount_raw = $_POST['amount'] ?? '';
        $amount = filter_var($amount_raw, FILTER_VALIDATE_FLOAT);
        
        // Get the transaction date and time from the form
        $transaction_date = $_POST['transaction_date'] ?? date('Y-m-d');
        $transaction_time = $_POST['transaction_time'] ?? date('H:i');
        $transaction_datetime = $transaction_date . ' ' . $transaction_time . ':00';

        if (empty($user_id)) $errors[] = "A user must be selected.";
        if ($amount === false || $amount <= 0) $errors[] = "Amount must be a valid positive number.";
        if (!in_array($type, ['credit', 'debit'])) $errors[] = "A transaction type must be selected.";
        if (empty($currency)) $errors[] = "A currency must be selected.";
        if (empty($description)) $errors[] = "A description/reason is required.";
        if (empty($transaction_date)) $errors[] = "Transaction date is required.";
        if (empty($transaction_time)) $errors[] = "Transaction time is required.";

        if (empty($errors)) {
            try {
                $db->beginTransaction();
                
                // Get the user's account number and email first
                $user_stmt = $db->prepare("SELECT account_number, first_name, last_name, email FROM users WHERE id = ?");
                $user_stmt->execute([$user_id]);
                $user_data = $user_stmt->fetch(PDO::FETCH_ASSOC);
                
                if (!$user_data) {
                    throw new Exception("User does not exist.");
                }
                
                $account_number = $user_data['account_number'];
                
                $stmt = $db->prepare("SELECT balance FROM account_balances WHERE user_id = :user_id AND currency = :currency FOR UPDATE");
                $stmt->execute([':user_id' => $user_id, ':currency' => $currency]);
                $balance_data = $stmt->fetch(PDO::FETCH_ASSOC);

                // Store the current balance before making changes
                $current_balance = $balance_data ? (float)$balance_data['balance'] : 0;
                $new_balance = ($type == 'credit') ? $current_balance + $amount : $current_balance - $amount;
                
                if ($balance_data) {
                    if ($type == 'debit' && $new_balance < 0) throw new Exception("Insufficient funds.");
                    
                    $update_stmt = $db->prepare("UPDATE account_balances SET balance = :new_balance, last_updated = NOW() WHERE user_id = :user_id AND currency = :currency");
                    $update_stmt->execute([':new_balance' => $new_balance, ':user_id' => $user_id, ':currency' => $currency]);
                } else {
                    if ($type == 'debit') throw new Exception("Cannot debit. User has no {$currency} account.");
                    
                    // Include account_number in the INSERT statement
                    $create_stmt = $db->prepare("INSERT INTO account_balances (user_id, account_number, currency, balance, last_updated) VALUES (:user_id, :account_number, :currency, :balance, NOW())");
                    $create_stmt->execute([
                        ':user_id' => $user_id, 
                        ':account_number' => $account_number, 
                        ':currency' => $currency, 
                        ':balance' => $amount
                    ]);
                }

                // Generate a reference number
                $reference = 'ADMIN_' . time();
                
                // Insert transaction with the specified date and time
                $trans_stmt = $db->prepare("
                    INSERT INTO transactions 
                    (user_id, type, amount, currency, description, reference, status, transaction_type, created_at) 
                    VALUES 
                    (:user_id, :type, :amount, :currency, :description, :reference, 'completed', 'adjustment', :created_at)
                ");
                $trans_stmt->execute([
                    ':user_id' => $user_id, 
                    ':type' => $type, 
                    ':amount' => $amount, 
                    ':currency' => $currency, 
                    ':description' => "Admin Action: " . $description, 
                    ':reference' => $reference,
                    ':created_at' => $transaction_datetime
                ]);
                
                $db->commit();
                
                // Send transaction notification email
                $emailSent = false;
                try {
                    $fullName = $user_data['first_name'] . ' ' . $user_data['last_name'];
                    $formattedDate = date('F j, Y, g:i a', strtotime($transaction_datetime));
                    
                    // Format the balance for display
                    $formattedBalance = formatCurrency($new_balance, $currency);
                    $formattedAmount = formatCurrency($amount, $currency);
                    
                    // Debug information
                    error_log("Sending email to: " . $user_data['email']);
                    error_log("Transaction details: Type=$type, Amount=$formattedAmount $currency, Date=$formattedDate");
                    
                    $emailSent = sendTransactionEmail(
                        $user_data['email'],
                        $fullName,
                        $type,
                        $formattedAmount,
                        $currency,
                        $reference,
                        "Admin Action: " . $description,
                        $formattedBalance,
                        $formattedDate
                    );
                    
                    error_log("Email sending result: " . ($emailSent ? "Success" : "Failed"));
                } catch (Exception $e) {
                    error_log("Email sending error: " . $e->getMessage());
                }
                
                $_SESSION['success_message'] = "Transaction posted successfully." . 
                    ($emailSent ? " Email notification sent." : " Email notification could not be sent. Check server logs for details.");
                
            } catch (Exception $e) {
                $db->rollBack();
                $_SESSION['error_message'] = "Transaction failed: " . $e->getMessage();
            }
        } else {
            $_SESSION['error_message'] = implode("<br>", $errors);
        }
    }
    header("Location: credit_debit_user.php");
    exit;
}

// --- Fetch Data for Form ---
$users = $db->query("SELECT id, first_name, last_name, username FROM users WHERE role = 'user' AND status = 'active' ORDER BY first_name, last_name")->fetchAll(PDO::FETCH_ASSOC);
$currencies = ['USD', 'BTC', 'ETH', 'EUR', 'GBP'];
sort($currencies);
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

// Create logs directory if it doesn't exist
if (!is_dir('../logs')) {
    mkdir('../logs', 0755, true);
}

include 'includes/header.php';
?>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Manual Account Adjustment</h1>

    <!-- Display Messages -->
    <?php if (isset($_SESSION['success_message'])): ?><div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
    <?php if (isset($_SESSION['error_message'])): ?><div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

    <div class="card shadow mb-4">
        <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Post a New Transaction</h6></div>
        <div class="card-body">
            <form action="credit_debit_user.php" method="POST" onsubmit="return confirmTransaction(event);">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="user_id" class="form-label">Select User</label>
                        <select class="form-select" id="user_id" name="user_id" required onchange="updateUserBalance()">
                            <option value="" disabled selected>-- Choose a user --</option>
                            <?php foreach ($users as $user): ?>
                                <option value="<?php echo $user['id']; ?>"><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name'] . ' (@' . $user['username'] . ')'); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="currency" class="form-label">Currency</label>
                        <select class="form-select" id="currency" name="currency" required onchange="updateUserBalance()">
                            <option value="" disabled selected>-- Select --</option>
                            <?php foreach ($currencies as $currency): ?>
                                <option value="<?php echo htmlspecialchars($currency); ?>"><?php echo htmlspecialchars($currency); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <div id="currentBalanceInfo" class="form-text mt-2 fw-bold"></div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="amount" class="form-label">Amount</label>
                        <input type="text" class="form-control" id="amount" name="amount" required placeholder="e.g., 100.00 or 0.005">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Transaction Type</label>
                        <div>
                            <div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="type" id="type_credit" value="credit" required><label class="form-check-label" for="type_credit">Credit</label></div>
                            <div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="type" id="type_debit" value="debit"><label class="form-check-label" for="type_debit">Debit</label></div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="transaction_date" class="form-label">Transaction Date</label>
                        <input type="date" class="form-control" id="transaction_date" name="transaction_date" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="transaction_time" class="form-label">Transaction Time</label>
                        <input type="time" class="form-control" id="transaction_time" name="transaction_time" required>
                    </div>
                </div>
                <div class="mb-3">
                    <label for="description" class="form-label">Description / Reason</label>
                    <textarea class="form-control" id="description" name="description" rows="3" required placeholder="e.g., Refund for failed transaction #12345 or Bonus for loyalty program."></textarea>
                </div>
                <button type="submit" class="btn btn-primary">Post Transaction</button>
            </form>
        </div>
    </div>
</div>

<script>
function updateUserBalance() {
    const userId = document.getElementById('user_id').value;
    const currency = document.getElementById('currency').value;
    const balanceInfo = document.getElementById('currentBalanceInfo');
    
    if (!userId || !currency) {
        balanceInfo.innerHTML = ''; // Clear if either dropdown is not selected
        return;
    }
    
    balanceInfo.innerHTML = '<small class="text-muted">Loading balance...</small>';
    
    fetch(`get_user_balance.php?user_id=${userId}&currency=${currency}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const decimalPlaces = (currency === 'BTC' || currency === 'ETH') ? 8 : 2;
                const formattedBalance = parseFloat(data.balance).toLocaleString('en-US', {
                    minimumFractionDigits: decimalPlaces,
                    maximumFractionDigits: decimalPlaces
                });
                
                // Apply styling based on balance amount
                let balanceClass = 'text-info';
                if (parseFloat(data.balance) > 0) {
                    balanceClass = 'text-success';
                } else if (parseFloat(data.balance) < 0) {
                    balanceClass = 'text-danger';
                }
                
                balanceInfo.innerHTML = `<span class="${balanceClass}">Current Balance: <strong>${formattedBalance} ${currency}</strong></span>`;
            } else {
                balanceInfo.innerHTML = `<span class="text-warning">No ${currency} balance found</span>`;
            }
        })
        .catch(error => {
            console.error('Error fetching balance:', error);
            balanceInfo.innerHTML = '<span class="text-danger">Could not fetch balance.</span>';
        });
}

function confirmTransaction(event) {
    event.preventDefault();
    const form = event.target;
    
    const amountInput = form.querySelector('#amount');
    const amountValue = amountInput.value.trim();
    const typeInput = form.querySelector('input[name="type"]:checked');
    const userSelect = form.querySelector('#user_id');
    const currency = form.querySelector('#currency').value;
    const transactionDate = form.querySelector('#transaction_date').value;
    const transactionTime = form.querySelector('#transaction_time').value;

    if (amountValue === '' || !/^[0-9.]*$/.test(amountValue) || parseFloat(amountValue) <= 0) {
        Swal.fire('Invalid Amount', 'Please enter a valid, positive number for the amount.', 'error');
        return false;
    }
    
    if (!userSelect.value) { Swal.fire('Error', 'Please select a user.', 'error'); return false; }
    if (!currency) { Swal.fire('Error', 'Please select a currency.', 'error'); return false; }
    if (!typeInput) { Swal.fire('Error', 'Please select a transaction type.', 'error'); return false; }
    if (!transactionDate) { Swal.fire('Error', 'Please select a transaction date.', 'error'); return false; }
    if (!transactionTime) { Swal.fire('Error', 'Please select a transaction time.', 'error'); return false; }

    const type = typeInput.value;
    const userName = userSelect.options[userSelect.selectedIndex].text;
    const formattedDateTime = new Date(`${transactionDate}T${transactionTime}`).toLocaleString();

    Swal.fire({
        title: 'Are you absolutely sure?',
        html: `You are about to post a <strong>${type.toUpperCase()}</strong> of <strong>${currency} ${amountValue}</strong> for:<br><b>${userName}</b>.<br><br>Transaction Date/Time: <b>${formattedDateTime}</b>`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, post it!',
    }).then((result) => {
        if (result.isConfirmed) {
            form.submit();
        }
    });
    
    return false;
}

// Initialize the date and time fields with current values
document.addEventListener('DOMContentLoaded', function() {
    const today = new Date();
    const dateInput = document.getElementById('transaction_date');
    const timeInput = document.getElementById('transaction_time');
    
    // Format date as YYYY-MM-DD
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    dateInput.value = `${year}-${month}-${day}`;
    
    // Format time as HH:MM
    const hours = String(today.getHours()).padStart(2, '0');
    const minutes = String(today.getMinutes()).padStart(2, '0');
    timeInput.value = `${hours}:${minutes}`;
});
</script>

<?php include 'includes/footer.php'; ?>
