<?php
ob_start();
include("db/cn.php");
include("common/tx.php");

if ($_GET) {
    // Sanitize the ID to prevent SQL injection
    $id = mysqli_real_escape_string($connection, $_GET["id"]);
    $del_query = mysqli_query($connection, "DELETE FROM products WHERE id = '$id'");
    echo "<script type='text/javascript'>window.location.href = 'addproduct.php';</script>";
    exit();
}
?>
<!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">
    <meta name="description" content="">
    <meta name="author" content="">

    <title><?php echo $tx; ?></title>

    <!-- Custom fonts for this template-->
    <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;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Custom styles for this template-->
    <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/chart.js"></script>
</head>

<style>
    body {
        font-family: 'Quicksand', sans-serif;
        background-color: #f8f9fc;
    }

    .page-title {
        font-size: 1.4rem;
        font-weight: 700;
        color: #212529;
        margin-bottom: 0;
    }

    .search-input {
        border-radius: 50px;
        border: 1px solid #ced4da;
        padding-left: 20px;
        box-shadow: none;
        transition: all 0.3s;
    }

    .search-input:focus {
        border-color: #0A4657;
        box-shadow: 0 0 0 0.2rem rgba(10, 70, 87, 0.15);
    }

    .card {
        border: none;
        border-radius: 15px;
        box-shadow: 0 2px 20px rgba(0, 0, 0, 0.05);
    }

    .card-header {
        background: #fff;
        border-bottom: 1px solid rgba(0,0,0,0.05);
        padding: 1.2rem 1.5rem;
    }

    .table thead th {
        background-color: #0A4657;
        color: #fff;
        font-weight: 600;
        font-size: 0.85rem;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        border-bottom: none;
        vertical-align: middle;
        padding: 12px 8px;
    }

    .table tbody td {
        vertical-align: middle;
        font-size: 0.9rem;
        padding: 10px 8px;
    }

    .table tbody tr {
        transition: background 0.2s;
    }

    .table tbody tr:hover {
        background-color: rgba(10, 70, 87, 0.04);
    }

    .low-stock-row {
        background-color: #fff5f5 !important;
        border-left: 4px solid #dc3545;
    }

    .low-stock-row td {
        font-weight: 600;
        color: #721c24;
    }

    .low-stock-badge {
        background: #dc3545;
        color: white;
        font-size: 0.7rem;
        padding: 3px 8px;
        border-radius: 20px;
        margin-left: 8px;
        font-weight: 700;
        text-transform: uppercase;
    }

    .btn-action {
        border-radius: 8px;
        padding: 4px 10px;
        font-size: 0.8rem;
    }

    .btn-update {
        background: #0A4657;
        border: 1px solid #0A4657;
        color: #fff;
    }

    .btn-update:hover {
        background: #fff;
        color: #0A4657;
        border-color: #0A4657;
    }

    .btn-delete {
        background: #e74a3b;
        border: 1px solid #e74a3b;
        color: #fff;
    }

    .btn-delete:hover {
        background: #fff;
        color: #e74a3b;
        border-color: #e74a3b;
    }

    .table-responsive {
        border-radius: 0 0 15px 15px;
    }

    #table-container {
        max-height: 70vh;
        overflow-y: auto;
    }

    .search-wrapper {
        position: relative;
    }

    .search-wrapper .fa-search {
        position: absolute;
        right: 15px;
        top: 50%;
        transform: translateY(-50%);
        color: #aaa;
    }

    .add-product-btn {
        background: #0A4657;
        color: #fff;
        border-radius: 50px;
        padding: 0.5rem 1.5rem;
        font-weight: 600;
        font-size: 0.9rem;
        transition: all 0.3s;
    }

    .add-product-btn:hover {
        background: #fff;
        color: #0A4657;
        border: 1px solid #0A4657;
    }

    .no-data-message {
        background: #0A4657;
        color: #fff;
        border-radius: 10px;
        padding: 20px;
        font-weight: 600;
    }
</style>

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

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">
            <!-- Main Content -->
            <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 -->

                <!-- Begin Page Content -->
                <div class="container-fluid">
                    <!-- Header Row -->
                    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap">
                        <h1 class="page-title"><i class="fas fa-boxes mr-2 text-primary"></i>Product Management</h1>
                        <a href="addproducts.php" class="btn add-product-btn shadow-sm">
                            <i class="fas fa-plus-circle mr-1"></i> Add New Product
                        </a>
                    </div>

                    <!-- Search Card -->
                    <div class="card shadow-sm mb-4">
                        <div class="card-header py-3">
                            <div class="row align-items-center">
                                <div class="col-md-6">
                                    <h6 class="m-0 font-weight-bold" style="color: #0A4657;">
                                        <i class="fas fa-search mr-2"></i>Search Products
                                    </h6>
                                </div>
                                <div class="col-md-6 mt-2 mt-md-0">
                                    <div class="search-wrapper">
                                        <input type="text" id="search-input" class="form-control search-input" placeholder="Type product name...">
                                        <i class="fas fa-search"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Products Table Card -->
                    <div class="card shadow mb-4">
                        <div class="card-body p-0">
                            <div id="table-container" class="table-responsive">
                                <?php
                                $sql = "SELECT * FROM products";
                                $result = $connection->query($sql);

                                if ($result->num_rows > 0) {
                                    echo '<table id="productTable" class="table table-hover align-middle mb-0">';
                                    echo '<thead><tr>';
                                    echo '<th>#</th>';
                                    echo '<th>Item Code</th>';
                                    echo '<th>Stock</th>';
                                    echo '<th>Supplier</th>';
                                    echo '<th>Category</th>';
                                    echo '<th>Company</th>';
                                    echo '<th>Product Name</th>';
                                    echo '<th>Sale Price</th>';
                                    echo '<th>Total Amount</th>';
                                    echo '<th class="text-center">Actions</th>';
                                    echo '</tr></thead><tbody>';

                                    $sr_no = 1;
                                    while ($row = $result->fetch_assoc()) {
                                        // Determine row class for low stock
                                        $rowClass = ($row["quantity"] < 5) ? 'low-stock-row' : '';
                                        $quantityDisplay = $row["quantity"];
                                        if ($row["quantity"] < 5) {
                                            $quantityDisplay = $row["quantity"] . ' <span class="low-stock-badge">Low</span>';
                                        }

                                        echo '<tr class="product-row ' . $rowClass . '" data-category="' . htmlspecialchars($row["company"]) . '">';
                                        echo '<td class="font-weight-bold">' . $sr_no++ . '</td>';
                                        echo '<td class="font-weight-bold">' . htmlspecialchars($row["product_id"]) . '</td>';
                                        echo '<td class="font-weight-bold">' . $quantityDisplay . '</td>';
                                        echo '<td class="text-capitalize">' . htmlspecialchars($row["supplier"]) . '</td>';
                                        echo '<td class="text-capitalize font-weight-semibold">' . htmlspecialchars($row["category"]) . '</td>';
                                        echo '<td class="text-capitalize">' . htmlspecialchars($row["company"]) . '</td>';
                                        echo '<td class="font-weight-bold text-primary">' . htmlspecialchars($row["product_name"]) . '</td>';
                                        echo '<td>Rs. ' . number_format($row["retail_price"], 0) . '</td>';
                                        echo '<td>Rs. ' . number_format($row["total_amount"], 0) . '</td>';
                                        echo '<td class="text-center">
                                                <a href="product_update.php?id=' . $row["id"] . '" class="btn btn-action btn-update btn-sm mr-1" title="Update">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <button type="button" class="btn btn-action btn-delete btn-sm" onclick="confirmDelete(' . $row["id"] . ')" title="Delete">
                                                    <i class="fas fa-trash-alt"></i>
                                                </button>
                                              </td>';
                                        echo '</tr>';
                                    }
                                    echo '</tbody></table>';
                                } else {
                                    echo '<div class="text-center py-5 no-data-message">
                                            <i class="fas fa-box-open fa-3x mb-3"></i>
                                            <h5>No products found</h5>
                                            <p class="mb-0">Start by adding your first product.</p>
                                          </div>';
                                }
                                ?>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- /.container-fluid -->
            </div>
            <!-- End of Main Content -->

            <!-- Footer -->
            <?php include("common/main_ft.php"); ?>
            <!-- End of Footer -->
        </div>
        <!-- End of Content Wrapper -->
    </div>
    <!-- End of Page Wrapper -->

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

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="">Logout</a>
                </div>
            </div>
        </div>
    </div>

    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        function confirmDelete(productId) {
            Swal.fire({
                title: "Delete Product?",
                text: "This action cannot be undone.",
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#e74a3b",
                cancelButtonColor: "#858796",
                confirmButtonText: "Yes, delete it!",
                cancelButtonText: "Cancel",
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = "addproduct.php?id=" + productId;
                }
            });
        }

        // Real-time search filtering
        document.addEventListener("DOMContentLoaded", function() {
            document.getElementById("search-input").addEventListener("input", function() {
                var searchText = this.value.toLowerCase();
                var rows = document.querySelectorAll(".product-row");

                rows.forEach(function(row) {
                    var productName = row.querySelector("td:nth-child(7)").textContent.toLowerCase();
                    if (productName.includes(searchText)) {
                        row.style.display = "table-row";
                    } else {
                        row.style.display = "none";
                    }
                });
            });
        });
    </script>

    <!-- Bootstrap core JavaScript-->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- Custom scripts for all pages-->
    <script src="../js/sb-admin-2.min.js"></script>
</body>
</html>