<?php
session_start();
require_once 'db.php';

// 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();

// Fetch user info
$user_name = 'User';
$profile_pic = 'default.png';
try {
    $stmt = $conn->prepare("SELECT firstName, profile_pic FROM users WHERE id=?");
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($user) {
        $user_name = $user['firstName'] ?? 'User';
        $profile_pic = $user['profile_pic'] ?? 'default.png';
    }
} catch (PDOException $e) {}

// Fetch cart items
$cart_items = [];
$subtotal = 0;
try {
    $user_id = $_SESSION['user_id'];
    $session_token = session_id();

    $stmt = $conn->prepare("SELECT id FROM carts WHERE user_id=?");
    $stmt->execute([$user_id]);
    $cart = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$cart) {
        $stmt = $conn->prepare("INSERT INTO carts (user_id, session_token) VALUES (?, ?)");
        $stmt->execute([$user_id, $session_token]);
        $cart_id = $conn->lastInsertId();
    } else {
        $cart_id = $cart['id'];
    }

    $stmt = $conn->prepare("
        SELECT ci.id, ci.product_id, ci.qty, ci.price, p.name, p.image
        FROM cart_items ci
        LEFT JOIN products p ON ci.product_id = p.id
        WHERE ci.cart_id=?
    ");
    $stmt->execute([$cart_id]);
    $cart_items = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($cart_items as $k => $item) {
        $cart_items[$k]['subtotal'] = $item['qty'] * $item['price'];
        $subtotal += $cart_items[$k]['subtotal'];
        $cart_items[$k]['image'] = $item['image'] ? "uploads/".$item['image'] : "images/placeholder.png";
    }

} catch (PDOException $e) {}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Checkout - Taji Yetu</title>
<link rel="icon" href="images/taji-yetu.png" type="image/png">
<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="admin-sidebar.css">
<style>
body, html { margin:0; padding:0; height:100%; font-family:Arial, sans-serif; background:#000; color:#fff; overflow-x:hidden; position:relative; }
.dashboard-wrapper { display:flex; min-height:100vh; margin-top:60px; position:relative; }
.main-content { flex:1; padding:20px; position:relative; z-index:1; }

.checkout-card { 
    max-width:800px; 
    margin:40px auto; 
    background:#111; 
    border-radius:12px; 
    box-shadow:0 6px 20px rgba(255,255,255,0.1); 
    padding:25px; 
    color:#fff; 
    animation: fadeIn 0.6s ease-in-out;
}

@keyframes fadeIn {
    0% {opacity:0; transform: translateY(20px);}
    100% {opacity:1; transform: translateY(0);}
}

.checkout-card h4 { margin-bottom:15px; font-weight:600; letter-spacing:0.5px; text-align:center; }

#cart-items ul { list-style:none; padding:0; margin:0 0 20px 0; width:100%; }
#cart-items li { display:flex; align-items:center; justify-content:space-between; gap:15px; padding:12px 0; border-bottom:1px solid #333; }
#cart-items img { width:70px; height:70px; object-fit:cover; border-radius:8px; }
.item-info { flex-grow:1; display:flex; flex-direction:column; align-items:flex-start; gap:6px; }
.item-info strong { font-size:15px; }
.item-price { min-width:90px; text-align:right; font-weight:600; }

input[type="number"], textarea { 
    width:100%; 
    padding:10px; 
    margin-top:10px; 
    border-radius:8px; 
    border:none; 
    background:#222; 
    color:#fff; 
    resize:none; 
    min-height:50px; 
    animation: fadeInInput 0.5s ease-in-out; 
}

@keyframes fadeInInput {
    0% {opacity:0; transform: translateY(10px);}
    100% {opacity:1; transform: translateY(0);}
}

button, .action-buttons button { 
    background:#000; 
    color:#fff; 
    border:2px solid #fff; 
    border-radius:6px; 
    padding:8px 12px; 
    cursor:pointer; 
    transition:0.2s; 
}
button:hover, .action-buttons button:hover { 
    background:#fff; 
    color:#000; 
}

.action-buttons { display:flex; flex-wrap:wrap; gap:10px; margin-top:15px; justify-content:center; }

.total { font-weight:bold; font-size:16px; margin-top:12px; text-align:center; }
.tip-section { display:flex; flex-wrap:wrap; gap:8px; justify-content:center; margin-top:12px; }
.tip-section label { background:#222; padding:6px 10px; border-radius:6px; cursor:pointer; font-size:14px; border:1px solid #444; display:flex; align-items:center; gap:4px; }
.tip-section input[type="radio"] { accent-color:#FF7F00; cursor:pointer; }
#clearTip { padding:6px 10px; font-size:14px; background:#333; }

.profile-pic { width:80px; height:80px; border-radius:50%; object-fit:cover; margin:0 auto 15px auto; border:3px solid #fff; display:block; }

.bg-overlay { position:fixed; top:0; left:0; width:100%; height:100%; z-index:0; pointer-events:none; }

@media(max-width:768px){ .checkout-card { padding:20px; } }
</style>
</head>
<body>
<?php include "navbar.php"; ?>
<div class="dashboard-wrapper">
<?php if(!empty($_SESSION['is_admin']) && $_SESSION['is_admin']==1){ include "admin-sidebar.php"; } ?>
<div class="bg-overlay"><canvas id="bgCanvas"></canvas></div>

<div class="main-content">
    <div class="checkout-card">
        <img src="<?php echo htmlspecialchars($profile_pic); ?>" class="profile-pic" alt="Profile">
        <h4>Hi <?php echo htmlspecialchars($user_name); ?>, thank you for shopping with us!</h4>

        <!-- Cart items -->
        <div id="cart-items">
            <ul id="items-list">
                <?php if(count($cart_items) > 0): 
                    foreach($cart_items as $item): ?>
                    <li>
                        <img src="<?php echo $item['image']; ?>" alt="<?php echo htmlspecialchars($item['name']); ?>">
                        <div class="item-info">
                            <strong><?php echo htmlspecialchars($item['name']); ?></strong>
                            Quantity: <?php echo $item['qty']; ?>
                        </div>
                        <div class="item-price">Ksh <?php echo number_format($item['subtotal']); ?></div>
                    </li>
                    <?php endforeach; 
                else: ?>
                    <li>Your cart is empty. <a href="listing.php">Shop now</a></li>
                <?php endif; ?>
            </ul>

            <!-- Tip section -->
            <div class="total" id="subtotal">Subtotal: Ksh <?php echo number_format($subtotal); ?></div>
            <div class="tip-section">
                <label>5%<input type="radio" name="tipOption" value="5"></label>
                <label>10%<input type="radio" name="tipOption" value="10"></label>
                <label>15%<input type="radio" name="tipOption" value="15"></label>
                <label>20%<input type="radio" name="tipOption" value="20"></label>
                <label>Custom: <input type="number" id="customTip" min="0"></label>
                <button type="button" id="clearTip">Clear Tip</button>
            </div>
            <div class="total" id="tip-amount">Tip: Ksh 0</div>
            <div class="total" id="total-price">Total: Ksh <?php echo number_format($subtotal); ?></div>

            <!-- Checkout form -->
            <form id="checkout-form">
                <textarea name="address" id="address" placeholder="Delivery Address" required></textarea>
                <textarea name="notes" id="notes" placeholder="Leave a note (optional)"></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>
</div>

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

<script>
// Background particle animation
const canvas = document.getElementById('bgCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let particles = [];
for(let i=0;i<80;i++){ particles.push({x:Math.random()*canvas.width,y:Math.random()*canvas.height,r:Math.random()*2+1}); }
function animateParticles(){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    particles.forEach(p=>{
        ctx.beginPath();
        ctx.arc(p.x,p.y,p.r,0,Math.PI*2);
        ctx.fillStyle='white';
        ctx.fill();
        p.y -= 0.3;
        if(p.y<0) p.y=canvas.height;
    });
    requestAnimationFrame(animateParticles);
}
animateParticles();
window.addEventListener('resize',()=>{ canvas.width=window.innerWidth; canvas.height=window.innerHeight; });

// Tip calculation
const subtotalEl = document.getElementById('subtotal');
const totalEl = document.getElementById('total-price');
const tipAmountEl = document.getElementById('tip-amount');
const customTipInput = document.getElementById('customTip');
const clearTipBtn = document.getElementById('clearTip');
let subtotal = <?php echo $subtotal; ?>;

function updateTotal(){
    let tip = 0;
    const selected = document.querySelector('input[name="tipOption"]:checked');
    const custom = parseInt(customTipInput.value);
    if(!isNaN(custom) && custom>0){ if(selected) selected.checked=false; tip=custom; }
    else if(selected){ tip = Math.round(subtotal * parseInt(selected.value)/100); }
    totalEl.textContent = `Total: Ksh ${(subtotal+tip).toLocaleString()}`;
    tipAmountEl.textContent = `Tip: Ksh ${tip.toLocaleString()}`;
}
document.querySelectorAll('input[name="tipOption"]').forEach(r=>r.addEventListener('change', updateTotal));
customTipInput.addEventListener('input', updateTotal);
clearTipBtn.addEventListener('click', ()=>{
    customTipInput.value = '';
    document.querySelectorAll('input[name="tipOption"]').forEach(r=>r.checked=false);
    updateTotal();
});
updateTotal();
</script>
</body>
</html>
