<?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");
require_once("../config/functions.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 ---
        
       // --- Email Sending Logic ---
        $to_email = $email;
        $fallback_cur = isset($cur) ? $cur : '$';
        $formatted_amount = $fallback_cur . number_format($transaction_amount, 2);
        $formatted_balance = $fallback_cur . number_format($updated_balance, 2);
        $current_year = date('Y');
        $txnRef = strtoupper(substr($transaction_type, 0, 3)) . rand(1000000, 9999999);
        
        // Dynamic styling based on Credit vs Debit
        $amount_color = ($transaction_type === 'Credit') ? '#198754' : '#dc3545';
        $amount_sign = ($transaction_type === 'Credit') ? '+' : '-';
        
        $subject = "Transaction Alert: Account " . $transaction_type . "ed";
        
        $body = "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <meta name='viewport' content='width=device-width, initial-scale=1.0'>
        </head>
        <body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f8fafc;'>
            <table width='100%' cellpadding='0' cellspacing='0' style='background-color: #f8fafc; padding: 40px 20px;'>
                <tr>
                    <td align='center'>
                        <table width='100%' cellpadding='0' cellspacing='0' style='max-width: 600px; background-color: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.05);'>
                            <tr>
                                <td style='background: linear-gradient(135deg, #003399 0%, #005D9D 100%); padding: 30px; text-align: center;'>
                                    <h1 style='color: #ffffff; margin: 0; font-size: 24px; font-weight: bold;'>$transaction_type Alert</h1>
                                </td>
                            </tr>
                            
                            <tr>
                                <td style='padding: 40px 30px; color: #0f172a; line-height: 1.6;'>
                                    <h2 style='margin-top: 0; color: #003399; font-size: 20px;'>Hello " . htmlspecialchars($custname) . ",</h2>
                                    <p style='font-size: 16px; color: #64748b;'>Your account has recently been <strong>" . strtolower($transaction_type) . "ed</strong> by our administration team. Below are the details of the transaction.</p>
                                    
                                    <div style='background-color: #e6efff; border-left: 4px solid #003399; padding: 20px; margin: 30px 0; border-radius: 0 8px 8px 0;'>
                                        <h3 style='margin-top: 0; color: #003399; font-size: 16px; text-transform: uppercase; letter-spacing: 1px;'>Transaction Details</h3>
                                        <table width='100%' cellpadding='8' cellspacing='0' style='font-size: 15px;'>
                                            <tr>
                                                <td width='40%' style='color: #64748b; font-weight: bold; border-bottom: 1px solid #cce0ff;'>Action:</td>
                                                <td style='color: #0f172a; font-weight: bold; border-bottom: 1px solid #cce0ff; text-align: right;'>$transaction_type</td>
                                            </tr>
                                            <tr>
                                                <td style='color: #64748b; font-weight: bold; border-bottom: 1px solid #cce0ff;'>Amount:</td>
                                                <td style='color: $amount_color; font-weight: bold; border-bottom: 1px solid #cce0ff; text-align: right;'>$amount_sign$formatted_amount</td>
                                            </tr>
                                            <tr>
                                                <td style='color: #64748b; font-weight: bold; border-bottom: 1px solid #cce0ff;'>Date & Time:</td>
                                                <td style='color: #0f172a; font-weight: bold; border-bottom: 1px solid #cce0ff; text-align: right;'>$payment_date</td>
                                            </tr>
                                            <tr>
                                                <td style='color: #003399; font-weight: bold; border-bottom: 1px solid #cce0ff;'>Available Balance:</td>
                                                <td style='color: #003399; font-weight: bold; border-bottom: 1px solid #cce0ff; text-align: right;'>$formatted_balance</td>
                                            </tr>
                                            <tr>
                                                <td style='color: #64748b; font-weight: bold;'>Reference ID:</td>
                                                <td style='color: #0f172a; font-weight: bold; text-align: right;'>$txnRef</td>
                                            </tr>
                                        </table>
                                    </div>
                                    
                                    <p style='font-size: 16px; color: #64748b; margin-top: 30px;'>If you have any questions regarding this transaction, please contact our support team </p>
                                    <p style='font-size: 16px; color: #64748b;'>Thank you for banking with us,<br><strong style='color: #003399;'>The " . htmlspecialchars($bank_name) . " Team</strong></p>
                                </td>
                            </tr>
                            
                            <tr>
                                <td style='background-color: #f1f5f9; text-align: center; padding: 20px; font-size: 13px; color: #94a3b8;'>
                                    <p style='margin: 0;'>&copy; $current_year " . htmlspecialchars($bank_name) . " (RC796975). All rights reserved.</p>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </body>
        </html>
        ";

        if (!empty($to_email)) {
            // Using your custom sendMail function as requested
            sendMail($to_email, $subject, $body);
        }
        
    } 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>