<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
include 'php/db_connection.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

/* ---------- PRODUCT ID GENERATOR ---------- */
function generateProductId($con){
    do{
        $random = "2".rand(100000,999999);
        $check = mysqli_query($con,"SELECT Product_id FROM product_cat WHERE Product_id='$random'");
    }while(mysqli_num_rows($check) > 0);
    return $random;
}

$autoProductId = generateProductId($con);

/* ---------- DELETE PRODUCT (AJAX) ---------- */
if (isset($_POST['action']) && $_POST['action'] == 'deleteProduct') {

    $id = intval($_POST['id']);
    $get = mysqli_query($con,"SELECT Product_id FROM product_cat WHERE id=$id");

    if(mysqli_num_rows($get)>0){
        $row = mysqli_fetch_assoc($get);
        $productId = $row['Product_id'];

        mysqli_query($con,"DELETE FROM product WHERE product_id='$productId'");
        mysqli_query($con,"DELETE FROM product_cat WHERE id=$id");

        echo json_encode(["status"=>"success"]);
    }

    exit();
}

/* ---------- ADD PRODUCT ---------- */
if(isset($_POST['addProduct'])){

    $productName = mysqli_real_escape_string($con,$_POST['productName']);
    $price = $_POST['price'];
    $purchasePrice = $_POST['purchasePrice'];
    $supplier = $_POST['supplier'];

    $productId = generateProductId($con);

    $sql = "INSERT INTO product_cat
    (Product_name,Product_id,price,purchase_price,supplier_id)
    VALUES
    ('$productName','$productId','$price','$purchasePrice','$supplier')";

    if(mysqli_query($con,$sql)){
        header("Location: ".$_SERVER['PHP_SELF']."?success=1");
        exit();
    }else{
        echo "Database Error: ".mysqli_error($con);
    }
}

/* ---------- SUPPLIERS ---------- */
function getSuppliers(){
    global $con;
    return mysqli_query($con,"SELECT id,name FROM suppliers");
}

/* ---------- PAGINATION ---------- */
$limit = 20;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page-1)*$limit;

/* ---------- SEARCH ---------- */
$search = isset($_GET['search']) ? mysqli_real_escape_string($con,$_GET['search']) : '';
$where = "";
if($search!=""){
    $where="WHERE pc.Product_name LIKE '%$search%'
    OR pc.Product_id LIKE '%$search%'
    OR s.name LIKE '%$search%'";
}

/* ---------- PRODUCT LIST ---------- */
$result = mysqli_query($con,"
SELECT pc.*,s.name supplier_name,
SUM(p.quantity) total_quantity,
SUM(p.quantity*pc.price) total_price,
SUM(p.quantity*pc.purchase_price) total_purchase_price
FROM product_cat pc
LEFT JOIN suppliers s ON pc.supplier_id=s.id
LEFT JOIN product p ON pc.Product_id=p.product_id
$where
GROUP BY pc.id
ORDER BY pc.id DESC
LIMIT $offset,$limit
");

$count = mysqli_query($con,"SELECT COUNT(*) total FROM product_cat");
$totalProducts = mysqli_fetch_assoc($count)['total'];
$totalPages = ceil($totalProducts/$limit);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product Management</title>
<link rel="stylesheet" href="css/cusatom.css">

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

<style>
body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: #f8f9fa;
    margin: 0;
    padding: 0;
}
h2, h3 {
    color: #343a40;
}
form, table {
    background: #fff;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
input[type="text"], input[type="number"], select {
    padding: 10px;
    width: 100%;
    max-width: 300px;
    margin-bottom: 15px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 14px;
}
button {
    padding: 10px 18px;
    background: #007bff;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 14px;
}
button:hover {
    background: #0056b3;
}
.success {
    background: #28a745;
    color: #fff;
    padding: 12px 20px;
    border-radius: 5px;
    margin-bottom: 15px;
}
.search-box {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
    max-width: 1114px;
}
.search-box input[type="text"] {
    flex: 1;
}
.search-box button {
    margin: 0;
}
.clear-search {
    background: #6c757d !important;
}
.clear-search:hover {
    background: #5a6268 !important;
}
table {
    width: 100%;
    border-collapse: collapse;
}
table th, table td {
    padding: 12px 10px;
    border: 1px solid #dee2e6;
    text-align: center;
    font-size: 14px;
}
table th {
    background: #007bff;
    color: white;
}
table tr:nth-child(even) {
    background: #f2f2f2;
}
.action-button, .delete-button {
    border: none;
    background: transparent;
    cursor: pointer;
    font-size: 16px;
}
.action-button i, .delete-button i {
    color: #007bff;
}
.delete-button i {
    color: #dc3545;
}
.pagination {
    margin-top: 20px;
    font-size: 14px;
}
.pagination a {
    text-decoration: none;
    padding: 6px 12px;
    border: 1px solid #007bff;
    color: #007bff;
    margin: 0 5px;
    border-radius: 4px;
}
.pagination a:hover {
    background: #007bff;
    color: #fff;
}

@media(max-width:768px){
    table th, table td {
        font-size:12px;
        padding:8px;
    }
    .search-box {
        flex-direction: column;
        align-items: stretch;
    }
}
</style>

<script>
function deleteProduct(id){
    if(confirm("Delete Product?")){
        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){
                location.reload();
            }
        };
        xhr.send("action=deleteProduct&id="+id);
    }
}
</script>
</head>
<body>

<?php if(isset($_GET['success'])): ?>
<div class='success'>Product Added Successfully</div>
<?php endif; ?>

<h2>Add Product</h2>
<form method="POST" action="">
    <input type="text" name="productName" placeholder="Product Name" required>
    <input type="hidden" value="<?php echo $autoProductId ?>" readonly>
    <input type="number" step="0.01" name="purchasePrice" placeholder="Purchase Price" required>
    <input type="number" step="0.01" name="price" placeholder="Price" required>
    <input type="number" step="0.01" name="#" placeholder="Qty Not Working" required>
    <input type="date" step="0.01" name="#" placeholder="EX Date" required>
    <select name="supplier" required>
        <option value="">Select Supplier</option>
        <?php
        $suppliers=getSuppliers();
        while($s=mysqli_fetch_assoc($suppliers)){
            echo "<option value='{$s['id']}'>{$s['name']}</option>";
        }
        ?>
    </select>
    <button type="submit" name="addProduct">Add </button>
</form>

<h3>Product List</h3>
<div class="search-box">
    <form method="GET" style="flex:1; display:flex; gap:10px;">
        <input type="text" name="search" placeholder="Search product..." value="<?php echo $search ?>">
        <button type="submit">Search</button>
        <?php if($search!=""): ?>
            <a href="<?= $_SERVER['PHP_SELF'] ?>" class="clear-search">Clear</a>
        <?php endif; ?>
    </form>
</div>

<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Product ID</th>
<th>Price</th>
<th>Purchase Price</th>
<th>Supplier</th>
<th>Total Qty</th>
<th>Total Price</th>
<th>Total Purchase</th>
<th>Add</th>
<th>Barcode</th>
<th>Delete</th>
</tr>

<?php
if(mysqli_num_rows($result)>0){
    while($row=mysqli_fetch_assoc($result)){
?>
<tr>
<td><?= $row['id'] ?></td>
<td><?= $row['Product_name'] ?></td>
<td><?= $row['Product_id'] ?></td>
<td><?= $row['price'] ?></td>
<td><?= $row['purchase_price'] ?></td>
<td><?= $row['supplier_name'] ?></td>
<td><?= $row['total_quantity'] ?></td>
<td><?= $row['total_price'] ?></td>
<td><?= $row['total_purchase_price'] ?></td>
<td>
<a href="add_product.php?category=<?= urlencode($row['Product_id']) ?>" class="btn btn-primary"><i class="bi bi-plus-square"></i></a>
</td>
<td>
<button class="action-button" onclick="window.open('barcode_labels.php?search=<?= $row['Product_id'] ?>', '_blank')"><i class="fas fa-barcode"></i></button>
</td>
<td>
<button class='delete-button' onclick='deleteProduct(<?= $row["id"] ?>)'><i class="bi bi-trash"></i></button>
</td>
</tr>
<?php
    }
}else{
    echo "<tr><td colspan='13'>No Product Found</td></tr>";
}
?>
</table>

<div class="pagination">
<?php if($page>1){ ?>
<a href="?page=<?= $page-1 ?>&search=<?= $search ?>">Prev</a>
<?php } ?>
Page <?= $page ?> / <?= $totalPages ?>
<?php if($page<$totalPages){ ?>
<a href="?page=<?= $page+1 ?>&search=<?= $search ?>">Next</a>
<?php } ?>
</div>

</body>
</html>