<!----------------------------------Login------------------------------------>
<?php
session_start();
include 'php/db_connection.php';

// শুধুমাত্র লগইন করা ইউজার পেজ দেখতে পারবে
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$userName = $_SESSION['user_name'];
$role = $_SESSION['role']; // ✅ এখানে role সেভ করা হচ্ছে
$userId = $_SESSION['user_id'];


$isAdmin = ($_SESSION['role'] == 'admin');

?>


<?php include 'heade.php';?>
<?php include 'sidebar.php';?>

<?php

// Initialize success message variable
$successMessage = '';

// Handle product addition
if (isset($_POST['action']) && $_POST['action'] == 'addProduct') {
    $productName = $_POST['productName'];
    $productId = $_POST['productId'];
    $price = $_POST['price'];
    $insert = "INSERT INTO product_cat (Product_name, Product_id, price) VALUES ('$productName', '$productId', '$price')";
    $query = mysqli_query($con, $insert);
    if ($query) {
        $successMessage = "Product added successfully!";
    } else {
        echo "<script>alert('Failed to add product.');</script>";
    }
}

// Handle product update
if (isset($_POST['action']) && $_POST['action'] == 'updateProduct') {
    $id = $_POST['id'];
    $productName = $_POST['productName'];
    $productId = $_POST['productId'];
    $price = $_POST['price'];
    $update = "UPDATE product_cat SET Product_name = '$productName', Product_id = '$productId', price = '$price' WHERE id = $id";
    $updateQuery = mysqli_query($con, $update);
    echo json_encode(['status' => $updateQuery ? 'success' : 'error']);
    exit;
}

// Pagination variables
$limit = 10; // Number of products to display per page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Fetch product data with pagination
function getProductAggregatedData($offset, $limit) {
    global $con;
    $result = mysqli_query($con, "
        SELECT pc.id, pc.Product_name, pc.Product_id, pc.price, 
               SUM(p.quantity) AS total_quantity, 
               SUM(p.quantity * pc.price) AS total_price
        FROM product_cat pc
        LEFT JOIN product p ON pc.Product_id = p.product_id
        GROUP BY pc.id, pc.Product_name, pc.Product_id, pc.price
        LIMIT $offset, $limit
    ");
    return $result;
}

// Count total products for pagination
function getTotalProducts() {
    global $con;
    $result = mysqli_query($con, "SELECT COUNT(*) as count FROM product_cat");
    return mysqli_fetch_assoc($result)['count'];
}

$totalProducts = getTotalProducts();
$totalPages = ceil($totalProducts / $limit);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Product List</title>
    <style>
        body { font-family: Arial, sans-serif; background-color: #f4f4f4;  }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { padding: 10px; border: 1px solid #ccc; text-align: center; }
        th { background-color: #3498db; color: white; }
        .add-product-container { margin-bottom: 20px; }
        .add-product-button, .submit-button, .close-button, .edit-button { background-color: #3498db; color: white; padding: 8px; border: none; cursor: pointer; }
        .edit-button { background-color: #2ecc71; }
        .success-message { background-color: #2ecc71; color: white; padding: 10px; margin-top: 10px; }
        .pagination { margin-top: 20px; }
        .pagination a { padding: 8px 16px; margin: 0 4px; text-decoration: none; border: 1px solid #3498db; color: #3498db; }
        .pagination a.active { background-color: #3498db; color: white; }
    </style>
    <script>
        function showForm() {
            document.getElementById('productFormContainer').style.display = 'block';
        }

        function hideForm() {
            document.getElementById('productFormContainer').style.display = 'none';
        }

        function editProduct(rowId) {
            var row = document.getElementById(`row-${rowId}`);
            row.innerHTML = `
                <td>${rowId}</td>
                <td><input type="text" id="editProductName-${rowId}" value="${row.getAttribute('data-name')}"></td>
                <td><input type="text" id="editProductId-${rowId}" value="${row.getAttribute('data-productid')}"></td>
                <td><input type="text" id="editPrice-${rowId}" value="${row.getAttribute('data-price')}"></td>
                <td colspan="3">
                    <button class="edit-button" onclick="saveProduct(${rowId})">Save</button>
                    <button class="close-button" onclick="window.location.reload()">Cancel</button>
                </td>
            `;
        }

        function saveProduct(rowId) {
            var productName = document.getElementById(`editProductName-${rowId}`).value;
            var productId = document.getElementById(`editProductId-${rowId}`).value;
            var price = document.getElementById(`editPrice-${rowId}`).value;

            var xhr = new XMLHttpRequest();
            xhr.open("POST", "", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var response = JSON.parse(xhr.responseText);
                    if (response.status === 'success') {
                        alert("Product updated successfully!");
                        window.location.reload();
                    } else {
                        alert("Failed to save changes.");
                    }
                }
            };
            xhr.send(`action=updateProduct&id=${rowId}&productName=${encodeURIComponent(productName)}&productId=${encodeURIComponent(productId)}&price=${encodeURIComponent(price)}`);
        }

        // Add product and close form
        function addProduct() {
            const productName = document.getElementById('addProductName').value;
            const productId = document.getElementById('addProductId').value;
            const price = document.getElementById('addPrice').value;

            if (productName && productId && price) {
                var xhr = new XMLHttpRequest();
                xhr.open("POST", "", true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        var response = JSON.parse(xhr.responseText);
                        if (response.status === 'success') {
                            alert("Product added successfully!");
                            window.location.reload();
                        } else {
                            alert("Failed to add product.");
                        }
                    }
                };
                xhr.send(`action=addProduct&productName=${encodeURIComponent(productName)}&productId=${encodeURIComponent(productId)}&price=${encodeURIComponent(price)}`);
            } else {
                alert("Please fill in all fields.");
            }
        }
    </script>
</head>
<body>
    <h2>Product List</h2>
    
    <?php if ($successMessage): ?>
        <div class="success-message"><?php echo $successMessage; ?></div>
    <?php endif; ?>

    <div class="add-product-container">
        <button class="add-product-button" onclick="showForm()">Add Product</button>
    </div>
    <div class="container" id="productFormContainer" style="display: none;">
        <h2>Add Product</h2>
        <input type="text" id="addProductName" placeholder="Product Name">
        <input type="text" id="addProductId" placeholder="Product ID">
        <input type="text" id="addPrice" placeholder="Price">
        <div>
            <button type="button" class="submit-button" onclick="addProduct()">Submit</button>
            <button type="button" class="close-button" onclick="hideForm()">Close</button>
        </div>
    </div>

    <table>
        <thead>
            <tr>
                <th>Sl No</th>
                <th>Product Name</th>
                <th>Product ID</th>
                <th>Price</th>
                <th>Total Quantity</th>
                <th>Total Price</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $result = getProductAggregatedData($offset, $limit);
            $sl_no = $offset + 1; // Adjust the serial number based on the current page
            while ($row = mysqli_fetch_assoc($result)) {
                echo "<tr id='row-{$row['id']}' data-name='{$row['Product_name']}' data-productid='{$row['Product_id']}' data-price='{$row['price']}'>";
                echo "<td>{$sl_no}</td>";
                echo "<td>{$row['Product_name']}</td>";
                echo "<td>{$row['Product_id']}</td>";
                echo "<td>{$row['price']}</td>";
                echo "<td>{$row['total_quantity']}</td>";
                echo "<td>{$row['total_price']}</td>";
                echo "<td>
                    <button class='edit-button' onclick='editProduct({$row['id']})'>Edit</button>
                    <button class='btn btn-danger btn-sm'>
                        <a href='add_product.php?category={$row['Product_id']}' style='color: white; text-decoration: none;'>Add</a>
                    </button>
                </td>";
                echo "</tr>";
                $sl_no++;
            }
            ?>
        </tbody>
    </table>

    <div class="pagination">
        <?php if ($page > 1): ?>
            <a href="?page=<?php echo $page - 1; ?>">Previous</a>
        <?php endif; ?>
        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
            <a href="?page=<?php echo $i; ?>" class="<?php echo $i == $page ? 'active' : ''; ?>"><?php echo $i; ?></a>
        <?php endfor; ?>
        <?php if ($page < $totalPages): ?>
            <a href="?page=<?php echo $page + 1; ?>">Next</a>
        <?php endif; ?>
    </div>
</body>
</html>
<?php $con->close(); ?>
