<?php
session_start();

// Enforce login
if (!isset($_SESSION['user_id'])) {
    $_SESSION['redirect_after_login'] = 'checkout.php';
    header('Location: login.php');
    exit();
}

// Handle inactivity auto logout (10 min)
$inactiveLimit = 600;
if (isset($_SESSION['last_activity']) && time() - $_SESSION['last_activity'] > $inactiveLimit) {
    session_unset();
    session_destroy();
    header('Location: login.php');
    exit();
}
$_SESSION['last_activity'] = time();

$cart = $_SESSION['cart'] ?? [];
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Responsive scaling -->
  <title>Checkout - Taji Yetu</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">

  <!-- Sidebar CSS -->
  <link rel="stylesheet" href="admin-sidebar.css">

  <style>
    /* Checkout page content */
    .checkout-container {
      display:flex;
      flex-wrap:wrap;
      gap:30px;
      max-width:1200px;
      margin:30px auto;
      padding:20px;
    }
    .cart-box, form {
      background:rgba(30,30,30,0.95);
      padding:25px;
      border-radius:10px;
      flex:1 1 450px;
      box-shadow:0 6px 20px rgba(0,0,0,0.4);
      color:#fff;
    }
    h2, h4 { text-align:center; margin-bottom:20px; }
    input, textarea {
      width:100%; padding:10px; margin-bottom:15px;
      border-radius:6px; border:none;
      font-size:14px;
    }
    button {
      background:#28a745; color:white;
      padding:12px; border:none; border-radius:6px;
      cursor:pointer; width:100%; font-size:16px; font-weight:bold;
    }
    button:hover { background:#218838; }
    #cart-items ul { list-style:none; padding:0; margin:0; }
    #cart-items li {
      display:flex; align-items:center; justify-content:space-between;
      gap:10px; padding:10px 0; border-bottom:1px solid #444;
    }
    #cart-items img {
      width:60px; height:60px; object-fit:cover; border-radius:5px;
    }
    .item-info { flex-grow:1; }
    .item-price { min-width:80px; text-align:right; }
    .total { font-weight:bold; text-align:right; margin-top:10px; }
    .tip-section { display:flex; flex-wrap:wrap; gap:10px; margin-bottom:20px; }
    .tip-section label {
      background:#222; padding:8px 12px; border-radius:6px;
      border:1px solid #444; cursor:pointer; display:flex; align-items:center; gap:5px;
    }
    .tip-section input[type="radio"] { accent-color:#28a745; cursor:pointer; }
    .notes-label { font-weight:bold; margin:10px 0 5px; display:block; }
    textarea#notes { height:100px; resize:vertical; }
    .action-buttons { display:flex; justify-content:space-between; gap:10px; }
    .action-buttons a, .action-buttons button { flex:1; }

    /* Admin layout (copied from dashboard) */
    .dashboard-wrapper {
      display: flex;
      min-height: calc(100vh - 60px); /* offset navbar height */
      margin-top: 60px; /* since navbar is fixed */
    }
    .main-content {
      flex: 1;
      padding: 20px;
      background: url('images/bg.jpg') center/cover no-repeat fixed;
      color: #fff;
    }
  </style>
</head>
<body>

<?php include "navbar.php"; ?>

<div class="dashboard-wrapper">
  <?php if (!empty($_SESSION['is_admin']) && $_SESSION['is_admin'] == 1): ?>
    <?php include "admin-sidebar.php"; ?>
  <?php endif; ?>

  <div class="main-content">
    <div class="checkout-container">
      <div class="cart-box">
        <h4>Your Cart</h4>
        <div id="cart-items">
          <ul id="items-list"></ul>
          <div class="total" id="subtotal">Subtotal: Ksh 0</div>
          <div class="total">Shipping Fee: Ksh 300</div>
          <div class="total">Tip: <span id="tip-amount">Ksh 0</span></div>
          <div class="total" id="total-price">Total: Ksh 0</div>
        </div>
      </div>

      <form id="checkout-form">
        <input type="text" name="name" id="name" placeholder="Full Name" required />
        <input type="tel" name="phone" id="phone" placeholder="Phone Number" required />
        <textarea name="address" id="address" placeholder="Delivery Address" required></textarea>

        <div class="tip-section">
          <label><input type="radio" name="tipOption" value="5"> 5%</label>
          <label><input type="radio" name="tipOption" value="10"> 10%</label>
          <label><input type="radio" name="tipOption" value="15"> 15%</label>
          <label><input type="radio" name="tipOption" value="20"> 20%</label>
          <label>Custom Tip (KES): <input type="number" id="customTip" min="0" style="width:80px;" /></label>
        </div>

        <label for="notes" class="notes-label">Leave us a note</label>
        <textarea name="notes" id="notes" placeholder="e.g., Deliver Monday only or call before delivery"></textarea>

        <div class="action-buttons">
          <a href="listing.php"><button type="button">Keep Shopping</button></a>
          <button type="submit">Pay</button>
        </div>
      </form>
    </div>
  </div>
</div>


<script src="admin-sidebar.js"></script>
<script>
const itemsList = document.getElementById('items-list');
const subtotalEl = document.getElementById('subtotal');
const totalEl = document.getElementById('total-price');
const tipAmountEl = document.getElementById('tip-amount');
const customTipInput = document.getElementById('customTip');
const SHIPPING_FEE = 300;
let subtotal = 0;

// Fetch cart items
fetch('get_cart.php')
  .then(res => res.json())
  .then(data => {
    const cart = data.cart || [];
    if (cart.length === 0) {
      itemsList.innerHTML = '<li>Your cart is empty.</li>';
      return;
    }
    cart.forEach(item => {
      const li = document.createElement('li');
      const quantity = parseInt(item.quantity) || 1;
      const price = parseFloat(item.price.toString().replace(/[^\d.-]/g, ''));
      const lineTotal = quantity * price;
      subtotal += lineTotal;
      const img = document.createElement('img');
      img.src = item.image && item.image.trim() !== '' ? `uploads/${item.image}` : 'images/placeholder.png';
      img.alt = item.name || 'Product';
      const info = document.createElement('div');
      info.className = 'item-info';
      info.innerHTML = `<strong>${item.name}</strong><br>(${quantity}x)`;
      const priceEl = document.createElement('div');
      priceEl.className = 'item-price';
      priceEl.textContent = `Ksh ${lineTotal.toLocaleString()}`;
      li.appendChild(img);
      li.appendChild(info);
      li.appendChild(priceEl);
      itemsList.appendChild(li);
    });
    subtotalEl.textContent = `Subtotal: Ksh ${subtotal.toLocaleString()}`;
    updateTotal();
  });

function getTipValue() {
  const selectedRadio = document.querySelector('input[name="tipOption"]:checked');
  const custom = parseInt(customTipInput.value);
  if (!isNaN(custom) && custom > 0) {
    if (selectedRadio) selectedRadio.checked = false;
    return custom;
  }
  if (selectedRadio) {
    const percent = parseInt(selectedRadio.value);
    return Math.round((subtotal * percent) / 100);
  }
  return 0;
}

function updateTotal() {
  const tip = getTipValue();
  const finalTotal = subtotal + SHIPPING_FEE + tip;
  tipAmountEl.textContent = `Ksh ${tip.toLocaleString()}`;
  totalEl.textContent = `Total: Ksh ${finalTotal.toLocaleString()}`;
}

document.querySelectorAll('input[name="tipOption"]').forEach(radio => {
  radio.addEventListener('change', () => {
    customTipInput.value = '';
    updateTotal();
  });
});

customTipInput.addEventListener('input', updateTotal);

// Handle checkout form submit
document.getElementById('checkout-form').addEventListener('submit', function(e) {
  e.preventDefault();
  const name = this.name.value;
  const phone = this.phone.value;
  const address = this.address.value;
  const notes = this.notes.value;
  const tipAmount = getTipValue();

  fetch('process_payment.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name, phone, address, notes, tip: tipAmount, shipping: SHIPPING_FEE })
  })
  .then(res => res.text())
  .then(data => {
    alert(data);
    window.location.href = 'thankyou.html';
  })
  .catch(err => {
    console.error(err);
    alert("Something went wrong!");
  });
});
</script>
</body><?php include "footer.php"; ?>
</html>
