<?php

declare(strict_types=1);

require_once '../../private/db.php';
require_once '../../private/auth.php';

require_login();

$stmt = $pdo->query("
SELECT *
FROM products
WHERE active = 1
ORDER BY name ASC
");

$products = $stmt->fetchAll();

?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>EpiPos POS</title>

<script src="https://js.stripe.com/terminal/v1/"></script>

<style>

body{
margin:0;
font-family:Arial;
background:#111827;
color:#fff;
}

.topbar{
background:#000;
padding:20px;
display:flex;
justify-content:space-between;
align-items:center;
}

.topbar a{
color:#fff;
text-decoration:none;
margin-left:15px;
}

.container{
display:flex;
}

.products{
width:70%;
padding:20px;
display:grid;
grid-template-columns:repeat(auto-fill,minmax(240px,1fr));
gap:20px;
}

.card{
background:#1f2937;
border-radius:12px;
overflow:hidden;
}

.product-image{
width:100%;
height:220px;
background:#0f172a;
display:flex;
align-items:center;
justify-content:center;
overflow:hidden;
}

.product-image img{
width:100%;
height:100%;
object-fit:cover;
}

.card-content{
padding:20px;
}

.card button{
width:100%;
padding:12px;
background:#2563eb;
border:none;
border-radius:8px;
color:#fff;
cursor:pointer;
}

.cart{
width:30%;
background:#0f172a;
padding:20px;
min-height:100vh;
}

.cart-item{
padding:10px 0;
border-bottom:1px solid #374151;
}

.checkout-btn{
width:100%;
padding:14px;
margin-top:10px;
border:none;
border-radius:8px;
cursor:pointer;
font-size:15px;
}

.cash{
background:#059669;
color:#fff;
}

.cardpay{
background:#2563eb;
color:#fff;
}

#connectBtn{
background:red;
color:#fff;
width:100%;
padding:14px;
margin-top:10px;
border:none;
border-radius:8px;
cursor:pointer;
font-size:15px;
}

#readerStatus{
margin-top:10px;
background:#111827;
padding:10px;
border-radius:8px;
min-height:20px;
}

.customer-box input{
width:100%;
padding:12px;
margin-bottom:10px;
border:none;
border-radius:8px;
}

</style>

</head>
<body>

<div class="topbar">

<div>
<strong>EpiPos POS</strong>
</div>

<div>
<a href="dashboard.php">Dashboard</a>
<a href="inventory.php">Inventory</a>
<a href="customers.php">Customers</a>
<a href="reports.php">Reports</a>
<a href="settings.php">Settings</a>
<a href="logout.php">Logout</a>
</div>

</div>

<div class="container">

<div class="products">

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

<div class="card">

<div class="product-image">

<?php if(!empty($product['image'])): ?>

<img
src="images/<?= htmlspecialchars($product['image']) ?>"
alt="<?= htmlspecialchars($product['name']) ?>"
>

<?php else: ?>

<div>No Image</div>

<?php endif; ?>

</div>

<div class="card-content">

<h3><?= htmlspecialchars($product['name']) ?></h3>

<p>SKU: <?= htmlspecialchars($product['sku']) ?></p>

<p>
Price:
$<?= number_format((float)$product['price'],2) ?>
</p>

<p>
Stock:
<?= (int)$product['quantity'] ?>
</p>

<button onclick="addToCart(
<?= (int)$product['id'] ?>,
'<?= htmlspecialchars($product['name'],ENT_QUOTES) ?>',
<?= (float)$product['price'] ?>
)">
Add To Cart
</button>

</div>

</div>

<?php endforeach; ?>

</div>

<div class="cart">

<h2>Shopping Cart</h2>

<div id="cart-items"></div>

<h3 id="cart-total">$0.00</h3>

<div class="customer-box">

<input
type="email"
id="customer_email"
placeholder="Customer Email">

<input
type="text"
id="customer_phone"
placeholder="Customer Phone">

</div>

<button
class="checkout-btn cash"
onclick="window.location.href='pos_cash_ready.php'">
Cash Checkout
</button>

<button
class="checkout-btn cardpay"
onclick="startStripeCheckout()">
Stripe Terminal Checkout
</button>

<button
id="connectBtn"
onclick="connectReader()">
Connect WisePOS E Reader
</button>

<div id="readerStatus"></div>

</div>

</div>

<script>

let cart = [];

let terminal = null;

let connectedReader = null;

function addToCart(id,name,price){

cart.push({
id:id,
name:name,
price:parseFloat(price)
});

renderCart();

}

function renderCart(){

let html = '';
let total = 0;

cart.forEach((item)=>{

total += item.price;

html += `
<div class="cart-item">
${item.name} - $${item.price.toFixed(2)}
</div>
`;

});

document.getElementById('cart-items').innerHTML = html;

document.getElementById('cart-total').innerHTML =
'$' + total.toFixed(2);

}

function setStatus(message){

document.getElementById(
'readerStatus'
).innerHTML = message;

}

async function initializeTerminal(){

terminal = StripeTerminal.create({

onFetchConnectionToken: async () => {

const response = await fetch(
'api/terminal_connection_token.php',
{
method:'POST'
}
);

const data = await response.json();

return data.secret;
},

onUnexpectedReaderDisconnect: () => {

connectedReader = null;

document.getElementById(
'connectBtn'
).style.background='red';

setStatus('');

}

});

}

async function connectReader(){

try{

if(!terminal){
await initializeTerminal();
}

setStatus('Discovering readers...');

const discoverResult =
await terminal.discoverReaders({
simulated:false
});

if(discoverResult.error){

setStatus(discoverResult.error.message);

return;
}

if(discoverResult.discoveredReaders.length === 0){

setStatus('No readers found');

return;
}

const selectedReader =
discoverResult.discoveredReaders[0];

setStatus('Connecting to reader...');

const connectResult =
await terminal.connectReader(
selectedReader
);

if(connectResult.error){

setStatus(connectResult.error.message);

return;
}

connectedReader =
connectResult.reader;

document.getElementById(
'connectBtn'
).style.background='gray';

setStatus(
'Connected to: ' +
connectedReader.label
);

}catch(error){

setStatus(error.message);

}

}

async function startStripeCheckout(){

if(cart.length < 1){

alert('Cart empty');

return;
}

if(!connectedReader){

alert('Connect WisePOS E Reader first');

return;
}

const total =
parseFloat(
document.getElementById('cart-total')
.innerText.replace('$','')
);

const response = await fetch(
'api/create_terminal_payment.php',
{
method:'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify({
amount:total
})
}
);

const data = await response.json();

if(data.error){

alert(data.error);

return;
}

const collectResult =
await terminal.collectPaymentMethod(
data.client_secret
);

if(collectResult.error){

alert(collectResult.error.message);

return;
}

const processResult =
await terminal.processPayment(
collectResult.paymentIntent
);

if(processResult.error){

alert(processResult.error.message);

return;
}

await fetch(
'api/save_terminal_order.php',
{
method:'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify({
payment_intent:
processResult.paymentIntent.id,
amount:total,
email:
document.getElementById('customer_email').value,
phone:
document.getElementById('customer_phone').value,
cart:cart
})
}
);

window.location =
'receipt.php?pi=' +
processResult.paymentIntent.id;

}

</script>

</body>
</html>
