<?php
include("../db/cn.php");
include("common/tx.php");
ob_start();
session_start(); // <-- Uncommented, now sessions work

if (isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name']) && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
} else {
    // Fallback if not logged in (optional)
    $userName = $userRole = $outlet_address = $outlet_name = '';
}

// Handle Delete Action
if (isset($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);
    $deleteQuery = "DELETE FROM credit_paid WHERE id = $delete_id";
    if (mysqli_query($connection, $deleteQuery)) {
        echo "<script>alert('Record deleted successfully!'); window.location.href='credit_rec.php';</script>";
    } else {
        echo "<script>alert('Error deleting record: " . mysqli_error($connection) . "');</script>";
    }
}

// Handle Insert & Update balance (only on POST)
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["creditor_paid"])) {
    $date_time = $_POST["date_time"] ?? date("Y-m-d");
    $cr_name = $_POST["cr_name"];
    $amount = $_POST["amount"];
    $paid_by = $_POST["paid_by"];
    $description = $_POST["desc"];

    $insertQuery = "
        INSERT INTO credit_paid (cr_name, amount, paid_by, description, date_time, user_name, user_role, outlet_name, outlet_address)
        VALUES ('$cr_name', '$amount', '$paid_by', '$description', '$date_time', '$userName', '$userRole', '$outlet_name', '$outlet_address')
    ";

    if (mysqli_query($connection, $insertQuery)) {
        // Update remaining balance – now inside POST block
        mysqli_query(
            $connection,
            "UPDATE creditor_closing 
             SET remain_balance = remain_balance - $amount
             WHERE creditor_name = '$cr_name'"
        );
        echo "<script>alert('Amount received successfully!'); window.location.href='credit_rec.php';</script>";
    } else {
        echo "<script>alert('Error: " . mysqli_error($connection) . "');</script>";
    }
}

// Fetch received amounts
$receivedAmounts = mysqli_query($connection, "SELECT * FROM credit_paid ORDER BY id DESC");

// Payment method display mapping
$methodNames = [
    'cash'   => 'Cash',
    'bank1'  => 'Ibrahim Meezan',
    'bank2'  => 'Adil Meezan',
    'bank3'  => 'HBL Bank',
    'bank4'  => 'JazzCash',
    'other'  => 'Other'
];

ob_end_flush();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>WholeSale Retail </title>

    <!-- Fonts & CSS -->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@300;500;700&display=swap" rel="stylesheet">
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/sb-admin-2.css" rel="stylesheet">

    <style>
        body { font-family: 'Quicksand', sans-serif; }
        .bg-gradient-primary { background: #0A4657; color: #fff; }
        .btn-primary { background: #0A4657; border: 1px solid #0A4657; }
        .btn-primary:hover { background: #fff; color: #0A4657; }
        .card { border-radius: 12px; }
        .card-header { background: #0A4657; color: white; }
        #table-container { max-height: 650px; overflow-y: auto; }
        table { font-size: 14px; }
        th { background: #0A4657; color: white; }
        .form-control, .btn, option { font-weight:700; text-transform:capitalize; }
    </style>
</head>

<body id="page-top">
    <div id="wrapper">
        <!-- Sidebar -->
        <?php include("common/sd.php"); ?>
        <!-- End of Sidebar -->

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <!-- Topbar -->
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">
                    <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                        <i class="fa fa-bars"></i>
                    </button>
                    <?php include('common/log.php'); ?>
                </nav>
                <!-- End of Topbar -->

                <!-- Page Content -->
                <div class="container-fluid mt-3">
                    <div class="row justify-content-center">
                        <!-- Form Section -->
                        <div class="col-md-4 mb-1">
                            <div class="card shadow">
                                <div class="card-header">
                                    <h5 class="mb-0 font-weight-bold">Add Received Amount</h5>
                                </div>
                                <div class="card-body">
                                    <form method="post" action="credit_rec.php" enctype="multipart/form-data" id="credit-form">
                                        <!-- Customer Select -->
                                        <div class="form-group mb-3">
                                            <label class="font-weight-bold">Select Customer</label>
                                            <select name="cr_name" class="form-control" required>
                                                <option value="">-- Select Customer --</option>
                                                <?php
                                                $getCustomers = mysqli_query($connection, "SELECT DISTINCT cr_name FROM credit_note ORDER BY cr_name ASC");
                                                while ($row = mysqli_fetch_assoc($getCustomers)) {
                                                    echo '<option value="' . htmlspecialchars($row['cr_name']) . '">' . htmlspecialchars($row['cr_name']) . '</option>';
                                                }
                                                ?>
                                            </select>
                                        </div>

                                        <!-- Amount -->
                                        <div class="form-group mb-3">
                                            <label class="font-weight-bold">Amount</label>
                                            <input type="number" name="amount" placeholder="Enter Amount" class="form-control" required>
                                        </div>

                                        <!-- Payment Method -->
                                        <div class="form-group mb-3">
                                            <label class="font-weight-bold">Payment Method</label>
                                            <select name="paid_by" class="form-control" required>
                                                <option value="">-- Select Method --</option>
                                                <option value="cash">Cash</option>
                                                <option value="bank1">Ibrahim Meezan</option>
                                                <option value="bank2">Adil Meezan</option>
                                                <option value="bank3">HBL Bank</option>
                                                <option value="bank4">JazzCash</option>
                                                <option value="other">Other</option>
                                            </select>
                                        </div>

                                        <!-- Description -->
                                        <div class="form-group mb-3">
                                            <label class="font-weight-bold">Description</label>
                                            <textarea name="desc" class="form-control" placeholder="Enter description..." rows="3"></textarea>
                                        </div>

                                        <!-- Date -->
                                        <div class="form-group mb-3">
                                            <label class="font-weight-bold">Date</label>
                                            <input class="form-control" type="date" name="date_time" required value="<?= date('Y-m-d'); ?>" />
                                        </div>

                                        <!-- Submit -->
                                        <button type="submit" name="creditor_paid" class="btn btn-dark btn-block">Enter</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <!-- Table Section -->
                        <div class="col-md-7">
                            <div class="card-header">
                                <h5 class="mb-0 font-weight-bold">View Amount Received</h5>
                            </div>
                            <div class="card-body p-2" id="table-container">
                                <table class="table table-striped table-hover text-center">
                                    <thead>
                                        <tr style="font-size:13px;">
                                            <th>Date</th>
                                            <th>Customer</th>
                                            <th>Amount (Rs)</th>
                                            <th>Method</th>
                                            <th>Description</th>
                                            <th>Received By</th>
                                            <th>Edit</th>
                                            <th>Delete</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        while ($row = mysqli_fetch_assoc($receivedAmounts)) { 
                                            $displayMethod = $methodNames[$row['paid_by']] ;
                                        ?>
                                            <tr class="text-capitalize font-weight-bold">
                                                <td><?= htmlspecialchars($row['date_time']); ?></td>
                                                <td><?= htmlspecialchars($row['cr_name']); ?></td>
                                                <td><?= htmlspecialchars($row['amount']); ?></td>
                                                <td ><?= $displayMethod; ?></td>
                                                <td><?= htmlspecialchars($row['description']); ?></td>
                                                <td><?= htmlspecialchars($row['user_name']); ?></td>
                                                <td>
                                                    <a href="edit_credit_rec.php?id=<?= $row['id']; ?>" class="btn btn-sm btn-primary mr-1">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                </td>
                                                <td>
                                                    <a href="?delete_id=<?= $row['id']; ?>" class="btn btn-sm btn-danger" 
                                                       onclick="return confirm('Are you sure you want to delete this record?');">
                                                        <i class="fas fa-trash-alt"></i>
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- /.container-fluid -->
            </div>

            <!-- Footer -->
            <?php include("common/main_ft.php"); ?>
        </div>
    </div>

    <!-- Scroll to Top -->
    <a class="scroll-to-top rounded" href="#page-top"><i class="fas fa-angle-up"></i></a>

    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const form = document.getElementById("credit-form");
            const customerSelect = form.querySelector("select[name='cr_name']");

            if (performance.getEntriesByType("navigation")[0].type === "reload" ||
                performance.getEntriesByType("navigation")[0].type === "navigate") {
                customerSelect.focus();
            }

            form.addEventListener("submit", function() {
                setTimeout(() => {
                    customerSelect.focus();
                }, 100);
            });
        });
    </script>

    <!-- Scripts -->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="../js/sb-admin-2.min.js"></script>
</body>
</html>