<?php
ob_start();
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include("header.php");
//include("../config/theconfig.php");

if (!isset($_SESSION['customerid'])) {
    header('Location: login.php?error=nologin');
    exit;
}

// Prepared statement to fetch accounts
$stmt_acc = $con->prepare("SELECT * FROM accounts WHERE customerid=?");
$stmt_acc->bind_param("s", $_SESSION['customerid']);
$stmt_acc->execute();
$acc = $stmt_acc->get_result();

// Assuming you have the transaction details in variables
$beneficiaryDetails = htmlspecialchars($_POST['rname'] ?? '') . " (Account No: " . htmlspecialchars($_POST['acctno'] ?? '') . ")";
$senderDetails = htmlspecialchars($_SESSION['customername'] ?? '') . " (Account No: " . htmlspecialchars($_POST['acct'] ?? '') . ")";
$amountTransferred = htmlspecialchars($_POST['pay_amt'] ?? '0');
$theReference = "TXN" . rand(1000000, 9999999);
$paymentType = "Outward Transfer";
$paidOn = date("d M Y h:i A");

// System Settings (for currency symbol if needed)
$cur = '$';
$sbank = 'Default Bank';
$favicon = ''; 

if (isset($con) && $con instanceof mysqli) {
   $stmt = $con->prepare("SELECT bank_name, currency, favicon FROM system_settings LIMIT 1");
   if ($stmt) {
       $stmt->execute();
       $stmt->bind_result($bankname_db, $currency_db, $favicon_db);
       if($stmt->fetch()) {
           $sbank = $bankname_db ? $bankname_db : $sbank;
           $cur = $currency_db ? $currency_db : $cur;
           $favicon = $favicon_db;
       }
       $stmt->close();
   }
}

// Fetch available balance for the balance display
$stmt_balance = $con->prepare("SELECT accountbalance FROM accounts WHERE customerid=?");
$stmt_balance->bind_param("s", $_SESSION['customerid']);
$stmt_balance->execute();
$result_balance = $stmt_balance->get_result();
$arrow = $result_balance->fetch_assoc();
$availableBalance = $arrow['accountbalance'] ?? 0;
$stmt_balance->close();

?>

<html lang="en">
   <head>
      <meta charset="utf-8" />
      <title>Send Money | <?php echo $sbank ?></title>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      
      <?php if (!empty($favicon)): ?>
      <link rel="icon" href="../<?= htmlspecialchars($favicon); ?>" type="image/<?= pathinfo($favicon, PATHINFO_EXTENSION); ?>">
      <?php endif; ?>
      
      <link href="assets/css/bootstrap.min.css" id="bootstrap-style" rel="stylesheet" type="text/css" />
      <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
      <link href="assets/css/app.min.css" id="app-style" rel="stylesheet" type="text/css" />
      
      <link rel="preconnect" href="https://fonts.googleapis.com">
      <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
      <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
      
      <script src="assets/libs2/custom/sweetalert.min.js"></script>
      <style>
    /* --- PREMIUM BLUE THEME --- */
    :root {
        --primary-purple: #003399; /* Updated to Primary Blue */
        --dark-purple: #005D9D;    /* Updated to Secondary Blue */
        --deep-bg: #001a4d;        /* Darker Blue for background depth */
        --soft-purple-bg: #e6efff; /* Very Light Blue for focus/hover states */
        
        --bg-body: #f8fafc;
        --card-surface: #ffffff;
        --text-main: #000000; /* Set to Black */
        --text-secondary: #000000; /* Set to Black for Labels */
        --border-light: #e2e8f0;
        
        --shadow-sm: 0 1px 3px rgba(0,0,0,0.1);
        --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
    }

    body {
        background-color: var(--bg-body);
        font-family: 'Plus Jakarta Sans', sans-serif;
        color: var(--text-main);
    }

    .page-content { padding-top: 80px; padding-bottom: 60px; }

    .swal-text { font-size: 13px; }

    /* --- Transfer Card Styling --- */
    .transfer-card {
        background: white;
        border-radius: 24px;
        border: none;
        overflow: hidden;
        box-shadow: var(--shadow-lg);
        height: 100%;
    }

    .transfer-header {
        background: linear-gradient(135deg, var(--deep-bg) 0%, var(--primary-purple) 100%);
        padding: 40px;
        color: white;
        position: relative;
    }
    
    .transfer-header::before {
        content: '';
        position: absolute;
        top: -50%; right: -5%;
        width: 400px; height: 400px;
        background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 60%);
        border-radius: 50%;
    }

    .balance-pill {
        background: rgba(255,255,255,0.2);
        backdrop-filter: blur(5px);
        padding: 8px 20px;
        border-radius: 50px;
        display: inline-block;
        margin-top: 10px;
        border: 1px solid rgba(255,255,255,0.1);
        font-size: 1rem;
    }

    /* --- Form Styling --- */
    .card-body { padding: 40px; }

    .form-floating > .form-control, 
    .form-floating > .form-select {
        border: 1px solid var(--border-light);
        border-radius: 12px;
        height: 58px;
        color: #000000 !important; /* Force Black */
        font-weight: 700 !important; /* Force Bold */
    }

    .form-floating > .form-control:focus,
    .form-floating > .form-select:focus {
        border-color: var(--primary-purple);
        box-shadow: 0 0 0 4px var(--soft-purple-bg);
    }
    
    .form-floating > label { 
        color: #000000 !important; /* Force Black */
        font-weight: 700 !important; /* Force Bold */
    }

    .btn-primary {
        background: var(--primary-purple);
        border: none;
        border-radius: 12px;
        padding: 16px;
        font-weight: 700;
        letter-spacing: 0.5px;
        box-shadow: 0 4px 12px rgba(0, 51, 153, 0.3); /* Adjusted shadow to Blue */
        transition: all 0.3s;
        font-size: 1.1rem;
    }
    
    .btn-primary:hover {
        background: var(--dark-purple);
        transform: translateY(-2px);
        box-shadow: 0 6px 15px rgba(0, 51, 153, 0.4);
    }
    
    .btn-primary:disabled {
        background: #cbd5e1;
        box-shadow: none;
        transform: none;
    }

    /* Breadcrumb and Helper Text color */
    .text-purple { color: var(--primary-purple) !important; }

    .security-notice {
        background: #fffbeb;
        border: 1px solid #fcd34d;
        color: #92400e;
        padding: 15px;
        border-radius: 12px;
        font-size: 0.9rem;
        display: flex;
        gap: 15px;
        align-items: center;
        margin-bottom: 30px;
    }
</style>
   </head>

   <body data-sidebar="colored">
      <div id="layout-wrapper">
         <div class="main-content">
            <div class="page-content">
               <div class="container-fluid">
                  
                  <div class="row mb-4">
                      <div class="col-12">
                          <div class="d-flex align-items-center justify-content-between">
                              <div>
                                  <h4 class="mb-1 fw-bold text-dark">International Transfer</h4>
                                  <p class="text-secondary mb-0">Securely send money to any bank account.</p>
                              </div>
                              <div class="d-none d-md-block">
                                  <nav aria-label="breadcrumb">
                                      <ol class="breadcrumb m-0">
                                          <li class="breadcrumb-item"><a href="dashboard.php" class="text-decoration-none text-muted">Dashboard</a></li>
                                          <li class="breadcrumb-item active text-purple fw-bold">Transfer</li>
                                      </ol>
                                  </nav>
                              </div>
                          </div>
                      </div>
                  </div>

                  <div class="row">
                     <div class="col-12"> <div class="transfer-card">
                           
                           <div class="transfer-header text-center">
                               <h4 class="text-white mb-2 fw-bold">Dear <?php echo htmlspecialchars($_SESSION['customername'] ?? ''); ?></h4>
                               <div class="balance-pill">
                                   <span style="opacity: 0.8;">Available Balance:</span>
                                   <span class="fw-bold ms-2"><?php echo htmlspecialchars($cur ?? '') . ' ' . number_format($availableBalance, 2); ?></span>
                               </div>
                           </div>

                           <div class="card-body">
                              
                              <div class="security-notice">
                                  <i class="bx bx-shield-quarter fs-3"></i>
                                  <div>
                                      <strong>Security Alert:</strong> Your IP Address: <?php echo htmlspecialchars($_SERVER['REMOTE_ADDR']); ?> has been logged for security monitoring. Please ensure all beneficiary details are correct before proceeding.
                                  </div>
                              </div>
                              
                              <form id="transferForm" name="form1" method="post" action="internationalbankstransfer.php">
                                 
                                 <?php 
                                 if (isset($_REQUEST['error'])) {
                                     $error_messages = [
                                         'nodetails' => "Details Missing or Invalid.<br/>Payment Failed",
                                         'WrongPassword' => "Wrong Password Entered!",
                                         'insufficientbalance' => "Insufficient Balance. Please check account funds.",
                                         'cot' => "Wrong COT Code Entered! Contact Support.",
                                         'imf' => "Wrong IMF Code Entered! Contact Support.",
                                         'accountnotfound' => "Wrong Account Number. Please Check and Try Again!"
                                     ];
                                     $error_type = htmlspecialchars($_REQUEST['error']);
                                     if (isset($error_messages[$error_type])) {
                                         $message = $error_messages[$error_type];
                                         if ($error_type === 'nodetails') {
                                             echo "<div class='alert alert-danger text-center'>$message</div>";
                                         } else {
                                             echo "<script>swal('Error!', '$message', 'error').then((value) => {window.location='international.php'})</script>;";
                                         }
                                     } 
                                 }

                                 if (isset($_REQUEST['success']) && $_REQUEST['success'] === 'successful') {
                                     // Success Modal Logic (Kept exactly as yours)
                                     echo '<script>
                                        swal({
                                            title: "Transfer Successful!",
                                            html: `
                                               <div style="font-size: 16px;">
                                                  <div style="text-align: center; font-weight: bold; font-size: 18px;">
                                                    Amount: ₦' . htmlspecialchars($amountTransferred) . '
                                                  </div>
                                                  <hr>
                                                  <div style="display: flex; justify-content: space-between;">
                                                    <div><strong>Beneficiary:</strong></div>
                                                    <div>' . htmlspecialchars($beneficiaryDetails) . '</div>
                                                  </div>
                                                  <hr>
                                                  <div style="display: flex; justify-content: space-between;">
                                                    <div><strong>Sender:</strong></div>
                                                    <div>' . htmlspecialchars($senderDetails) . '</div>
                                                  </div>
                                                  <hr>
                                                  <div style="display: flex; justify-content: space-between;">
                                                    <div><strong>Date:</strong></div>
                                                    <div>' . htmlspecialchars($paidOn) . '</div>
                                                  </div>
                                                  <hr>
                                                  <div style="display: flex; justify-content: space-between;">
                                                    <div><strong>Ref:</strong></div>
                                                    <div>' . htmlspecialchars($theReference) . '</div>
                                                  </div>
                                                  <hr>
                                                  <div style="text-align: center; margin-top: 20px;">
                                                    <button onclick="window.print();" style="padding: 10px 20px; background-color: #7c3aed; color: white; border: none; cursor: pointer; border-radius: 8px;">Print Receipt</button>
                                                  </div>
                                               </div>
                                            `,
                                            icon: "success",
                                            confirmButtonText: "Done",
                                            customClass: { container: "swal-text" }
                                        }).then((value) => {
                                            window.location = "international.php";
                                        });
                                     </script>';
                                 }
                                 ?>
                                 
                                 <div class="row g-4">
                                     <div class="col-12">
                                         <div class="form-floating">
                                            <input type="text" class="form-control" name="bank" id="bank" placeholder="Enter Receiver's Bank" required>
                                            <label for="bank">Receiver's Bank Name</label>
                                            <span id="bankError" class="text-danger small mt-1"></span>
                                         </div>
                                     </div>

                                    <div class="col-md-6">
                                       <div class="form-floating">
                                          <input type="text" class="form-control" name="bankadd" id="bankadd" placeholder="Receiver's Bank Address" required>
                                          <label for="bankadd">Bank Address</label>
                                          <span id="bankAddError" class="text-danger small mt-1"></span>
                                       </div>
                                    </div>
                                    <div class="col-md-6">
                                       <div class="form-floating">
                                          <input type="text" class="form-control" name="rname" id="rname" placeholder="Receiver's Name" required>
                                          <label for="rname">Receiver's Name</label>
                                          <span id="rnameError" class="text-danger small mt-1"></span>
                                       </div>
                                    </div>
                                    <div class="col-md-6">
                                       <div class="form-floating">
                                          <input type="text" class="form-control" name="acctno" id="acctno" placeholder="Receiver's Account Number" required>
                                          <label for="acctno">Account Number</label>
                                          <span id="acctnoError" class="text-danger small mt-1"></span>
                                       </div>
                                    </div>
                                    <div class="col-md-6">
                                       <div class="form-floating">
                                          <input type="text" class="form-control" name="swift" id="swift" placeholder="Swift/Routing Number" required>
                                          <label for="swift">Swift / Routing Number</label>
                                          <span id="swiftError" class="text-danger small mt-1"></span>
                                       </div>
                                    </div>
                                    <div class="col-md-6">
                                       <div class="form-floating">
                                          <input type="text" class="form-control" min="0" name="pay_amt" id="pay_amt" placeholder="Enter Amount" required style="font-size: 1.1rem;">
                                          <label for="pay_amt">Amount To Transfer</label>
                                          <span id="amountError" class="text-danger small mt-1"></span> 
                                       </div>
                                    </div>
                                    <div class="col-md-6">
                                       <div class="form-floating">
                                          <select class="form-select" name="acct" id="ac_no" aria-label="Select Sender's Account">
                                             <?php 
                                             $stmt_select = $con->prepare("SELECT accno FROM accounts WHERE customerid=?");
                                             $stmt_select->bind_param("s", $_SESSION['customerid']);
                                             $stmt_select->execute();
                                             $result_select = $stmt_select->get_result();
                                             while ($rowsacc = $result_select->fetch_assoc()) {
                                                 echo "<option value='".htmlspecialchars($rowsacc['accno'])."'>".htmlspecialchars($rowsacc['accno'])."</option>";
                                             }
                                             $stmt_select->close();
                                             ?>
                                          </select>
                                          <label for="ac_no">Debit From Account</label>
                                       </div>
                                    </div>
                                 </div>
                                 
                                 <div class="mt-4 d-grid">
                                     <button type="submit" name="pay" id="pay" class="btn btn-primary btn-lg shadow-lg">Proceed Transfer</button>
                                 </div>
                              </form>
                           </div>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
            
            <?php include 'footer.php'; ?>
            
         </div>
      </div>

      <script src="assets/libs/jquery/jquery.min.js"></script>
      <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
      <script src="assets/libs/simplebar/simplebar.min.js"></script>
      <script src="assets/libs/node-waves/waves.min.js"></script>
      <script src="assets/js/app.js"></script>
      <script src="assets/libs2/node_modules/sweetalert2/dist/sweetalert2.js"></script>
      <script src="assets/libs2/custom/sweet-alert.js"></script>
      
      <script>
        $(document).ready(function () {
            const payAmtInput = $('#pay_amt');
            const payButton = $('#pay');
            const availableBalance = parseFloat(<?php echo $availableBalance; ?>);

            // Validation Logic (Kept exactly as yours)
            const formFields = [
                { id: 'bank', errorId: 'bankError', minLength: 3, maxLength: 50, pattern: /^[A-Za-z\s.'-]{2,50}$/, message: 'Please enter a valid bank name (letters only, min 3 chars).' },
                { id: 'bankadd', errorId: 'bankAddError', minLength: 5, maxLength: 100, pattern: /^[A-Za-z0-9\s.,'#&-]{5,100}$/, message: 'Please enter a valid bank address (min 5 chars).' },
                { id: 'rname', errorId: 'rnameError', minLength: 3, maxLength: 60, pattern: /^[A-Za-z\s.'-]{3,60}$/, message: 'Please enter a valid name (min 3 characters).' },
                { id: 'acctno', errorId: 'acctnoError', minLength: 10, maxLength: 15, pattern: /^\d{10,15}$/, message: 'Account number must be 10-15 digits.' },
                { id: 'swift', errorId: 'swiftError', minLength: 8, maxLength: 11, pattern: /^[A-Z0-9]{8,11}$/i, message: 'SWIFT/ABA number must be 8 or 11 alphanumeric characters.' },
                { id: 'pay_amt', errorId: 'amountError', message: '' } 
            ];

            function showError(element, message) {
                const errorSpan = $(`#${element.data('error-id')}`);
                errorSpan.text(message).show();
                element.addClass('is-invalid');
            }

            function hideError(element) {
                const errorSpan = $(`#${element.data('error-id')}`);
                errorSpan.text('').hide();
                element.removeClass('is-invalid').addClass('is-valid');
            }

            function formatAmount(number) {
                return number.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            }

            function cleanInput(value) {
                return value.replace(/,/g, '');
            }

            function validateField(fieldConfig) {
                const element = $(`#${fieldConfig.id}`);
                const value = element.val().trim();

                if (value === '') {
                    showError(element, 'This field is required.');
                    return false;
                }
                if (value.length < fieldConfig.minLength) {
                    showError(element, `Please enter at least ${fieldConfig.minLength} characters.`);
                    return false;
                }
                if (fieldConfig.pattern && !fieldConfig.pattern.test(value)) {
                    showError(element, fieldConfig.message);
                    return false;
                }
                
                hideError(element);
                return true;
            }

            function validateAmount() {
                const cleanedValue = cleanInput(payAmtInput.val());
                const parsedValue = parseFloat(cleanedValue);
                payAmtInput.data('unformatted', cleanedValue);

                if (cleanedValue === '') {
                    showError(payAmtInput, 'Please enter an amount.');
                    return false;
                }
                if (isNaN(parsedValue)) {
                    showError(payAmtInput, 'Please enter a valid number.');
                    return false;
                }
                if (parsedValue <= 0) {
                    showError(payAmtInput, 'Amount must be greater than 0.');
                    return false;
                }
                if (parsedValue > availableBalance) {
                    showError(payAmtInput, 'Entered amount exceeds available balance.');
                    return false;
                }

                hideError(payAmtInput);
                return true;
            }

            function checkFormValidity() {
                let isFormValid = true;
                formFields.forEach(field => {
                    const element = $(`#${field.id}`);
                    if (element.data('touched')) {
                        let isValid;
                        if (field.id === 'pay_amt') {
                            isValid = validateAmount();
                        } else {
                            isValid = validateField(field);
                        }
                        if (!isValid) { isFormValid = false; }
                    } else {
                        if (element.val().trim() === '' || (field.id === 'pay_amt' && cleanInput(element.val()) === '')) {
                            isFormValid = false;
                        }
                    }
                });
                payButton.prop('disabled', !isFormValid);
                return isFormValid;
            }
            
            formFields.forEach(field => {
                const element = $(`#${field.id}`);
                element.data('error-id', field.errorId);

                element.on('blur', () => {
                    element.data('touched', true);
                    if (field.id === 'pay_amt') {
                        const cleanedValue = cleanInput(element.val());
                        const parsedValue = parseFloat(cleanedValue);
                        if (!isNaN(parsedValue) && cleanedValue !== '') {
                            element.val(formatAmount(parsedValue));
                        }
                    }
                    checkFormValidity();
                });

                element.on('input', () => {
                    if (element.data('touched')) { checkFormValidity(); } 
                    else { checkFormValidity(); }
                });
            });

            payAmtInput.on('focus', function() {
                const cleanedValue = cleanInput($(this).val());
                if (!isNaN(parseFloat(cleanedValue))) {
                    $(this).val(parseFloat(cleanedValue));
                }
            });

            $('#transferForm').on('submit', function (e) {
                let isFormValid = true;
                formFields.forEach(field => {
                     const element = $(`#${field.id}`);
                     element.data('touched', true);
                     let isValid;
                     if (field.id === 'pay_amt') { isValid = validateAmount(); } 
                     else { isValid = validateField(field); }
                     if (!isValid) { isFormValid = false; }
                });

                if (!isFormValid) {
                    e.preventDefault();
                } else {
                    payAmtInput.val(parseFloat(payAmtInput.data('unformatted')));
                }
            });

            payButton.prop('disabled', true);
            $('.text-danger').hide();
        });
      </script>
   </body>
</html>