<?php
session_start();

error_reporting(0);
include("check_installation.php");
include("fetch_settings.php");

// Check if the user is authenticated, redirect if not
if (!isset($_SESSION["adminid"])) {
    header("Location: login.php");
    exit;
}

include("fetch_settings.php");

// --- Customer and Account Data Fetching ---
$custid = $_GET['custid'] ?? '';
$custname = '';
$email = ''; 


// Redirect if no custid is set (i.e., user didn't come from credit.php)
if (empty($custid)) {
    header("Location: credit_customer.php");
    exit;
}

if ($custid) {
    // Use prepared statements for secure database queries
    $stmt = $con->prepare("SELECT firstname, lastname, email, accounts.accountbalance FROM customers JOIN accounts ON customers.customerid = accounts.customerid WHERE customers.customerid = ?");
    $stmt->bind_param("i", $custid);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $custname = $row['firstname'] . " " . $row['lastname'];
        $email = $row['email'];
    }
    $stmt->close();
}

// --- Handle Form Submissions (Credit & Debit) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $transaction_amount = floatval(str_replace(',', '', $_POST['amount']));
    $transaction_custid = intval($_POST['custid']);
    $payment_date = $_POST['paymentdate'];
    
    // Define the dynamic variables
    $bank_name = $system_bank_name;
    $company_email = $system_email;
    
    $message = '';
    $status = 'error';
    $transaction_type = '';

    // Check for a valid customer ID and amount
    if (!$transaction_custid || $transaction_amount <= 0) {
        $message = 'Invalid amount or customer ID.';
        $_SESSION['credit_status'] = $status;
        $_SESSION['credit_message'] = $message;
        header("Location: credit.php?custid=$transaction_custid");
        exit;
    }

    $con->begin_transaction();
    try {
        if (isset($_POST['credit'])) {
            $transaction_type = 'Credit';
            // Securely insert into transactions table
            $stmt1 = $con->prepare("INSERT INTO transactions (cashier, type, paymentdate, receiveid, amount, paymentstat) VALUES (?, 'Credit', ?, ?, ?, 'active')");
            $stmt1->bind_param("isii", $_SESSION['adminid'], $payment_date, $transaction_custid, $transaction_amount);
            $stmt1->execute();
            $stmt1->close();

            // Securely insert into saved table
            $stmt2 = $con->prepare("INSERT INTO saved (userid, amount, status) VALUES (?, ?, 'active')");
            $stmt2->bind_param("ii", $transaction_custid, $transaction_amount);
            $stmt2->execute();
            $stmt2->close();
            
            // Securely update account balance
            $stmt3 = $con->prepare("UPDATE accounts SET accountbalance = accountbalance + ? WHERE customerid = ?");
            $stmt3->bind_param("di", $transaction_amount, $transaction_custid);
            $stmt3->execute();
            $stmt3->close();

            $message = 'Account Successfully Credited!';
            $status = 'success';

        } elseif (isset($_POST['debit'])) {
            $transaction_type = 'Debit';
            // Check if account has sufficient funds
            $stmt_balance = $con->prepare("SELECT accountbalance FROM accounts WHERE customerid = ?");
            $stmt_balance->bind_param("i", $transaction_custid);
            $stmt_balance->execute();
            $result_balance = $stmt_balance->get_result();
            $balance_row = $result_balance->fetch_assoc();
            $stmt_balance->close();
            $current_balance = $balance_row['accountbalance'];

            if ($current_balance < $transaction_amount) {
                throw new Exception("Insufficient funds. Cannot debit this amount.");
            }

            // Insert into transactions table (FIXED)
            $stmt1 = $con->prepare("INSERT INTO transactions (cashier, type, paymentdate, payeeid, amount, paymentstat) VALUES (?, 'Debit', ?, ?, ?, 'active')");
            $stmt1->bind_param("isii", $_SESSION['adminid'], $payment_date, $transaction_custid, $transaction_amount);
            $stmt1->execute();
            $stmt1->close();

            // Update account balance
            $stmt2 = $con->prepare("UPDATE accounts SET accountbalance = accountbalance - ? WHERE customerid = ?");
            $stmt2->bind_param("di", $transaction_amount, $transaction_custid);
            $stmt2->execute();
            $stmt2->close();

            $message = 'Account Successfully Debited!';
            $status = 'success';
        }

        $con->commit();

        // Fetch the updated balance for the email notification
        $stmt_updated_balance = $con->prepare("SELECT accountbalance FROM accounts WHERE customerid = ?");
        $stmt_updated_balance->bind_param("i", $transaction_custid);
        $stmt_updated_balance->execute();
        $result_updated = $stmt_updated_balance->get_result();
        $updated_row = $result_updated->fetch_assoc();
        $stmt_updated_balance->close();
        $updated_balance = $updated_row['accountbalance'] ?? 0;

        // --- Email Sending Logic ---
        
        $subj = htmlspecialchars($bank_name) . ' Transaction Alert'; 
        
        $mess = '<html><head><meta name="viewport" content="width=device-width"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link href="https://fonts.googleapis.com/css2?family=Mulish:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet"><title>Transaction Alert</title></head><body class="" style="background-color: #f6f6f6; font-family: sans-serif; -webkit-font-smoothing: antialiased; font-size: 14px; line-height: 1.4; margin: 0; padding: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;"><span class="preheader" style="color: transparent; display: none; height: 0; max-height: 0; max-width: 0; opacity: 0; overflow: hidden; mso-hide: all; visibility: hidden; width: 0;">' . htmlspecialchars($bank_name) . ' Transaction Alert.</span><table border="0" cellpadding="0" cellspacing="0" class="body" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; background-color: #f6f6f6;"><tr><td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">&nbsp;</td><td class="container" style="font-family: sans-serif; font-size: 14px; vertical-align: top; display: block; Margin: 0 auto; max-width: 580px; padding: 10px; width: 580px;"><div class="content" style="box-sizing: border-box; display: block; Margin: 0 auto; max-width: 580px; padding: 10px;"><table class="main" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; background: #ffffff; border-radius: 3px;"><tr><td class="wrapper" style="font-family: sans-serif; font-size: 14px; vertical-align: top; box-sizing: border-box; padding: 20px;"><table border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;"><tr><td style="font-family: sans-serif; font-size: 15px; vertical-align: top;"><p style="font-family: -apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif; font-size: 15px; font-weight: normal; margin: 0; Margin-bottom: 15px;">Dear, <b>' . htmlspecialchars($custname) . '</b></p><p style="font-family: "Mulish", sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">Your account has been ' . htmlspecialchars($transaction_type) . ' with <b>' . htmlspecialchars($cur) . '' . number_format($transaction_amount, 2) . '</b>.</p><p style="font-family: "Mulish", sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">You now have a total of: <b>' . htmlspecialchars($cur) . '' . number_format($updated_balance, 2) . '</b> in your account.</p>
        
        <p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">You can **login to your account** to view your balance.</p>
        
        <p></p><tbody><tr><td align="left" style="font-family: sans-serif; font-size: 14px; vertical-align: top; padding-bottom: 15px;">
        
        <br/><br/><p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">You can reach our 24/7 contact center ' . htmlspecialchars($bank_name) . ' Direct on the details below, livechat with us at www.' . htmlspecialchars($bank_name) . '.com or engage us via our social media platforms. We would happily respond to your quries.</p><p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">Thank you for Banking with us..</p></td></tr></tbody></table></td></tr></table></td></tr></table><div class="footer" style="clear: both; Margin-top: 10px; text-align: center; width: 100%;"><table border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;"><tr><td class="content-block" style="font-family: sans-serif; vertical-align: top; padding-bottom: 10px; padding-top: 10px; font-size: 15px; color: #888888; text-align: center;"><span class="apple-link" style="color: #999999; font-size: 12px; text-align: center;">© 2022 ' . htmlspecialchars($bank_name) . ' Bank (RC796975). All rights reserved.</span><br></td></tr><tr><td class="content-block powered-by" style="font-family: sans-serif; vertical-align: top; padding-bottom: 10px; padding-top: 10px; font-size: 15px; color: #666666; text-align: center;">Any views of this e-mail are those of the sender except where the sender specifically states them to be that of ' . htmlspecialchars($bank_name) . ' Plc or its subsidiaries. The message and its attachments are for designated recipient(s) only and may contain privileged, proprietary and private information. If you have received it in error, kindly delete it and notify the sender immediately. ' . htmlspecialchars($bank_name) . ' Plc accepts no liability for any loss or damage resulting directly and indirectly from the transmission of this e-mail message..</td></tr></table></div></div></td><td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">&nbsp;</td></tr></table></body></html>';

        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        
        $headers .= 'From: ' . htmlspecialchars($bank_name) . '<' . $company_email . '>' . "\r\n"; 
        if (!empty($email)) {
            mail($email, $subj, $mess, $headers);
        }
        
    } catch (Exception $e) {
        $con->rollback();
        $message = $e->getMessage();
    }
    // Set session variables to carry the message across the redirect
    $_SESSION['credit_status'] = $status;
    $_SESSION['credit_message'] = $message;
    // Redirect to the same page to prevent form resubmission
    header("Location: credit.php?custid=$transaction_custid");
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Dashboard</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="author" content="">
    <meta name="description" content="">
    <link rel="icon" href="../<?= htmlspecialchars($system_favicon); ?>" type="image/<?= pathinfo($system_favicon, PATHINFO_EXTENSION); ?>">
    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&amp;family=Poppins:wght@400;500;700&amp;display=swap">
    <link rel="stylesheet" type="text/css" href="assets/vendor/font-awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/flatpickr/css/flatpickr.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/bootstrap-icons/bootstrap-icons.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/overlay-scrollbar/css/overlayscrollbars.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/apexcharts/css/apexcharts.css">
    <link rel="stylesheet" type="text/css" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <style>
        .location-cell { white-space: pre-line; }
        
    </style>
</head>

<body>
<main>
    <?php include "include/sidebar.php" ?>
    <div class="page-content">
        <?php include "include/topbar.php" ?>
        <div class="page-content-wrapper p-xxl-4">
            <div class="row">
                <div class="col-12 mb-4 mb-sm-5">
                    <div class="d-sm-flex justify-content-between align-items-center">
                        <h1 class="h3 mb-2 mb-sm-0">Dashboard</h1>
                        <div class="d-grid"><a href="systemsettings.php" class="btn btn-primary-soft mb-0"><i class="bi bi-plus-lg fa-fw"></i> Manage Account</a></div>
                    </div>
                </div>
            </div>

            <div class="row g-4 mb-5">
                <div class="col-12">
                    <div class="card shadow">
                        <div class="card-header border-bottom">
                            <h5 class="card-title mb-0">Customer Account</h5>
                        </div>
                        <div class="card-body">
                            <div class="bg-light rounded p-3 d-none d-sm-block">
                                <div class="row row-cols-5 g-4">
                                    <div class="col"><h6 class="mb-0">Account No</h6></div>
                                    <div class="col"><h6 class="mb-0">Status</h6></div>
                                    <div class="col"><h6 class="mb-0">Open Date</h6></div>
                                    <div class="col"><h6 class="mb-0">Account Type</h6></div>
                                    <div class="col"><h6 class="mb-0">Balance</h6></div>
                                </div>
                            </div>
                            <?php
                            $stmt = $con->prepare("SELECT accno, accstatus, accopendate, accounttype, accountbalance FROM accounts WHERE customerid=?");
                            $stmt->bind_param("i", $custid);
                            $stmt->execute();
                            $resultsd = $stmt->get_result();
                            if ($resultsd && $resultsd->num_rows > 0) {
                                while ($arrow = $resultsd->fetch_assoc()) {
                                ?>
                                <div class="row row-cols-1 row-cols-sm-2 row-cols-md-5 g-4 align-items-center border-bottom px-2 py-4">
                                    <div class="col">
                                        <small class="d-block d-sm-none">Account No:</small>
                                        <h6 class="fw-light mb-0"><?= htmlspecialchars($arrow['accno']); ?></h6>
                                    </div>
                                    <div class="col">
    <small class="d-block d-sm-none">Status:</small>
    <?php 
        $status = strtolower($arrow['accstatus']); 
        $badgeClass = 'bg-secondary text-dark';    

        if ($status === 'active') {
            $badgeClass = 'bg-success bg-opacity-10 text-success';
        } elseif ($status === 'blocked') {
            $badgeClass = 'bg-danger bg-opacity-10 text-danger';
        } elseif ($status === 'onreview') {
            $badgeClass = 'bg-warning bg-opacity-10 text-warning';
        }
    ?>
    <div class="badge <?= $badgeClass; ?>">
        <?= htmlspecialchars($arrow['accstatus']); ?>
    </div>
</div>

                                    <div class="col">
                                        <small class="d-block d-sm-none">Open Date:</small>
                                        <h6 class="fw-normal mb-0"><?= htmlspecialchars($arrow['accopendate']); ?></h6>
                                    </div>
                                    <div class="col">
                                        <small class="d-block d-sm-none">Account Type:</small>
                                        <h6 class="fw-normal mb-0"><?= htmlspecialchars($arrow['accounttype']); ?></h6>
                                    </div>
                                    <div class="col">
                                        <small class="d-block d-sm-none">Balance:</small>
                                        <h6 class="fw-light mb-0 account-balance"><?= htmlspecialchars($cur) . " " . number_format($arrow['accountbalance'], 2); ?></h6>
                                    </div>
                                </div>
                                <?php
                                }
                            } else {
                                ?>
                                <div class="row px-2 py-4 text-center">
                                    <div class="col">
                                        <p class="mb-0">No customer accounts found.</p>
                                    </div>
                                </div>
                                <?php
                            }
                            $stmt->close();
                            ?>
                            <div class="text-end mt-3">
                                <button type="button" class="btn btn-primary-soft" data-bs-toggle="modal" data-bs-target="#creditModal">Credit Account</button>
                                <button type="button" class="btn btn-danger-soft" data-bs-toggle="modal" data-bs-target="#debitModal">Debit Account</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="creditModal" tabindex="-1" aria-labelledby="creditModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <form id="credit-form" method="post" action="credit.php?custid=<?= htmlspecialchars($custid); ?>">
                    <div class="modal-header">
                        <h5 class="modal-title" id="creditModalLabel">Credit User</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <input type="hidden" value="<?= htmlspecialchars($custid); ?>" name="custid">
                            <label class="form-label">Enter Amount To Credit</label>
                            <input type="text" step="0.01" name="amount" class="form-control amount-input" required>
                            <br>
                            <label class="form-label">Transaction Date</label>
                            <input type="datetime-local" name="paymentdate" class="form-control" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
                        <button name="credit" type="submit" class="btn btn-secondary">Credit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="debitModal" tabindex="-1" aria-labelledby="debitModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <form id="debit-form" method="post" action="credit.php?custid=<?= htmlspecialchars($custid); ?>">
                    <div class="modal-header">
                        <h5 class="modal-title" id="debitModalLabel">Debit User</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <input type="hidden" value="<?= htmlspecialchars($custid); ?>" name="custid">
                            <label class="form-label">Enter Amount To Debit</label>
                            <input type="text" step="0.01" name="amount" class="form-control amount-input" required>
                            <br>
                            <label class="form-label">Transaction Date</label>
                            <input type="datetime-local" name="paymentdate" class="form-control" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button name="debit" type="submit" class="btn btn-danger">Debit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</main>
<script src="assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/flatpickr/js/flatpickr.min.js"></script>
<script src="assets/vendor/overlay-scrollbar/js/overlayscrollbars.min.js"></script>
<script src="assets/vendor/apexcharts/js/apexcharts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script src="assets/js/functions.js"></script>

<script>
    // SweetAlert logic to display messages after full page reload
    <?php
    if (isset($_SESSION['credit_status']) && isset($_SESSION['credit_message'])) {
        $status = $_SESSION['credit_status'];
        $message = $_SESSION['credit_message'];
        echo "Swal.fire('" . ucfirst($status) . "!', '" . addslashes($message) . "', '" . $status . "');";
        // Clear the session variables to prevent the alert from showing on refresh
        unset($_SESSION['credit_status']);
        unset($_SESSION['credit_message']);
    }
    ?>
</script>

<script>
    document.querySelectorAll('.amount-input').forEach(function(amountInput) {
        amountInput.addEventListener('input', function(e) {
            let value = e.target.value;
            value = value.replace(/[^0-9.]/g, '');
            value = value.replace(/(\..*)\./g, '$1');
            if (value.startsWith('.')) {
                value = '0' + value;
            }
            const parts = value.split('.');
            parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            e.target.value = parts.join('.');
        });
    });
</script>

</body>
</html>