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

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

// Helper Functions
function getAccountDetails($con, $customerId) {
    $stmt = $con->prepare("SELECT * FROM accounts WHERE customerid=?");
    $stmt->bind_param("s", $customerId);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}

function getCustomerDetails($con, $customerId) {
    $stmt = $con->prepare("SELECT * FROM customers WHERE customerid=?");
    $stmt->bind_param("s", $customerId);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}

// Get account and customer details
$custid = $_SESSION['customerid'];
$accountDetails = getAccountDetails($con, $custid);
$customerDetails = getCustomerDetails($con, $custid);
$availableBalance = $accountDetails['accountbalance'];

// System Settings
$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();
   }
}

// Handle Final Transfer Submission
if (isset($_POST["confirmTransfer"])) {
    $pin = $_POST['pin'];
    $amount = $_POST['amount'];
    $receiverAccount = $_POST['receiver_account'];
    $receiverName = $_POST['receiver_name'];
    $receiverBank = $_POST['receiver_bank'];
    $senderAccount = $_POST['sender_account'];
    
    // Verify PIN
    if ($pin === $customerDetails['transpassword']) {
        // Check balance
        if ($amount > $availableBalance) {
            echo "<script>
                document.addEventListener('DOMContentLoaded', function() {
                    Swal.fire({
                        icon: 'error',
                        title: 'Insufficient Balance',
                        text: 'You do not have enough funds for this transfer.',
                        confirmButtonColor: '#003399'
                    }).then(() => {
                        window.location = 'local-transfer.php';
                    });
                });
            </script>";
        } else {
            $con->begin_transaction();
            
            try {
                $dt = date('Y-m-d H:i:s');
                
                // 1. Insert transaction
                $stmt1 = $con->prepare("INSERT INTO transactions (type, paymentdate, payeeid, receiveid, amount, paymentstat) VALUES (?, ?, ?, ?, ?, ?)");
                $type = 'Transfer';
                $paymentstat = 'active';
                $stmt1->bind_param("ssisss", $type, $dt, $custid, $receiverAccount, $amount, $paymentstat);
                $stmt1->execute();
                
                // 2. Deduct from sender
                $stmt2 = $con->prepare("UPDATE accounts SET accountbalance = accountbalance - ? WHERE customerid = ?");
                $stmt2->bind_param("ds", $amount, $custid);
                $stmt2->execute();
                
                // 3. Add to receiver (if internal account exists)
                $stmt3 = $con->prepare("UPDATE accounts SET accountbalance = accountbalance + ? WHERE accno = ?");
                $stmt3->bind_param("ds", $amount, $receiverAccount);
                $stmt3->execute();
                
                $con->commit();
                
                // Success
                $txnRef = 'TXN' . rand(1000000, 9999999);
                echo '
                <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
                <script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.5.1/dist/confetti.browser.min.js"></script>
                <script>
                document.addEventListener("DOMContentLoaded", function() {
                    function launchConfetti() {
                        var duration = 2 * 1000;
                        var animationEnd = Date.now() + duration;
                        var defaults = { startVelocity: 30, spread: 360, ticks: 60, zIndex: 2000 };
                        function randomInRange(min, max) { return Math.random() * (max - min) + min; }
                        var interval = setInterval(function() {
                            var timeLeft = animationEnd - Date.now();
                            if (timeLeft <= 0) return clearInterval(interval);
                            var particleCount = 50 * (timeLeft / duration);
                            confetti(Object.assign({}, defaults, { origin: { x: randomInRange(0.1, 0.9), y: Math.random() - 0.2 } }));
                        }, 250);
                    }
                    Swal.fire({
                        title: "Transfer Successful!",
                        html: `
                            <div>
                                <div style="font-size: 1.5em; font-weight: bold; text-align: center; color: #003399; margin-bottom: 15px;">
                                    Amount: ' . htmlspecialchars($cur) . number_format($amount, 2) . '
                                </div>
                                <div style="border-top: 1px solid #e5e7eb; margin: 15px 0;"></div>
                                <div style="display: flex; flex-direction: column; gap: 10px; color: #4b5563;">
                                    <div style="display: flex; align-items: center; justify-content: space-between;">
                                        <span style="font-weight: 600;">Beneficiary:</span>
                                        <div style="text-align: right;">' . htmlspecialchars($receiverName) . '</div>
                                    </div>
                                    <div style="display: flex; align-items: center; justify-content: space-between;">
                                        <span style="font-weight: 600;">Account:</span>
                                        <div style="text-align: right;">' . htmlspecialchars($receiverAccount) . '</div>
                                    </div>
                                    <div style="display: flex; align-items: center; justify-content: space-between;">
                                        <span style="font-weight: 600;">Bank:</span>
                                        <div style="text-align: right;">' . htmlspecialchars($receiverBank) . '</div>
                                    </div>
                                    <div style="display: flex; align-items: center; justify-content: space-between;">
                                        <span style="font-weight: 600;">Sender:</span>
                                        <div style="text-align: right;">' . htmlspecialchars($_SESSION["customername"]) . '</div>
                                    </div>
                                    <div style="display: flex; align-items: center; justify-content: space-between;">
                                        <span style="font-weight: 600;">Ref:</span>
                                        <div style="text-align: right;">' . $txnRef . '</div>
                                    </div>
                                </div>
                                <div style="text-align: center; margin-top: 20px;">
                                    <button onclick="window.print()" style="background-color: transparent; color: #003399; border: 2px solid #003399; padding: 10px 20px; border-radius: 8px; font-weight: 600;">
                                        Print Receipt
                                    </button>
                                </div>
                            </div>
                        `,
                        icon: "success",
                        confirmButtonText: "Done",
                        confirmButtonColor: "#003399",
                        allowOutsideClick: false,
                        didOpen: () => { launchConfetti(); }
                    }).then(() => {
                        window.location = "dashboard.php";
                    });
                });
                </script>';
                exit();
            } catch (mysqli_sql_exception $e) {
                $con->rollback();
                echo "<script>
                    document.addEventListener('DOMContentLoaded', function() {
                        Swal.fire({
                            icon: 'error',
                            title: 'Transfer Failed',
                            text: 'An error occurred. Please try again.',
                            confirmButtonColor: '#003399'
                        });
                    });
                </script>";
            }
        }
    } else {
        echo "<script>
            document.addEventListener('DOMContentLoaded', function() {
                Swal.fire({
                    icon: 'error',
                    title: 'Wrong PIN',
                    text: 'The PIN you entered is incorrect.',
                    confirmButtonColor: '#003399'
                }).then(() => {
                    window.location = 'local-transfer.php';
                });
            });
        </script>";
    }
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Local Transfer | <?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" rel="stylesheet" type="text/css" />
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/app.min.css" rel="stylesheet" type="text/css" />
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    
    <style>
        :root {
            --primary-blue: #003399;
            --dark-blue: #005D9D;
            --soft-blue-bg: #e6efff;
            --bg-body: #f8fafc;
            --text-main: #0f172a;
            --text-secondary: #64748b;
        }
        
        body {
            font-family: 'Plus Jakarta Sans', sans-serif;
            background-color: var(--bg-body);
            color: var(--text-main);
        }
        
        .page-content { padding-top: 80px; padding-bottom: 60px; }
        
        .transfer-card {
            background: white;
            border-radius: 24px;
            border: none;
            box-shadow: 0 10px 30px rgba(0,0,0,0.08);
            overflow: hidden;
        }
        
        .transfer-header {
            background: linear-gradient(135deg, #001a4d, var(--primary-blue));
            padding: 40px;
            text-align: center;
            color: white;
            position: relative;
        }
        
        .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;
        }
        
        .card-body { padding: 40px; }
        
        .form-floating > .form-control,
        .form-floating > .form-select {
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            height: 58px;
            color: #000000;
            font-weight: 700;
        }
        
        .form-floating > .form-control:focus,
        .form-floating > .form-select:focus {
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 4px var(--soft-blue-bg);
        }
        
        .form-floating > label {
            color: #000000;
            font-weight: 700;
        }
        
        .btn-primary {
            background: var(--primary-blue);
            border: none;
            border-radius: 12px;
            padding: 16px;
            font-weight: 700;
            box-shadow: 0 4px 12px rgba(0, 51, 153, 0.3);
            transition: all 0.3s;
            font-size: 1.1rem;
        }
        
        .btn-primary:hover {
            background: var(--dark-blue);
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(0, 51, 153, 0.4);
        }
        
        .btn-outline-secondary {
            border: 2px solid #e2e8f0;
            color: var(--text-secondary);
            border-radius: 12px;
            padding: 16px;
            font-weight: 700;
            transition: all 0.3s;
        }
        
        .btn-outline-secondary:hover {
            background: #f8fafc;
            border-color: var(--primary-blue);
            color: var(--primary-blue);
        }
        
        .summary-box {
            background: #f8fafc;
            border-radius: 16px;
            padding: 24px;
            margin-bottom: 24px;
        }
        
        .summary-item {
            display: flex;
            justify-content: space-between;
            padding: 12px 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .summary-item:last-child {
            border-bottom: none;
        }
        
        .summary-label {
            color: var(--text-secondary);
            font-weight: 600;
        }
        
        .summary-value {
            color: var(--text-main);
            font-weight: 700;
            text-align: right;
        }
        
        .pin-input {
            text-align: center;
            font-size: 1.5rem;
            letter-spacing: 0.5rem;
        }
        
        @media (max-width: 768px) {
            .transfer-header { padding: 30px 20px; }
            .card-body { padding: 30px 20px; }
        }
    </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">Local Transfer</h4>
                                    <p class="text-secondary mb-0">Send money to local bank accounts</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" style="color: var(--primary-blue);">Transfer</li>
                                        </ol>
                                    </nav>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row justify-content-center">
                        <div class="col-12 col-lg-8">
                            <div class="transfer-card">
                                
                                <div class="transfer-header">
                                    <h4 class="text-white mb-2 fw-bold">Hello, <?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 id="transferForm" <?php echo isset($_POST['proceed']) ? 'style="display:none;"' : ''; ?>>
                                        <form method="post" action="" id="mainTransferForm">
                                            <div class="row g-4">
                                                
                                                <div class="col-12">
                                                    <div class="form-floating">
                                                        <input type="text" class="form-control" name="receiver_account" id="receiver_account" placeholder="Account Number" required>
                                                        <label for="receiver_account">Receiver's Account Number</label>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-12">
                                                    <div class="form-floating">
                                                        <input type="text" class="form-control" name="receiver_name" id="receiver_name" placeholder="Account Name" required>
                                                        <label for="receiver_name">Receiver's Account Name</label>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-12">
                                                    <div class="form-floating">
                                                        <input type="number" step="0.01" class="form-control" name="amount" id="amount" placeholder="Amount" required>
                                                        <label for="amount">Amount to Transfer</label>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-12">
                                                    <div class="form-floating">
                                                        <input type="text" class="form-control" name="receiver_bank" id="receiver_bank" placeholder="Receiver's Bank Name" required>
                                                        <label for="receiver_bank">Receiver's Bank Name</label>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-12">
                                                    <div class="form-floating">
                                                        <select class="form-select" name="sender_account" id="sender_account" required>
                                                            <?php 
                                                            $stmt_accounts = $con->prepare("SELECT accno FROM accounts WHERE customerid=?");
                                                            $stmt_accounts->bind_param("s", $custid);
                                                            $stmt_accounts->execute();
                                                            $result_accounts = $stmt_accounts->get_result();
                                                            while ($acc = $result_accounts->fetch_assoc()) {
                                                                echo "<option value='".htmlspecialchars($acc['accno'])."'>".htmlspecialchars($acc['accno'])."</option>";
                                                            }
                                                            $stmt_accounts->close();
                                                            ?>
                                                        </select>
                                                        <label for="sender_account">From Account (Your Account)</label>
                                                    </div>
                                                </div>
                                                
                                            </div>
                                            
                                            <div class="mt-4 d-grid">
                                                <button type="submit" name="proceed" id="proceedBtn" class="btn btn-primary btn-lg">Proceed</button>
                                            </div>
                                        </form>
                                    </div>
                                    
                                    <?php if (isset($_POST['proceed'])): ?>
                                    <div id="confirmationForm">
                                        <h5 class="mb-4 fw-bold">Confirm Transfer Details</h5>
                                        
                                        <div class="summary-box">
                                            <div class="summary-item">
                                                <span class="summary-label">Amount:</span>
                                                <span class="summary-value"><?php echo htmlspecialchars($cur) . ' ' . number_format($_POST['amount'], 2); ?></span>
                                            </div>
                                            <div class="summary-item">
                                                <span class="summary-label">To Account:</span>
                                                <span class="summary-value"><?php echo htmlspecialchars($_POST['receiver_account']); ?></span>
                                            </div>
                                            <div class="summary-item">
                                                <span class="summary-label">Account Name:</span>
                                                <span class="summary-value"><?php echo htmlspecialchars($_POST['receiver_name']); ?></span>
                                            </div>
                                            <div class="summary-item">
                                                <span class="summary-label">To Bank:</span>
                                                <span class="summary-value"><?php echo htmlspecialchars($_POST['receiver_bank']); ?></span>
                                            </div>
                                            <div class="summary-item">
                                                <span class="summary-label">From Account:</span>
                                                <span class="summary-value"><?php echo htmlspecialchars($_POST['sender_account']); ?></span>
                                            </div>
                                        </div>
                                        
                                        <form method="post" action="">
                                            <input type="hidden" name="amount" value="<?php echo htmlspecialchars($_POST['amount']); ?>">
                                            <input type="hidden" name="receiver_account" value="<?php echo htmlspecialchars($_POST['receiver_account']); ?>">
                                            <input type="hidden" name="receiver_name" value="<?php echo htmlspecialchars($_POST['receiver_name']); ?>">
                                            <input type="hidden" name="receiver_bank" value="<?php echo htmlspecialchars($_POST['receiver_bank']); ?>">
                                            <input type="hidden" name="sender_account" value="<?php echo htmlspecialchars($_POST['sender_account']); ?>">
                                            
                                            <div class="form-floating mb-4">
                                                <input type="password" class="form-control pin-input" name="pin" id="pin" placeholder="Enter PIN" maxlength="4" required>
                                                <label for="pin">Enter Your 4-Digit PIN</label>
                                            </div>
                                            
                                            <div class="d-grid gap-2">
                                                <button type="submit" name="confirmTransfer" class="btn btn-primary btn-lg">Confirm Transfer</button>
                                                <button type="button" onclick="window.location='local-transfer.php'" class="btn btn-outline-secondary">Cancel</button>
                                            </div>
                                        </form>
                                    </div>
                                    <?php endif; ?>
                                    
                                </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="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
</body>
</html>