<?php
include 'includes/config.php';
session_start();

if (!$_SESSION['email']) {
    header('location:login.php');
}
?>
<?php
$sql = "SELECT * FROM units Where business_id = 3";
try {
    $query = $conn->prepare($sql);
    $query->execute();
    $space = $query->fetchAll();
} catch (Exception $ex) {
    echo ($ex->getMessage());
}
?>
<?php
$sql = "SELECT * FROM brands Where business_id = 3";
try {
    $query = $conn->prepare($sql);
    $query->execute();
    $brand = $query->fetchAll();
} catch (Exception $ex) {
    echo ($ex->getMessage());
}
?>
<?php

// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Handle file upload
    $imageName = '';
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $imageTmpName = $_FILES['image']['tmp_name'];
        $imageOriginalName = $_FILES['image']['name'];
        $imageExtension = pathinfo($imageOriginalName, PATHINFO_EXTENSION);
        $uniqueId = uniqid(); // Unique ID for the image filename
        $imageName = $uniqueId . '.' . $imageExtension;
        move_uploaded_file($imageTmpName, 'img/' . $imageName);
    }

    // Retrieve form data
    $name = $_POST['name'];
    $unit_id = $_POST['unit_id'];
    $brand_id = $_POST['brand_id'];
    $category_id = $_POST['category_id'];
    $sub_category_id = $_POST['sub_category_id'];
    $alert_quantity = $_POST['alert_quantity'];
    $default_purchase_price = $_POST['default_purchase_price'];
    $dpp_inc_tax = $_POST['dpp_inc_tax'];
    $profit_percent = $_POST['profit_percent'];
    $default_sell_price = $_POST['default_sell_price'];
    $type = 'single';
    $business_id = 3;
    $product_code = $_POST['product_code'];
    $barcode = $_POST['barcode'];
    $color_id = isset($_POST['color_id']) && !empty($_POST['color_id']) ? $_POST['color_id'] : 0;
    $size_id  = isset($_POST['size_id']) && !empty($_POST['size_id']) ? $_POST['size_id'] : 0;
    $serial_no = $_POST['serial_no'];
    $model_no = $_POST['model_no'];


    $stmt = $conn->prepare("SELECT id FROM products WHERE barcode = ?");
    $stmt->execute([$barcode]);
    if ($stmt->rowCount() > 0) {
        echo "<script>alert('Error: Barcode already exists!');</script>";
        echo "<script>window.location.href='add_products.php'</script>";
        exit;
    }

    // Insert into products table
    $sql = "INSERT INTO products 
(name, business_id, type, unit_id, brand_id, category_id, sub_category_id, alert_quantity, sku, image, color_id, size_id, product_code, barcode, serial_no, model_no)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $conn->prepare($sql);
    $stmt->execute([
        $name,
        $business_id,
        $type,
        $unit_id,
        $brand_id,
        $category_id,
        $sub_category_id,
        $alert_quantity,
        '',
        $imageName,
        $color_id,
        $size_id,
        $product_code,
        $barcode,
        $serial_no,
        $model_no
    ]);


    $product_id = $conn->lastInsertId(); // Get the ID of the inserted product

    // Generate SKU
    $stmt = $conn->prepare("SELECT name FROM brands WHERE id = ?");
    $stmt->execute([$brand_id]);
    $brand = $stmt->fetch(PDO::FETCH_ASSOC);
    $sku = $brand['name'] . '' . $product_id;

    // Update the product record with the correct SKU
    $sql = "UPDATE products SET sku = ? WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$sku, $product_id]);

    // Insert into variations table
    $sql = "INSERT INTO variations (name, product_id, sub_sku, product_variation_id, default_purchase_price, dpp_inc_tax, profit_percent, default_sell_price, sell_price_inc_tax)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->execute(['DUMMY', $product_id, $sku, $product_id, $default_purchase_price, $dpp_inc_tax, $profit_percent, $default_sell_price, $default_sell_price]);

    // Confirmation and redirection
    echo "<script>alert('Data inserted Successfully');</script>";
    echo "<script>window.location.href='add_products.php'</script>";
}
?>

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Add Products</title>
    <!-- Favicon -->
    <link rel="shortcut icon" href="images/favicon.ico" />
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!-- Typography CSS -->
    <link rel="stylesheet" href="css/typography.css">
    <!-- Style CSS -->
    <link rel="stylesheet" href="css/style.css">
    <!-- Responsive CSS -->
    <link rel="stylesheet" href="css/responsive.css">
    <style>
        ion-icon {
            font-size: 20px;
            margin-bottom: -5px;
        }
    </style>

</head>

<body>
    <!-- loader Start -->
    <div id="loading">
        <div id="loading-center">
        </div>
    </div>
    <!-- loader END -->
    <!-- Wrapper Start -->
    <div class="wrapper">
        <!-- Sidebar  -->
        <?php
        include 'includes/sidebar.php';
        ?>
        <!-- TOP Nav Bar -->
        <?php include 'includes/header.php'; ?>
        <!-- TOP Nav Bar END -->
        <!-- Page Content  -->
        <!-- Modal HTML -->
        <div class="modal fade" id="addUnitModal" tabindex="-1" role="dialog" aria-labelledby="addUnitModalLabel"
            aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addUnitModalLabel">Add New Unit</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <form id="insertForm" method="post" action="insert_unit_data.php">
                        <div class="modal-body">
                            <div class="form-group">
                                <label for="actual_name" class="control-label">Name</label>
                                <input type="text" name="actual_name" class="form-control" placeholder="Name"
                                    id="actual_name" required>
                            </div>
                            <div class="form-group">
                                <label for="short_name" class="control-label">Short Name</label>
                                <input type="text" name="short_name" class="form-control" placeholder="Short Name"
                                    id="short_name" required>
                            </div>
                            <div class="form-group">
                                <label for="allow_decimal" class="control-label">Allow Decimal</label>
                                <select name="allow_decimal" class="form-control" id="allow_decimal" required>
                                    <option value="">Please select</option>
                                    <option value="1">Yes</option>
                                    <option value="0">No</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <input type="checkbox" name="add_multiple" id="add_multiple">
                                <label for="add_multiple">Add as multiple of other unit</label>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary">Save</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

        <!-- Font Awesome CSS -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">

        <!-- jQuery -->
        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>

        <!-- Bootstrap JS -->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script>

        <div id="content-page" class="content-page">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="iq-card">
                            <div class="iq-card-header d-flex justify-content-between row">
                                <div class="iq-header-title col-lg-6">
                                    <h4 class="card-title"><a href="list_products.php">Products</a> > Add Products
                                    </h4>
                                </div>
                            </div>
                            <div class="iq-card-body" style="overflow:auto;">
                                <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"
                                    enctype="multipart/form-data">
                                    <div class="row">
                                        <div class="col-lg-4">
                                            <div class="form-group">
                                                <label class="label-control">Product Name:*</label>
                                                <input type="text" class="form-control" name="name" id="product_name"
                                                    placeholder="Please Enter Product Name" required>
                                                <small id="name_error" class="text-danger"></small>
                                            </div>
                                        </div>

                                        <div class="col-lg-4">
                                            <div class="form-group">
                                                <label class="label-control">Product Code:*</label>
                                                <input type="text" class="form-control" name="product_code" id="product_code"
                                                    placeholder="Please Enter Product Code" required>
                                                <small id="code_error" class="text-danger"></small>
                                            </div>
                                        </div>
                                        <div class="col-lg-4">
                                            <div class="form-group">
                                                <label class="label-control">Bar Code:*</label>
                                                <input type="text" id="barcode" name="barcode" class="form-control" required>
                                                <small id="barcode_error" style="color:red;"></small>

                                            </div>
                                        </div>

                                        <div class="col-lg-4" style="display:none;">
                                            <div class="form-group">
                                                <label class="label-control">Serial No:*</label>
                                                <input type="text" id="serial_no" name="serial_no" class="form-control">
                                                <small id="serial_no_error" style="color:red;"></small>

                                            </div>
                                        </div>

                                        <div class="col-lg-4" style="display:none;">
                                            <div class="form-group">
                                                <label class="label-control">Model No:*</label>
                                                <input type="text" id="model_no" name="model_no" class="form-control">
                                                <small id="model_no_error" style="color:red;"></small>

                                            </div>
                                        </div>

                                        <div class="col-lg-4" style="display:none;">
                                            <div class="form-group">
                                                <label class="label-control">Product Color:*</label>
                                                <div class="input-group">
                                                    <select name="color_id" id="color_id" class="form-control">
                                                        <option selected disabled>Please Select</option>
                                                        <?php
                                                        $stmt = $conn->query("SELECT id, product_color FROM colors ORDER BY name ASC");
                                                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                                            echo "<option value='{$row['id']}'>" . htmlspecialchars($row['product_color']) . "</option>";
                                                        }
                                                        ?>
                                                    </select>

                                                </div>
                                            </div>
                                        </div>

                                        <!-- Product Size -->
                                        <div class="col-lg-4" style="display: none;">
                                            <div class="form-group">
                                                <label class="label-control">Product Size:*</label>
                                                <div class="input-group">
                                                    <select name="size_id" id="size_id" class="form-control">
                                                        <option selected disabled>Please Select</option>
                                                        <?php
                                                        $stmt = $conn->query("SELECT id, product_size FROM sizes ORDER BY name ASC");
                                                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                                            echo "<option value='{$row['id']}'>" . htmlspecialchars($row['product_size']) . "</option>";
                                                        }
                                                        ?>
                                                    </select>

                                                </div>
                                                <small id="combo_error" class="text-danger"></small>

                                            </div>
                                        </div>

                                        <div class="col-lg-4">
                                            <div class="form-group">
                                                <label for="unit_id" class="label-control mr-2">Unit:*</label>
                                                <div class="input-group">
                                                    <select name="unit_id" class="form-control" id="unit_id" required>
                                                        <option selected disabled>Please Select</option>

                                                        <?php foreach ($space as $output) { ?>
                                                            <option
                                                                value="<?php echo htmlspecialchars($output["id"], ENT_QUOTES); ?>">
                                                                <?php echo htmlspecialchars($output["actual_name"], ENT_QUOTES); ?>
                                                                (
                                                                <?php echo htmlspecialchars($output["short_name"], ENT_QUOTES); ?>
                                                                )
                                                            </option>
                                                        <?php } ?>
                                                    </select>
                                                    <div class="input-group-append">
                                                        <button class="btn btn-outline-secondary" type="button"
                                                            data-toggle="modal" data-target="#addUnitModal">
                                                            <i class="fa fa-plus"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>

                                        </div>
                                        <div class="col-lg-4">
                                            <div class="form-group">
                                                <label for="" class="label-control">Brand:*</label>
                                                <div class="input-group">
                                                    <select name="brand_id" class="form-control" id="" required>
                                                        <?php foreach ($brand as $output) { ?>
                                                            <option
                                                                value="<?php echo htmlspecialchars($output["id"], ENT_QUOTES); ?>">
                                                                <?php echo htmlspecialchars($output["name"], ENT_QUOTES); ?>
                                                            </option>
                                                        <?php } ?>
                                                    </select>
                                                    <!-- <div class="input-group-append">
                                                        <button class="btn btn-outline-secondary" type="button"
                                                            data-toggle="modal" data-target="#addUnitModal">
                                                            <i class="fa fa-plus"></i>
                                                        </button>
                                                    </div> -->
                                                </div>
                                            </div>
                                        </div>
                                        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

                                        <div class="col-lg-4">
                                            <div class="form-group">
                                                <label for="category" class="label-control">Category:*</label>
                                                <select name="category_id" class="form-control" id="category" required>
                                                    <option value="">Please Select</option>
                                                    <?php

                                                    $business_id = 3; // Assuming business_id is 3
                                                    $stmt = $conn->prepare("SELECT id, name FROM categories WHERE parent_id = 0 AND business_id = ?");
                                                    $stmt->execute([$business_id]);

                                                    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                                        echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
                                                    }
                                                    ?>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-lg-4" style="display: none;">
                                            <div class="form-group">
                                                <label for="subcategory" class="label-control">Sub category:*</label>
                                                <select name="sub_category_id" class="form-control" id="subcategory">
                                                    <option selected disabled>Please Select</option>
                                                </select>
                                            </div>
                                        </div>


                                        <div class="col-lg-4">
                                            <div class="form-group">
                                                <label for="" class="label-control">Alert quantity:*</label>
                                                <input type="number" class="form-control" name="alert_quantity"
                                                    placeholder="Alert quantity" id="">
                                            </div>
                                        </div>
                                         <div class="col-lg-4">
                                            <div class="form-group">
                                                <label for="purchasePriceExcTax"
                                                    class="label-control">Purchase Price:</label>
                                               <input type="number" class="form-control"
       name="default_purchase_price"
       id="purchasePriceExcTax"
       placeholder="Purchase Price"
       step="0.01"
       min="0">

                                            </div>
                                        </div>
                                      
                                        <div class="col-lg-4">
                                            <div class="form-group">
                                                <label for="sellingPrice" class="label-control">Selling Price:</label>
                                                <input type="text" class="form-control"
                                                    id="sellingPrice" name="default_sell_price"
                                                    placeholder="Selling Price">
                                            </div>
                                        </div>
                                     
                                        <div class="iq-card-body" style="overflow:auto;">
                                            <table class="table table-hover table-bordered">
                                                <thead>
                                                    <tr>
                                                        <!-- <th colspan="2">Default Purchase Price</th>
                                                        <th>x Margin (%)</th> -->
                                                        <!-- <th>Default Selling Price</th> -->
                                                        <th>Product Image</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>

                                                        <td style="display: none;">
                                                            <div class="form-group">
                                                                <label for="purchasePriceIncTax"
                                                                    class="label-control">Inc. tax:</label>
                                                                <input type="number" class="form-control"
                                                                    name="dpp_inc_tax" id="purchasePriceIncTax"
                                                                    placeholder="Inc. tax" readonly>
                                                            </div>
                                                        </td>
                                                        <td style="display: none;">
                                                            <div class="form-group">
                                                                <label for="margin" class="label-control">Margin
                                                                    (%)</label>
                                                                <input type="number" class="form-control" id="margin"
                                                                    name="profit_percent" placeholder="0.00"
                                                                    oninput="calculatePurchasePrice()">
                                                            </div>
                                                        </td>

                                                        <td>
                                                            <div class="form-group">
                                                                <label for="productImage" class="label-control">Attach
                                                                    Document:</label>
                                                                <input type="file" class="form-control" name="image"
                                                                    id="productImage">
                                                            </div>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>

                                        </div>
                                        <div class="col-lg-12">
                                            <button type="submit" id="submit_btn" class="btn btn-primary">Submit</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <script>
                $(document).ready(function() {
                    function checkAvailability(data) {
                        return $.ajax({
                            url: "check_product.php",
                            method: "POST",
                            data: data,
                            dataType: "json"
                        });
                    }

                    function validateFields() {
                        let name = $("#product_name").val().trim();
                        let code = $("#product_code").val().trim();
                        let color = $("#color_id").val();
                        let size = $("#size_id").val();
                        let barcode = $("#barcode").val().trim();

                        $("#combo_error").text("");
                        $("#barcode_error").text("");

                        if (name && code && color && size) {
                            checkAvailability({
                                field: "unique_product",
                                name: name,
                                product_code: code,
                                color_id: color,
                                size_id: size
                            }).done(function(res) {
                                if (res.exists) {
                                    $("#combo_error").text("This Product with same Name, Code, Color & Size already exists!");
                                    $("#submit_btn").prop("disabled", true);
                                } else {
                                    $("#combo_error").text("");
                                    $("#submit_btn").prop("disabled", false);
                                }
                            });
                        }

                        if (barcode) {
                            checkAvailability({
                                field: "unique_barcode",
                                barcode: barcode
                            }).done(function(res) {
                                if (res.exists) {
                                    $("#barcode_error").text("This Barcode is already in use!");
                                    $("#submit_btn").prop("disabled", true);
                                } else {
                                    $("#barcode_error").text("");
                                    $("#submit_btn").prop("disabled", false);
                                }
                            });
                        }
                    }

                    $("#product_name, #product_code, #color_id, #size_id, #barcode").on("change keyup blur", validateFields);
                });
            </script>



            <?php

            $records_per_page = 100;

            $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
            $offset = ($page - 1) * $records_per_page;

            $search = isset($_GET['search']) ? $_GET['search'] : '';
            $search = htmlspecialchars($search);

            $business_id = 3;

            $total_records_query = "
    SELECT COUNT(*) 
    FROM products p
    LEFT JOIN purchase_lines pl ON p.id = pl.product_id
    WHERE (p.name LIKE :search OR p.sku LIKE :search)
    AND p.business_id = :business_id
";
            $total_records_stmt = $conn->prepare($total_records_query);
            $total_records_stmt->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR);
            $total_records_stmt->bindValue(':business_id', $business_id, PDO::PARAM_INT);
            $total_records_stmt->execute();
            $total_records = $total_records_stmt->fetchColumn();
            $total_pages = ceil($total_records / $records_per_page);


            $sql = "
SELECT 
    p.id AS product_id,
    p.name AS product_name,
    p.business_id,
    p.image,
    p.type,
    p.brand_id,
    b.name AS brand_name,
    p.category_id,
    p.sub_category_id,
    c1.name AS category_name,
    c2.name AS sub_category_name,
    p.tax,
    p.sku,
    p.product_code,
    p.alert_quantity,
    p.product_custom_field1,
    p.product_custom_field2,
    p.product_custom_field3,
    p.product_custom_field4,
    p.product_description,
    p.unit_id,
    p.tax_type,
    v.profit_percent,
    u.actual_name,
    v.default_purchase_price,
    v.default_sell_price,
    b.name,
    COALESCE(v.dpp_inc_tax, 0) AS purchase_price,
    COALESCE(v.sell_price_inc_tax, 0) AS sale_price,
    COALESCE(SUM(pl.quantity), 0) AS total_quantity,
    COALESCE((SUM(pl.quantity) - 0), 0) AS current_stock,
    COALESCE(SUM(pl.quantity_sold), 0) AS total_sold,
    col.name AS color_name,
    sz.name AS size_name
FROM 
    products p
LEFT JOIN 
    (
        SELECT 
            product_id, 
            quantity, 
            quantity_sold
        FROM 
            purchase_lines
    ) pl ON p.id = pl.product_id
LEFT JOIN 
    brands b ON p.brand_id = b.id
LEFT JOIN 
    categories c1 ON p.category_id = c1.id
LEFT JOIN 
    categories c2 ON p.sub_category_id = c2.id
LEFT JOIN 
    units u ON p.unit_id = u.id
LEFT JOIN 
    variations v ON p.id = v.product_id
LEFT JOIN 
    colors col ON p.color_id = col.id
LEFT JOIN 
    sizes sz ON p.size_id = sz.id
WHERE 
    (p.name LIKE :search OR p.sku LIKE :search)
    AND p.business_id = :business_id
GROUP BY 
    p.id
ORDER BY 
    p.id DESC
LIMIT :limit OFFSET :offset
";

            // Prepare and execute the query
            $stmt = $conn->prepare($sql);
            $stmt->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR);
            $stmt->bindValue(':business_id', $business_id, PDO::PARAM_INT);
            $stmt->bindValue(':limit', $records_per_page, PDO::PARAM_INT);
            $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
            $stmt->execute();
            $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Function to generate pagination links
            function generatePaginationLinks($current_page, $total_pages)
            {
                $pagination_links = [];

                // Show first few pages
                for ($i = 1; $i <= 4; $i++) {
                    if ($i <= $total_pages) {
                        $pagination_links[] = $i;
                    }
                }

                // Ellipses if current page is greater than 5
                if ($current_page > 5) {
                    $pagination_links[] = '...';
                }

                // Show few pages around the current page
                for ($i = max(5, $current_page - 1); $i <= min($total_pages - 4, $current_page + 1); $i++) {
                    if ($i > 4 && $i < $total_pages - 3) {
                        $pagination_links[] = $i;
                    }
                }

                // Ellipses if current page is less than total_pages - 4
                if ($current_page < $total_pages - 4) {
                    $pagination_links[] = '...';
                }

                // Show last few pages
                for ($i = max($total_pages - 3, 5); $i <= $total_pages; $i++) {
                    if ($i > 4) {
                        $pagination_links[] = $i;
                    }
                }

                return $pagination_links;
            }

            // Generate pagination links
            $pagination_links = generatePaginationLinks($page, $total_pages);

            // Output the total number of products
            // echo "<p>Total products: " . $total_records . "</p>";

            ?>
            <form action="" method="get">
                <div class="row mt-5" style="width:95%;margin:0 auto;">
                    <div class="col-lg-5">
                        <input type="search" name="search" class="form-control" placeholder="Search products"
                            value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    <div class="col-lg-2">
                        <button type="submit" style="width:100%;" class="btn btn-primary p-2">Search</button>
                    </div>
                    <div class="col-lg-2">
                        <button type="button" style="width:100%;" class="btn btn-success p-2"
                            onclick="clearFilter()">Clear Filter</button>
                    </div>
                </div>
            </form>
            <br>
            <script>
                function clearFilter() {
                    // Redirect to list_products.php without the search query
                    window.location.href = 'add_products.php';
                }
            </script>
            <table class="table table-hover table-bordered">
                <thead>
                    <tr>
                        <th>Image</th>
                        <th>Actions</th>
                        <th>Brand</th>
                        <th>Product</th>
                        <th>Product Code</th>
                        <th>Purchase Price</th>
                        <th>Sale Price</th>
                        <!-- <th>Color</th>
            <th>Size</th> -->
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($products as $product): ?>
                        <tr>
                            <td>
                                <a href="img/<?php echo htmlspecialchars($product['image']); ?>" target="_blank">
                                    <img src="img/<?php echo htmlspecialchars($product['image']); ?>" style="width:4em;">
                                </a>
                            </td>
                            <td>
                                <div class="custom_select">
                                    <button class="select-button">
                                        <span class="selected-option">Actions</span>
                                        <span class="arrow">&#9660;</span>
                                    </button>
                                    <div class="select-options">
                                        <a href="add_purchase.php?product_id=<?php echo htmlentities($product['product_id']); ?>">
                                            <ion-icon name="cart-outline"></ion-icon> &nbsp; Purchase
                                        </a>
                                        <a href="print_label.php?product_id=<?php echo htmlentities($product['product_id']); ?>">
                                            <ion-icon name="barcode-outline"></ion-icon> &nbsp; Labels
                                        </a>
                                        <a href="action/delete_product.php?del=<?php echo htmlentities($product['product_id']); ?>"
                                            class="delete-link"
                                            onclick="return confirm('Are you sure you want to delete this item?');">
                                            <ion-icon name="trash-outline"></ion-icon> &nbsp; Delete
                                        </a>
                                        <a href="edit_products.php?product_id=<?php echo htmlentities($product['product_id']); ?>">
                                            <ion-icon name="create-outline"></ion-icon> &nbsp; Edit
                                        </a>
                                    </div>
                                </div>
                            </td>
                            <td><?php echo htmlspecialchars($product['brand_name']); ?></td>
                            <td><?php echo htmlspecialchars($product['product_name']); ?></td>
                            <td><?php echo htmlspecialchars($product['product_code']); ?></td>
                             <td><?php echo htmlspecialchars($product['default_purchase_price']); ?></td>
                              <td><?php echo htmlspecialchars($product['default_sell_price']); ?></td>
                            <!-- <td><?php echo htmlspecialchars($product['color_name']); ?></td>
            <td><?php echo htmlspecialchars($product['size_name']); ?></td> -->
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>


            <!-- Pagination Links -->
            <nav aria-label="Page navigation">
                <ul class="pagination">
                    <?php if ($page > 1): ?>
                        <li class="page-item">
                            <a class="page-link"
                                href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>"
                                aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                            </a>
                        </li>
                    <?php endif; ?>

                    <?php foreach ($pagination_links as $link): ?>
                        <?php if ($link === '...'): ?>
                            <li class="page-item disabled"><span class="page-link">...</span></li>
                        <?php else: ?>
                            <li class="page-item <?php echo ($link == $page) ? 'active' : ''; ?>">
                                <a class="page-link"
                                    href="?page=<?php echo $link; ?>&search=<?php echo urlencode($search); ?>"><?php echo $link; ?></a>
                            </li>
                        <?php endif; ?>
                    <?php endforeach; ?>

                    <?php if ($page < $total_pages): ?>
                        <li class="page-item">
                            <a class="page-link"
                                href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>"
                                aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                            </a>
                        </li>
                    <?php endif; ?>
                </ul>
                <h4>Total Products: <?php echo $total_records; ?></h4>
            </nav>
        </div>
    </div>
    </div>

    <style>
        ion-icon {
            font-size: 20px;
            margin-bottom: -5px;
        }

        .custom_select {
            position: relative;
            display: inline-block;
        }

        .select-button {
            background-color: #007BFF;
            color: white;
            padding: 4px 8px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 70px;
            text-align: left;
        }

        .arrow {
            margin-left: 3px;
        }

        .select-options {
            display: none;
            position: absolute;
            background-color: #f9f9f9;
            min-width: 120px;
            box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
            z-index: 1;
            border-radius: 4px;
            top: 100%;
            left: 0;
        }

        .select-options a {
            color: black;
            padding: 6px 10px;
            text-decoration: none;
            display: block;
            font-size: 12px;
        }

        .select-options a:hover {
            background-color: #f1f1f1;
        }
    </style>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // Attach event listeners for dynamically added elements
            document.body.addEventListener('click', (event) => {
                const selectButton = event.target.closest('.select-button');
                const selectOptions = event.target.closest('.select-options');

                if (selectButton) {
                    const dropdown = selectButton.nextElementSibling; // select-options
                    dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block';
                    event.stopPropagation(); // Prevent the click from propagating to window
                } else if (!selectOptions || !selectOptions.contains(event.target)) {
                    // Hide all dropdowns if the click is outside of any dropdown
                    document.querySelectorAll('.select-options').forEach((dropdown) => {
                        if (dropdown.style.display === 'block') {
                            dropdown.style.display = 'none';
                        }
                    });
                }
            });

            // Handle option selection
            document.body.addEventListener('click', (event) => {
                if (event.target.tagName === 'A' && event.target.closest('.select-options')) {
                    const selectButton = event.target.closest('.custom_select').querySelector(
                        '.select-button');
                    selectButton.querySelector('.selected-option').textContent = event.target.textContent;
                    event.target.closest('.select-options').style.display = 'none';
                }
            });
        });
    </script>
    <script>
        function calculatePurchasePrice() {
            // Get values from input fields
            var sellingPrice = parseFloat(document.getElementById('sellingPrice').value) || 0;
            var margin = parseFloat(document.getElementById('margin').value) || 0;

            // Calculate the purchase price (Exc. tax)
            var purchasePrice = sellingPrice / (1 + (margin / 100));

            // Update both purchase price fields to show the same value
            document.getElementById('purchasePriceExcTax').value = purchasePrice.toFixed(2);
            document.getElementById('purchasePriceIncTax').value = purchasePrice.toFixed(2);
        }
    </script>
    <script>
        $(document).ready(function() {
            $('#category').change(function() {
                var categoryId = $(this).val();

                if (categoryId) {
                    $.ajax({
                        url: 'fetch_subcategories.php',
                        type: 'POST',
                        data: {
                            id: categoryId
                        },
                        dataType: 'json',
                        success: function(response) {
                            $('#subcategory').empty();
                            $('#subcategory').append('<option value="">Please Select</option>');
                            $.each(response, function(index, subcategory) {
                                $('#subcategory').append('<option value="' + subcategory
                                    .id + '">' + subcategory.name + '</option>');
                            });
                        }
                    });
                } else {
                    $('#subcategory').empty();
                    $('#subcategory').append('<option value="">Please Select</option>');
                }
            });
        });
    </script>
    <!-- Wrapper END -->
    <!-- Footer -->
    <?php include 'includes/footer.php'; ?>
    <nav class="iq-float-menu">
        <input type="checkbox" href="#" class="iq-float-menu-open" name="menu-open" id="menu-open" />
        <label class="iq-float-menu-open-button" for="menu-open">
            <span class="lines line-1"></span>
            <span class="lines line-2"></span>
            <span class="lines line-3"></span>
        </label>
        <button class="iq-float-menu-item bg-info" data-toggle="tooltip" data-placement="top" title="Direction Mode"
            data-mode="rtl"><i class="ri-text-direction-r"></i></button>
        <button class="iq-float-menu-item bg-danger" data-toggle="tooltip" data-placement="top" title="Color Mode"
            id="dark-mode" data-active="true"><i class="ri-sun-line"></i></button>
        <button class="iq-float-menu-item bg-warning" data-toggle="tooltip" data-placement="top" title="Comming Soon"><i
                class="ri-palette-line"></i></button>
    </nav>
    <!-- Footer END -->
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="js/jquery.min.js"></script>
    <!-- Rtl and Darkmode -->
    <script src="js/rtl.js"></script>
    <script src="js/customizer.js"></script>
    <script src="js/popper.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <!-- Appear JavaScript -->
    <script src="js/jquery.appear.js"></script>
    <!-- Countdown JavaScript -->
    <script src="js/countdown.min.js"></script>
    <!-- Counterup JavaScript -->
    <script src="js/waypoints.min.js"></script>
    <script src="js/jquery.counterup.min.js"></script>
    <!-- Wow JavaScript -->
    <script src="js/wow.min.js"></script>
    <!-- Apexcharts JavaScript -->
    <script src="js/apexcharts.js"></script>
    <!-- Slick JavaScript -->
    <script src="js/slick.min.js"></script>
    <!-- Select2 JavaScript -->
    <script src="js/select2.min.js"></script>
    <!-- Owl Carousel JavaScript -->
    <script src="js/owl.carousel.min.js"></script>
    <!-- Magnific Popup JavaScript -->
    <script src="js/jquery.magnific-popup.min.js"></script>
    <!-- Smooth Scrollbar JavaScript -->
    <script src="js/smooth-scrollbar.js"></script>
    <!-- lottie JavaScript -->
    <script src="js/lottie.js"></script>
    <!-- Chart Custom JavaScript -->
    <script src="js/chart-custom.js"></script>
    <!-- Custom JavaScript -->
    <script src="js/custom.js"></script>
</body>

</html>