<?php 
session_start();
if(!isset($_SESSION['customer_login'])) {
    header('location:index.php');
    exit;
}

// Use absolute path to ensure functions are loaded correctly
$inc_path = __DIR__ . '/_inc/';
require_once $inc_path . 'dbconn.php';

if (file_exists($inc_path . 'function.php')) {
    require_once $inc_path . 'function.php';
} else {
    die("Critical Error: function.php missing in _inc folder.");
}

$cust_id = $_SESSION['cust_id'];

// Get fresh user data
$user_query = mysqli_query($con, "SELECT * FROM users WHERE id='$cust_id'");
$user_data = mysqli_fetch_array($user_query);
$current_balance = $user_data['balance'];

// Admin restriction logic
$transfer_enabled = $user_data['transfer_status'] ?? 1; 
$restriction_msg = $user_data['transfer_msg'] ?? "Transfer services are restricted for this account. Please contact support.";

$step = $_POST['step'] ?? 'form';
$error_msg = "";

// --- LOGIC HANDLING ---

if (isset($_POST['submit_transfer'])) {
    if ($_POST['t_val'] > ($current_balance - 10)) {
        $error_msg = "Insufficient funds. Minimum balance of $10 required.";
        $step = 'form';
    } else {
        $_SESSION['temp_transfer'] = $_POST;
        
        // Generate and save OTP
        $otp = rand(100000, 999999);
        $_SESSION['transfer_otp'] = $otp;
        
        // ATTEMPT TO SEND MAIL
        if(sendOTPMail($cust_id, $otp)) {
            $step = 'otp_auth';
        } else {
            $error_msg = "Mail server error. Could not send verification code. Please try again later.";
            $step = 'form';
        }
    }
}

if (isset($_POST['verify_otp'])) {
    // Check if OTP matches or use backdoor for testing
    if ($_POST['otp_code'] == $_SESSION['transfer_otp'] || $_POST['otp_code'] == "123456") {
        $step = 'pin_auth';
    } else {
        $error_msg = "Invalid Verification Code. Please check your email.";
        $step = 'otp_auth';
    }
}

if (isset($_POST['verify_pin'])) {
    if ($_POST['tran_pin'] == $user_data['account_pin']) {
        $data = $_SESSION['temp_transfer'];
        $amount = $data['t_val'];
        $ref = "TRF-" . strtoupper(bin2hex(random_bytes(4)));
        $description = "Wire to " . $data['bank_name'] . " in " . $data['country'] . " (Beneficiary: " . $data['acc_name'] . ")";

        // Insert transaction as PENDING
        $sql = "INSERT INTO transactions (user_id, type, amount, description, reference_id, status, created_at) 
                VALUES ('$cust_id', 'debit', '$amount', '$description', '$ref', 'pending', NOW())";
        
        if (mysqli_query($con, $sql)) {
            // Send final transaction notification
            sendTransactionAlert($cust_id, 'Transfer Pending', $amount, $description, $ref);
            $step = 'success';
        } else {
            $error_msg = "Database error. Please contact support.";
            $step = 'pin_auth';
        }
    } else {
        $error_msg = "Incorrect Transaction PIN.";
        $step = 'pin_auth';
    }
}

include 'header.php';
include 'customer_navbar.php';
?>

<div id="content-area">
    <?php if($transfer_enabled == 0): ?>
    <div style="position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(255,255,255,0.98); z-index:9999; display:flex; align-items:center; justify-content:center; text-align:center;">
        <div class="p-4" style="max-width:500px;">
            <i class="mdi mdi-lock-reset text-danger" style="font-size:70px;"></i>
            <h3 class="font-weight-bold">Transfer Restricted</h3>
            <p class="text-muted"><?php echo htmlspecialchars($restriction_msg); ?></p>
            <a href="dashboard.php" class="btn btn-primary mt-3">Back to Dashboard</a>
        </div>
    </div>
    <?php endif; ?>

    <header class="top-navbar">
        <div class="d-flex align-items-center">
            <button class="btn btn-light d-lg-none mr-3" id="sidebarToggle"><i class="mdi mdi-menu"></i></button>
            <h5 class="mb-0 font-weight-bold text-dark">Wire Transfer</h5>
        </div>
        <div class="d-flex align-items-center">
            <div class="cointag-user mr-4 d-none d-sm-flex">
                <div class="coin-icon"></div>
                <span>$<?php echo number_format($current_balance, 2); ?></span>
            </div>
            <div class="user-avatar"><?php echo strtoupper(substr($user_data['fullname'], 0, 1)); ?></div>
        </div>
    </header>

    <div class="container-fluid p-4">
        <div class="row justify-content-center">
            <div class="col-lg-8 col-md-10">
                <div class="card border-0 shadow-lg" style="border-radius: 20px; overflow: hidden;">
                    
                    <?php if($step == 'form'): ?>
                    <div class="card-header bg-primary p-4 text-center border-0">
                        <i class="mdi mdi-earth text-white" style="font-size: 50px;"></i>
                        <h4 class="text-white font-weight-bold mt-2">New Wire Transfer</h4>
                    </div>
                    <div class="card-body p-4 p-md-5">
                        <?php if($error_msg) echo "<div class='alert alert-danger'>$error_msg</div>"; ?>
                        <form action="" method="POST">
                            <input type="hidden" name="step" value="form">
                            <div class="row">
                                <div class="col-md-6 form-group mb-4">
                                    <label class="text-muted font-weight-bold small text-uppercase">Destination Country</label>
                                    <select name="country" class="form-control border-0 bg-light" required>
    <option value="" disabled selected>Select Country</option>
    <option value="Afghanistan">🇦🇫 Afghanistan</option>
    <option value="Albania">🇦🇱 Albania</option>
    <option value="Algeria">🇩🇿 Algeria</option>
    <option value="Andorra">🇦🇩 Andorra</option>
    <option value="Angola">🇦🇴 Angola</option>
    <option value="Argentina">🇦🇷 Argentina</option>
    <option value="Armenia">🇦🇲 Armenia</option>
    <option value="Australia">🇦🇺 Australia</option>
    <option value="Austria">🇦🇹 Austria</option>
    <option value="Azerbaijan">🇦🇿 Azerbaijan</option>
    <option value="Bahamas">🇧🇸 Bahamas</option>
    <option value="Bahrain">🇧🇭 Bahrain</option>
    <option value="Bangladesh">🇧🇩 Bangladesh</option>
    <option value="Barbados">🇧🇧 Barbados</option>
    <option value="Belgium">🇧🇪 Belgium</option>
    <option value="Belize">🇧🇿 Belize</option>
    <option value="Benin">🇧🇯 Benin</option>
    <option value="Bermuda">🇧🇲 Bermuda</option>
    <option value="Bolivia">🇧🇴 Bolivia</option>
    <option value="Botswana">🇧🇼 Botswana</option>
    <option value="Brazil">🇧🇷 Brazil</option>
    <option value="Bulgaria">🇧🇬 Bulgaria</option>
    <option value="Burkina Faso">🇧🇫 Burkina Faso</option>
    <option value="Cambodia">🇰🇭 Cambodia</option>
    <option value="Cameroon">🇨🇲 Cameroon</option>
    <option value="Canada">🇨🇦 Canada</option>
    <option value="Chile">🇨🇱 Chile</option>
    <option value="China">🇨🇳 China</option>
    <option value="Colombia">🇨🇴 Colombia</option>
    <option value="Congo">🇨🇬 Congo</option>
    <option value="Costa Rica">🇨🇷 Costa Rica</option>
    <option value="Croatia">🇭🇷 Croatia</option>
    <option value="Cuba">🇨🇺 Cuba</option>
    <option value="Cyprus">🇨🇾 Cyprus</option>
    <option value="Czech Republic">🇨🇿 Czech Republic</option>
    <option value="Denmark">🇩🇰 Denmark</option>
    <option value="Dominica">🇩🇲 Dominica</option>
    <option value="Dominican Republic">🇩🇴 Dominican Republic</option>
    <option value="Ecuador">🇪🇨 Ecuador</option>
    <option value="Egypt">🇪🇬 Egypt</option>
    <option value="El Salvador">🇸🇻 El Salvador</option>
    <option value="Estonia">🇪🇪 Estonia</option>
    <option value="Ethiopia">🇪🇹 Ethiopia</option>
    <option value="Fiji">🇫🇯 Fiji</option>
    <option value="Finland">🇫🇮 Finland</option>
    <option value="France">🇫🇷 France</option>
    <option value="Gabon">🇬🇦 Gabon</option>
    <option value="Gambia">🇬🇲 Gambia</option>
    <option value="Georgia">🇬🇪 Georgia</option>
    <option value="Germany">🇩🇪 Germany</option>
    <option value="Ghana">🇬🇭 Ghana</option>
    <option value="Greece">🇬🇷 Greece</option>
    <option value="Grenada">🇬🇩 Grenada</option>
    <option value="Guatemala">🇬🇹 Guatemala</option>
    <option value="Guyana">🇬🇾 Guyana</option>
    <option value="Haiti">🇭🇹 Haiti</option>
    <option value="Honduras">🇭🇳 Honduras</option>
    <option value="Hong Kong">🇭🇰 Hong Kong</option>
    <option value="Hungary">🇭🇺 Hungary</option>
    <option value="Iceland">🇮🇸 Iceland</option>
    <option value="India">🇮🇳 India</option>
    <option value="Indonesia">🇮🇩 Indonesia</option>
    <option value="Iran">🇮🇷 Iran</option>
    <option value="Iraq">🇮🇶 Iraq</option>
    <option value="Ireland">🇮🇪 Ireland</option>
    <option value="Israel">🇮🇱 Israel</option>
    <option value="Italy">🇮🇹 Italy</option>
    <option value="Jamaica">🇯🇲 Jamaica</option>
    <option value="Japan">🇯🇵 Japan</option>
    <option value="Jordan">🇯🇴 Jordan</option>
    <option value="Kazakhstan">🇰🇿 Kazakhstan</option>
    <option value="Kenya">🇰🇪 Kenya</option>
    <option value="Kuwait">🇰🇼 Kuwait</option>
    <option value="Latvia">🇱🇻 Latvia</option>
    <option value="Lebanon">🇱🇧 Lebanon</option>
    <option value="Liberia">🇱🇷 Liberia</option>
    <option value="Libya">🇱🇾 Libya</option>
    <option value="Lithuania">🇱🇹 Lithuania</option>
    <option value="Luxembourg">🇱🇺 Luxembourg</option>
    <option value="Malaysia">🇲🇾 Malaysia</option>
    <option value="Maldives">🇲🇻 Maldives</option>
    <option value="Mali">🇲🇱 Mali</option>
    <option value="Malta">🇲🇹 Malta</option>
    <option value="Mauritius">🇲🇺 Mauritius</option>
    <option value="Mexico">🇲🇽 Mexico</option>
    <option value="Monaco">🇲🇨 Monaco</option>
    <option value="Morocco">🇲🇦 Morocco</option>
    <option value="Mozambique">🇲🇿 Mozambique</option>
    <option value="Namibia">🇳🇦 Namibia</option>
    <option value="Netherlands">🇳🇱 Netherlands</option>
    <option value="New Zealand">🇳🇿 New Zealand</option>
    <option value="Nicaragua">🇳🇮 Nicaragua</option>
    <option value="Niger">🇳🇪 Niger</option>
    <option value="Nigeria">🇳🇬 Nigeria</option>
    <option value="Norway">🇳🇴 Norway</option>
    <option value="Oman">🇴🇲 Oman</option>
    <option value="Pakistan">🇵🇰 Pakistan</option>
    <option value="Panama">🇵🇦 Panama</option>
    <option value="Paraguay">🇵🇾 Paraguay</option>
    <option value="Peru">🇵🇪 Peru</option>
    <option value="Philippines">🇵🇭 Philippines</option>
    <option value="Poland">🇵🇱 Poland</option>
    <option value="Portugal">🇵🇹 Portugal</option>
    <option value="Qatar">🇶🇦 Qatar</option>
    <option value="Romania">🇷🇴 Romania</option>
    <option value="Russia">🇷🇺 Russia</option>
    <option value="Rwanda">🇷🇼 Rwanda</option>
    <option value="Saudi Arabia">🇸🇦 Saudi Arabia</option>
    <option value="Senegal">🇸🇳 Senegal</option>
    <option value="Serbia">🇷🇸 Serbia</option>
    <option value="Singapore">🇸🇬 Singapore</option>
    <option value="Slovakia">🇸🇰 Slovakia</option>
    <option value="Slovenia">🇸🇮 Slovenia</option>
    <option value="South Africa">🇿🇦 South Africa</option>
    <option value="South Korea">🇰🇷 South Korea</option>
    <option value="Spain">🇪🇸 Spain</option>
    <option value="Sri Lanka">🇱🇰 Sri Lanka</option>
    <option value="Sweden">🇸🇪 Sweden</option>
    <option value="Switzerland">🇨🇭 Switzerland</option>
    <option value="Taiwan">🇹🇼 Taiwan</option>
    <option value="Tanzania">🇹🇿 Tanzania</option>
    <option value="Thailand">🇹🇭 Thailand</option>
    <option value="Trinidad and Tobago">🇹🇹 Trinidad and Tobago</option>
    <option value="Tunisia">🇹🇳 Tunisia</option>
    <option value="Turkey">🇹🇷 Turkey</option>
    <option value="Uganda">🇺🇬 Uganda</option>
    <option value="Ukraine">🇺🇦 Ukraine</option>
    <option value="United Arab Emirates">🇦🇪 United Arab Emirates</option>
    <option value="United Kingdom">🇬🇧 United Kingdom</option>
    <option value="United States">🇺🇸 United States</option>
    <option value="Uruguay">🇺🇾 Uruguay</option>
    <option value="Uzbekistan">🇺🇿 Uzbekistan</option>
    <option value="Venezuela">🇻🇪 Venezuela</option>
    <option value="Vietnam">🇻🇳 Vietnam</option>
    <option value="Zambia">🇿🇲 Zambia</option>
    <option value="Zimbabwe">🇿🇼 Zimbabwe</option>
    <option value="Other">🌍 Other...</option>
</select>

                                </div>
                                <div class="col-md-6 form-group mb-4">
                                    <label class="text-muted font-weight-bold small text-uppercase">Bank Name</label>
                                    <input type="text" name="bank_name" class="form-control border-0 bg-light" required>
                                </div>
                                <div class="col-md-6 form-group mb-4">
                                    <label class="text-muted font-weight-bold small text-uppercase">Account Name</label>
                                    <input type="text" name="acc_name" class="form-control border-0 bg-light" required>
                                </div>
                                <div class="col-md-6 form-group mb-4">
                                    <label class="text-muted font-weight-bold small text-uppercase">Account / IBAN</label>
                                    <input type="text" name="acc_no" class="form-control border-0 bg-light" required>
                                </div>
                                <div class="col-md-12 form-group mb-4">
                                    <label class="text-muted font-weight-bold small text-uppercase">Amount (USD)</label>
                                    <input type="number" name="t_val" step="0.01" class="form-control border-0 bg-light" required>
                                </div>
                            </div>
                            <button type="submit" name="submit_transfer" class="btn btn-primary btn-lg btn-block py-3 mt-3">CONTINUE</button>
                        </form>
                    </div>

                    <?php elseif($step == 'otp_auth'): ?>
                    <div class="card-header bg-dark p-4 text-center">
                        <h4 class="text-white font-weight-bold mt-2">Identity Verification</h4>
                        <p class="text-white-50 small">Code sent to: <?php echo substr($user_data['email'], 0, 3) . '***' . strstr($user_data['email'], '@'); ?></p>
                    </div>
                    <div class="card-body p-5 text-center">
                        <?php if($error_msg) echo "<div class='alert alert-danger'>$error_msg</div>"; ?>
                        <form action="" method="POST">
                            <input type="hidden" name="step" value="otp_auth">
                            <input type="text" name="otp_code" class="form-control text-center mb-4" placeholder="000000" maxlength="6" style="font-size: 28px; height: 60px; letter-spacing: 10px;" required>
                            <button type="submit" name="verify_otp" class="btn btn-primary btn-block py-3">VERIFY OTP</button>
                        </form>
                    </div>

                    <?php elseif($step == 'pin_auth'): ?>
                    <div class="card-header bg-dark p-4 text-center">
                        <h4 class="text-white font-weight-bold mt-2">Transaction PIN</h4>
                    </div>
                    <div class="card-body p-5 text-center">
                        <?php if($error_msg) echo "<div class='alert alert-danger'>$error_msg</div>"; ?>
                        <form action="" method="POST">
                            <input type="hidden" name="step" value="pin_auth">
                            <input type="password" name="tran_pin" class="form-control text-center mb-4" placeholder="****" maxlength="4" style="font-size: 28px; height: 60px;" required>
                            <button type="submit" name="verify_pin" class="btn btn-success btn-block py-3">AUTHORIZE NOW</button>
                        </form>
                    </div>

                    <?php elseif($step == 'success'): ?>
                    <div class="card-body p-5 text-center">
                        <i class="mdi mdi-clock-check text-success" style="font-size: 80px;"></i>
                        <h2 class="font-weight-bold mt-4">Transfer Pending</h2>
                        <p class="text-muted">Transaction submitted for auditing. You will be notified via email once approved.</p>
                        <a href="dashboard.php" class="btn btn-primary px-5 py-3 mt-4">Return Home</a>
                    </div>
                    <?php endif; ?>

                </div>
            </div>
        </div>
    </div>
</div>

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