<?php
session_start();

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

include_once "../config/database.php";

if(!isset($_SESSION['cart']))
{
    $_SESSION['cart']=[];
}

$customers=[];

$q=mysqli_query($conn,"SELECT id,customer_name FROM customers ORDER BY customer_name");

while($r=mysqli_fetch_assoc($q))
{
    $customers[]=$r;
}

$categories=[];

$q=mysqli_query($conn,"SELECT * FROM categories ORDER BY category_name");

while($r=mysqli_fetch_assoc($q))
{
    $categories[]=$r;
}

$products=[];

$q=mysqli_query($conn,"
SELECT
products.*,
categories.category_name
FROM products
LEFT JOIN categories
ON products.category_id=categories.id
WHERE products.status=1
ORDER BY products.product_name
");

while($r=mysqli_fetch_assoc($q))
{
    $products[]=$r;
}

$subtotal=0;

foreach($_SESSION['cart'] as $item)
{
    $subtotal+=$item['price']*$item['qty'];
}

?>

<?php include_once "../includes/header.php"; ?>
<?php include_once "../includes/sidebar.php"; ?>

<div class="overlay" id="overlay"></div>

<div class="main-content">

<?php include_once "../includes/topbar.php"; ?>

<div class="container-fluid py-4">

<div class="row g-4">

<div class="col-xl-8 col-lg-8 col-12">

<div class="card rounded-4 shadow border-0 mb-4">

<div class="card-body">

<div class="row g-3">

<div class="col-lg-8">

<div class="input-group">

<span class="input-group-text bg-white">

<i class="fa fa-search"></i>

</span>

<input
type="text"
id="productSearch"
class="form-control"
placeholder="Search Product / Barcode">

</div>

</div>

<div class="col-lg-4">

<select
class="form-select"
id="customer_id">

<option value="">

Walk-in Customer

</option>

<?php foreach($customers as $customer){ ?>

<option value="<?= $customer['id']; ?>">

<?= htmlspecialchars($customer['customer_name']); ?>

</option>

<?php } ?>

</select>

</div>

</div>

<div class="mt-4 d-flex flex-wrap gap-2">

<button
class="btn btn-primary categoryBtn"
data-id="all">

All

</button>

<?php foreach($categories as $cat){ ?>

<button
class="btn btn-outline-primary categoryBtn"
data-id="<?= $cat['id']; ?>">

<?= htmlspecialchars($cat['category_name']); ?>

</button>

<?php } ?>

</div>

</div>

</div>

<div class="row g-3" id="productGrid">

<?php foreach($products as $product){ ?>

<div
class="col-xl-3 col-lg-4 col-md-6 col-6 productItem"
data-category="<?= $product['category_id']; ?>"
data-search="<?= strtolower($product['product_name'].' '.$product['barcode'].' '.$product['sku']); ?>">

<div
class="card rounded-4 shadow border-0 h-100 addProduct"
data-id="<?= $product['id']; ?>"
style="cursor:pointer">

<div class="card-body text-center">

<?php

if(!empty($product['image']) && file_exists("../uploads/".$product['image']))
{

?>

<img
src="/beauty_pos/uploads/<?= $product['image']; ?>"
class="img-fluid mb-3"
style="height:90px;object-fit:contain;">

<?php
}
else
{
?>

<div
class="rounded-circle bg-light mx-auto d-flex align-items-center justify-content-center mb-3"
style="width:90px;height:90px;">

<i class="fa fa-box fa-2x text-secondary"></i>

</div>

<?php
}
?>

<h6 class="fw-bold mb-1">

<?= htmlspecialchars($product['product_name']); ?>

</h6>

<div class="text-success fw-bold fs-5">

₹<?= number_format($product['selling_price'],2); ?>

</div>

<small class="text-muted">

Stock :
<?= $product['stock']; ?>

</small>

</div>

</div>

</div>

<?php } ?>

</div>

</div>
<div class="col-xl-4 col-lg-4 col-12">

<div class="card rounded-4 shadow border-0 h-100">

<div class="card-header bg-white d-flex justify-content-between align-items-center">

<h5 class="mb-0">

<i class="fa fa-shopping-cart me-2"></i>

Current Sale

</h5>

<button
class="btn btn-sm btn-outline-danger"
id="clearCart">

<i class="fa fa-trash"></i>

</button>

</div>

<div
class="card-body p-0"
style="max-height:500px;overflow:auto;">

<?php

if(empty($_SESSION['cart']))
{

?>

<div class="text-center py-5 text-muted">

<i class="fa fa-shopping-basket fa-3x mb-3"></i>

<h6>No Product Added</h6>

<p class="mb-0">

Click any product to add into cart.

</p>

</div>

<?php

}
else
{

foreach($_SESSION['cart'] as $id=>$item)
{

$itemTotal=$item['qty']*$item['price'];

?>

<div class="border-bottom p-3">

<div class="d-flex justify-content-between">

<div>

<h6 class="mb-1">

<?= htmlspecialchars($item['name']); ?>

</h6>

<small>

₹<?= number_format($item['price'],2); ?>

</small>

</div>

<strong>

₹<?= number_format($itemTotal,2); ?>

</strong>

</div>

<div class="d-flex justify-content-between align-items-center mt-3">

<div class="btn-group">

<button
class="btn btn-outline-secondary decreaseQty"
data-id="<?= $id; ?>">

<i class="fa fa-minus"></i>

</button>

<input
type="text"
class="form-control text-center"
value="<?= $item['qty']; ?>"
style="width:60px"
readonly>

<button
class="btn btn-outline-secondary increaseQty"
data-id="<?= $id; ?>">

<i class="fa fa-plus"></i>

</button>

</div>

<button
class="btn btn-sm btn-danger removeItem"
data-id="<?= $id; ?>">

<i class="fa fa-trash"></i>

</button>

</div>

</div>

<?php

}

}

?>

</div>

<div class="card-footer bg-white">

<div class="d-flex justify-content-between mb-2">

<span>

Subtotal

</span>

<strong>

₹<?= number_format($subtotal,2); ?>

</strong>

</div>

<div class="mb-3">

<input
type="number"
class="form-control"
id="discount"
placeholder="Discount"
value="0">

</div>

<div class="mb-3">

<input
type="number"
class="form-control"
id="tax"
placeholder="Tax"
value="0">

</div>

<div class="d-flex justify-content-between fs-5 fw-bold">

<span>

Total

</span>

<span id="grandTotal">

₹<?= number_format($subtotal,2); ?>

</span>

</div>

<hr>

<div class="row g-2 mb-3">

<div class="col-6">
<button class="btn btn-success w-100 paymentBtn active" data-method="Cash">
Cash
</button>
</div>

<div class="col-6">
<button class="btn btn-outline-primary w-100 paymentBtn" data-method="Card">
Card
</button>
</div>

<div class="col-6">
<button class="btn btn-outline-dark w-100 paymentBtn" data-method="UPI">
UPI
</button>
</div>

<div class="col-6">
<button class="btn btn-outline-secondary w-100 paymentBtn" data-method="MTN MOMO">
MTN MOMO
<small class="d-block text-muted">673210025</small>
</button>
</div>

<div class="col-6">
<button class="btn btn-outline-info w-100 paymentBtn" data-method="ORANGE MONEY">
ORANGE MONEY
<small class="d-block text-muted">695505787</small>
</button>
</div>

<div class="col-6">
<button class="btn btn-outline-warning w-100 paymentBtn" data-method="Other">
Other
</button>
</div>

</div>
<div id="cashSection">

<div class="mb-3">

<label class="form-label fw-semibold">

Paid Amount

</label>

<input
type="number"
class="form-control"
id="paid"
placeholder="Enter Paid Amount">

</div>

<div class="mb-3">

<label class="form-label fw-semibold">

Change

</label>

<input
type="text"
class="form-control"
id="change"
value="0.00"
readonly>

</div>

</div>

<input
type="hidden"
id="payment_method"
value="Cash">

<div class="d-grid mb-2">

<button
class="btn btn-success btn-lg"
id="checkoutBtn">

<i class="fa fa-check-circle me-2"></i>

Checkout

</button>

</div>

<div class="d-grid">

<button
class="btn btn-outline-danger"
id="clearCart">

<i class="fa fa-trash me-2"></i>

Clear Cart

</button>

</div>

</div>

</div>

</div>

</div>

</div>

<script>

let paymentMethod="Cash";

document.querySelectorAll(".paymentBtn").forEach(function(btn){

btn.onclick=function(){

document.querySelectorAll(".paymentBtn").forEach(function(b){

b.classList.remove("btn-success");

b.classList.remove("active");

b.classList.add("btn-outline-primary");

});

this.classList.remove("btn-outline-primary");

this.classList.add("btn-success");

this.classList.add("active");

paymentMethod=this.dataset.method;

document.getElementById("payment_method").value=paymentMethod;

if(paymentMethod=="Cash")
{

document.getElementById("cashSection").style.display="block";

}
else
{

document.getElementById("cashSection").style.display="none";

let total=parseFloat(document.getElementById("grandTotal").innerText.replace("₹",""));

document.getElementById("paid").value=total.toFixed(2);

document.getElementById("change").value="0.00";

}

};

});

function calculateTotal()
{

let subtotal=<?= $subtotal ?>;

let discount=parseFloat(document.getElementById("discount").value)||0;

let tax=parseFloat(document.getElementById("tax").value)||0;

let total=subtotal-discount+tax;

if(total<0)
{

total=0;

}

document.getElementById("grandTotal").innerHTML="₹"+total.toFixed(2);

if(paymentMethod!="Cash")
{

document.getElementById("paid").value=total.toFixed(2);

}

calculateChange();

}

function calculateChange()
{

let total=parseFloat(document.getElementById("grandTotal").innerText.replace("₹",""));

let paid=parseFloat(document.getElementById("paid").value)||0;

let change=paid-total;

if(change<0)
{

change=0;

}

document.getElementById("change").value=change.toFixed(2);

}

document.getElementById("discount").onkeyup=calculateTotal;
document.getElementById("discount").onchange=calculateTotal;

document.getElementById("tax").onkeyup=calculateTotal;
document.getElementById("tax").onchange=calculateTotal;

document.getElementById("paid").onkeyup=calculateChange;
document.getElementById("paid").onchange=calculateChange;
calculateTotal();

/* Product Search */

document.getElementById("productSearch").addEventListener("keyup",function(){

let keyword=this.value.toLowerCase().trim();

document.querySelectorAll(".productItem").forEach(function(card){

let search=card.dataset.search;

if(search.indexOf(keyword)!==-1)
{

card.style.display="block";

}
else
{

card.style.display="none";

}

});

});

/* Category Filter */

document.querySelectorAll(".categoryBtn").forEach(function(btn){

btn.onclick=function(){

document.querySelectorAll(".categoryBtn").forEach(function(x){

x.classList.remove("btn-primary");

x.classList.add("btn-outline-primary");

});

this.classList.remove("btn-outline-primary");

this.classList.add("btn-primary");

let category=this.dataset.id;

document.querySelectorAll(".productItem").forEach(function(card){

if(category==="all")
{

card.style.display="block";

return;

}

if(card.dataset.category===category)
{

card.style.display="block";

}
else
{

card.style.display="none";

}

});

};

});

/* Add Product */

document.addEventListener("click",function(e){

const product=e.target.closest(".addProduct");

if(!product)
{

return;

}

fetch("/beauty_pos/ajax/add_to_cart.php?id="+product.dataset.id)

.then(response=>response.text())

.then(function(res){

if(res.trim()=="success")
{

location.reload();

}
else
{

alert(res);

}

});

});

/* Remove Product */

document.addEventListener("click",function(e){

const remove=e.target.closest(".removeItem");

if(!remove)
{

return;

}

fetch("/beauty_pos/ajax/remove_cart.php?id="+remove.dataset.id)

.then(response=>response.text())

.then(function(){

location.reload();

});

});

/* Increase Qty */

document.addEventListener("click",function(e){

const plus=e.target.closest(".increaseQty");

if(!plus)
{

return;

}

let qty=parseInt(
plus.parentElement.querySelector("input").value
)+1;

fetch("/beauty_pos/ajax/update_cart.php",{

method:"POST",

headers:{
"Content-Type":"application/x-www-form-urlencoded"
},

body:"id="+plus.dataset.id+"&qty="+qty

})

.then(response=>response.text())

.then(function(res){

if(res.trim()=="success")
{

location.reload();

}
else
{

alert(res);

}

});

});

/* Decrease Qty */

document.addEventListener("click",function(e){

const minus=e.target.closest(".decreaseQty");

if(!minus)
{

return;

}

let qty=parseInt(
minus.parentElement.querySelector("input").value
)-1;

if(qty<1)
{

qty=0;

}

fetch("/beauty_pos/ajax/update_cart.php",{

method:"POST",

headers:{
"Content-Type":"application/x-www-form-urlencoded"
},

body:"id="+minus.dataset.id+"&qty="+qty

})

.then(response=>response.text())

.then(function(){

location.reload();

});

});
/* Checkout */

document.getElementById("checkoutBtn").addEventListener("click",function(){

let customer=document.getElementById("customer_id").value;

let payment=document.getElementById("payment_method").value;

let discount=document.getElementById("discount").value;

let tax=document.getElementById("tax").value;

let paid=document.getElementById("paid").value;

this.disabled=true;

this.innerHTML='<i class="fa fa-spinner fa-spin me-2"></i>Processing...';

fetch("/beauty_pos/ajax/checkout.php",{

method:"POST",

headers:{
"Content-Type":"application/x-www-form-urlencoded"
},

body:
"customer_id="+encodeURIComponent(customer)+
"&payment_method="+encodeURIComponent(payment)+
"&discount="+encodeURIComponent(discount)+
"&tax="+encodeURIComponent(tax)+
"&paid="+encodeURIComponent(paid)

})

.then(response=>response.json())

.then(function(res){

if(res.status=="success")
{
    var invoice_no = res.invoice_no; // 🔥 FIX (IMPORTANT)

    if(confirm("Sale Completed Successfully\nInvoice : " + invoice_no + "\n\nPrint Receipt?")){
        window.open('/beauty_pos/sales/print.php?invoice='+invoice_no, '_blank');
    }

    window.location.reload();

}
else
{

alert(res.message);

document.getElementById("checkoutBtn").disabled=false;

document.getElementById("checkoutBtn").innerHTML='<i class="fa fa-check-circle me-2"></i>Checkout';

}

})

.catch(function(){

alert("Server Error.");

document.getElementById("checkoutBtn").disabled=false;

document.getElementById("checkoutBtn").innerHTML='<i class="fa fa-check-circle me-2"></i>Checkout';

});

});

/* Clear Cart */

document.getElementById("clearCart").addEventListener("click",function(){

if(!confirm("Are you sure you want to clear the cart?"))
{

return;

}

window.location.href="/beauty_pos/ajax/clear_cart.php";

});

</script>

<?php include_once "../includes/footer.php"; ?>

</div>