<?php
include("db/cn.php");
include('common/tx.php');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ob_start();

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 {
    echo '<script type="text/javascript">window.location.href="logout.php";</script>';
    exit();
}

// --- Handle Supplier Paid Insert ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["supplier_paid"])) {
    $date_time = $_POST["date_time"] ?? date("Y-m-d");
    $supplier = $_POST["supplier_name"];
    $amount = $_POST["supplier_amount"];
    $description = $_POST["description"];
    $status = $_POST["status"];

    $query = "INSERT INTO supplier_paid(supplier_name, supplier_amount, status, description, date_time, user_name, user_role, outlet_name, outlet_address)
              VALUES ('$supplier', '$amount', '$status', '$description', '$date_time', '$userName', '$userRole', '$outlet_name', '$outlet_address')";

    if (mysqli_query($connection, $query)) {
        echo "<script>
                Swal.fire({icon:'success', title:'Supplier payment added + ledger Update successfully!', timer:2000, showConfirmButton:false});
                setTimeout(() => { window.location.href='credit_pay.php?supplier_name=$supplier'; }, 2000);
              </script>";
    } else {
        echo "<script>alert('Error: " . mysqli_error($connection) . "');</script>";
    }
    
    mysqli_query($connection,"UPDATE supplier_closing SET closing_balance = closing_balance - $amount 
    where supplier_name = '$supplier'");
}

// --- Handle Delete Supplier Payment ---
if (isset($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);
    $deleteQuery = "DELETE FROM supplier_paid WHERE id = $delete_id";
    if (mysqli_query($connection, $deleteQuery)) {
        echo "<script>
                Swal.fire({icon:'success', title:'Record deleted!', timer:1500, showConfirmButton:false});
                setTimeout(() => { window.location.href='supplier_detail.php'; }, 1500);
              </script>";
    } else {
        echo "<script>alert('Error deleting record: " . mysqli_error($connection) . "');</script>";
    }
}

// --- Fetch Supplier Payments ---
$payments = mysqli_query($connection, "SELECT * FROM supplier_paid ORDER BY date_time DESC");

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><?php echo $tx; ?></title>

    <!-- CSS & Fonts -->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/sb-admin-2.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <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;
        }
        .scroll-table {
            max-height: 400px;
            overflow-y: auto;
            display: block;
        }
        .btn, .form-control, option{
            font-weight:700;
        }
    </style>
</head>

<body id="page-top">

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

    <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>

            <!-- Page Content -->
            <div class="container-fluid mt-5">
                <div class="row">
                    <div class="col-md-4">
                        <div class="card shadow">
                            <div class="card-header bg-gradient-primary text-white">
                                <h5 class="mb-0 font-weight-bold">Add Party Payment</h5>
                            </div>
                            <div class="card-body">
                                <form method="post" action="credit_pay.php" id="credit-form" >
                                    <div class="form-group">
                                        <label><strong>Select Party</strong></label>
                                        <select name="supplier_name" class="form-control" required>
                                            <option value="">-- Select Party --</option>
                                            <?php
                                            $suppliers = mysqli_query($connection, "SELECT DISTINCT supplier_name FROM supplier ORDER BY supplier_name ASC");
                                            while ($row = mysqli_fetch_assoc($suppliers)) {
                                                echo '<option value="' . htmlspecialchars($row['supplier_name']) . '">' . htmlspecialchars($row['supplier_name']) . '</option>';
                                            }
                                            ?>
                                        </select>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label><strong>Amount</strong></label>
                                        <input type="number" name="supplier_amount" placeholder="Enter Amount" class="form-control" required>
                                    </div>
                                    <div class="form-group">
                                        <label><strong>Payment Method</strong></label>
                                        <select name="status" class="form-control" required>
                                            <option value="">-- Select Method --</option>
                                            <option value="cash">Cash</option>
                                            <option style="font-weight:700;" value="bank1">Meezan Bank</option>
                                            <option style="font-weight:700;" value="bank2">Faysal Bank</option>
                                            <option style="font-weight:700;" value="bank3">Bank AL-Habib</option>
                                            <option value="other">Other</option>
                                        </select>
                                    </div>
                                     <div class="form-group">
                                        <label><strong>Description</strong></label>
                                        <textarea name="description" class="form-control" required>
                                            
                                        </textarea>
                                    </div>
                                    <div class="form-group">
                                        <label><strong>Date</strong></label>
                                        <input type="date" name="date_time" class="form-control" value="<?php echo date('Y-m-d'); ?>"  required>
                                    </div>
                                    <button type="submit" name="supplier_paid" class="btn btn-dark btn-block">Enter</button>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- Supplier Payments Table -->
                    <div class="col-md-8">
                        <div class="card ">
                            <div class="card-header bg-gradient-primary text-white">
                                <h5 class="mb-0 font-weight-bold">Party Payment History</h5>
                            </div>
                            <div class="card-body scroll-table">
                                <table class="table table-stripped  text-center">
                                    <thead>
                                        <tr>
                                            <th class="bg-dark text-white">Date</th>
                                            <th class="bg-dark text-white">Party</th>
                                            <th class="bg-dark text-white">Description</th>
                                            <th class="bg-dark text-white">Amount (Rs)</th>
                                            <th class="bg-dark text-white">Method</th>
                                            <th class="bg-dark text-white">Added By</th>
                                            <th class="bg-dark text-white">Edit</th>
                                            <th class="bg-dark text-white">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                        // Bank mapping array
                                        $bank_map = [
                                            'bank1' => 'Meezan Bank',
                                            'bank2' => 'Faysal Bank',
                                            'bank3' => 'Bank AL-Habib'
                                        ];

                                        while ($row = mysqli_fetch_assoc($payments)) {
                                            // Map stored bank code to full name for display
                                            $paid_method_display = isset($bank_map[$row['status']]) ? $bank_map[$row['status']] : $row['status'];
                                        ?>
                                            <tr class="font-weight-bold text-capitalize">
                                                <td><?= htmlspecialchars($row['date_time']); ?></td>
                                                <td><?= htmlspecialchars($row['supplier_name']); ?></td>
                                                <td><?= htmlspecialchars($row['description']); ?></td>
                                                <td><?= htmlspecialchars($row['supplier_amount']); ?></td>
                                                <td><?= htmlspecialchars(ucfirst($paid_method_display)); ?></td>
                                                <td><?= htmlspecialchars($row['user_name']); ?></td>
                                                <td><a href="edit_pay.php?id=<?php echo $row['id']; ?>" class="btn btn-primary"><i class="fas fa-edit fa-1x"></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 payment?');">
                                                        <i class="fas fa-trash-alt"></i>
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Footer -->
        <?php include("common/main_ft.php"); ?>
    </div>
</div>
<script>
document.addEventListener("DOMContentLoaded", function() {
    const form = document.getElementById("credit-form");
    const customerSelect = form.querySelector("select[name='supplier_name']");

    // After page load (or reload), focus the customer select
    if (performance.getEntriesByType("navigation")[0].type === "reload" ||
        performance.getEntriesByType("navigation")[0].type === "navigate") {
        customerSelect.focus();
    }

    // Optional: If you want to prevent default and reset form without reloading
    form.addEventListener("submit", function() {
        setTimeout(() => {
            customerSelect.focus(); // focus after submission
        }, 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>


    <link rel="stylesheet" href="../css/responsive-mobile.css">
    <script src="../js/responsive-mobile.js"></script>
</body>
</html>