<?php
session_start();
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'cashier') {
    header("Location: login.php");
    exit();
}

include("db_connect.php");

// ---------------------------
// Generate Unique Receipt ID
// ---------------------------
function generateReceiptID() {
    return 'RCP-' . date('ymd-His') . '-' . rand(1000,9999);
}

// ---------------------------
// Handle Form Submission
// ---------------------------
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['product_id'])) {
    $receipt_id = generateReceiptID();
    $_SESSION['receipt_id'] = $receipt_id;

    foreach ($_POST['product_id'] as $index => $product_id) {
        $product_id = intval($product_id);
        $quantity = floatval($_POST['quantity'][$index]);
        $sell_price = floatval($_POST['selling_price'][$index]); // cashier can adjust
        $datetime = date('Y-m-d H:i:s');
        $cashier = $_SESSION['username'];

        // Fetch product info including weighted average buying price
        $query = "SELECT name, buying_price AS avg_buying_price, selling_price AS default_selling_price, quantity 
                  FROM products WHERE id = $product_id";
        $result = mysqli_query($conn, $query);
        $product = mysqli_fetch_assoc($result);

        if ($product && $quantity > 0) {
            $product_name = $product['name'];
            $buy_price = floatval($product['avg_buying_price']);
            $stock = intval($product['quantity']);
            $default_sell_price = floatval($product['default_selling_price']);

            if ($quantity <= $stock) {
                $total = $sell_price * $quantity;
                $profit = ($sell_price - $buy_price) * $quantity;
                $discount = max(0, $default_sell_price - $sell_price);

                // Insert sale
                $insert = "INSERT INTO sales (
                    receipt_id, sale_datetime, cashier, product_id, quantity,
                    buying_price, selling_price, total_sale, profit, discount, refunded
                ) VALUES (
                    '$receipt_id', '$datetime', '$cashier', $product_id, $quantity,
                    $buy_price, $sell_price, $total, $profit, $discount, 0
                )";
                mysqli_query($conn, $insert);

                // Update product stock
                $new_stock = $stock - $quantity;
                mysqli_query($conn, "UPDATE products SET quantity = $new_stock WHERE id = $product_id");

            } else {
                $message = "❌ Not enough stock for $product_name.";
            }
        }
    }

    header("Location: receipt.php?id=$receipt_id");
    exit();
}

// ---------------------------
// Pagination & Entries Selector
// ---------------------------
$entries_options = [20, 50, 100];
$entries = isset($_GET['entries']) ? $_GET['entries'] : 20;

$today = date('Y-m-d');

if ($entries === 'all') {
    $sales_query = "
        SELECT s.*, p.name AS product_name
        FROM sales s
        JOIN products p ON s.product_id = p.id
        WHERE DATE(s.sale_datetime) = '$today'
        ORDER BY s.id DESC
    ";
} else {
    $entries = intval($entries);
    $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
    $offset = ($page - 1) * $entries;

    $sales_query = "
        SELECT s.*, p.name AS product_name
        FROM sales s
        JOIN products p ON s.product_id = p.id
        WHERE DATE(s.sale_datetime) = '$today'
        ORDER BY s.id DESC
        LIMIT $entries OFFSET $offset
    ";
}

$sales = mysqli_query($conn, $sales_query);

// Fetch grand totals
$totals_query = mysqli_query($conn, "
    SELECT SUM(total_sale) AS grand_total_sale, SUM(profit) AS grand_total_profit, SUM(discount) AS grand_total_discount
    FROM sales
    WHERE DATE(sale_datetime) = '$today'
");
$totals_row = mysqli_fetch_assoc($totals_query);
$grand_total_sale = $totals_row['grand_total_sale'] ?? 0;
$grand_total_profit = $totals_row['grand_total_profit'] ?? 0;
$grand_total_discount = $totals_row['grand_total_discount'] ?? 0;

// Fetch products for sale
$product_list = mysqli_query($conn, "SELECT * FROM products WHERE quantity > 0");
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Cashier POS - Record Sales</title>
    <style>
        body { font-family: Arial; background: #f4f4f4; margin:0; padding:20px; }
        .container { width: 95%; max-width:1200px; margin:auto; background:white; padding:20px; border-radius:10px; box-shadow:0 3px 10px rgba(0,0,0,0.1);}
        h2 { text-align:center; color:#007bff; margin-bottom:20px; }
        form select, form input { padding:10px; margin-bottom:10px; width:100%; }
        .btn { background:#28a745; color:white; padding:10px 15px; border:none; cursor:pointer; border-radius:5px; }
        .btn:hover { background:#218838; }
        a.button { display:inline-block; padding:10px 15px; margin:10px 0; background:#007bff; color:white; text-decoration:none; border-radius:5px;}
        a.button:hover { background:#0056b3; }
        table { width:100%; border-collapse: collapse; margin-top:20px; }
        th, td { border:1px solid #ddd; padding:10px; text-align:center; }
        th { background:#007bff; color:white; position:sticky; top:0; }
        tr:nth-child(even){ background:#f9f9f9; }
        tr:hover { background:#f1f1f1; }
        .totals-row { font-weight:bold; background:#e2e3e5; }
        .entries-form { display:flex; gap:10px; margin-bottom:10px; align-items:center; flex-wrap:wrap;}
        .entries-form select { width:auto; }
    </style>
</head>
<body>
<div class="container">
    <h2>Cashier POS - Record Sale</h2>

    <!-- Sale Form -->
    <form method="POST">
        <div id="product-rows">
            <div class="product-row">
                <select name="product_id[]">
                    <?php while($row = mysqli_fetch_assoc($product_list)): ?>
                        <option value="<?= $row['id'] ?>"><?= $row['name'] ?> (Stock: <?= $row['quantity'] ?> | Price: <?= number_format($row['selling_price'],2) ?>)</option>
                    <?php endwhile; ?>
                </select>
                <input type="number" name="quantity[]" placeholder="Quantity" min="1" required>
                <input type="number" name="selling_price[]" placeholder="Selling Price (KES)" step="0.01" required>
            </div>
        </div>
        <button type="button" class="btn" onclick="addRow()">Add More Products</button><br><br>
        <button type="submit" class="btn">Submit Sale & View Receipt</button>
    </form>

    <script>
        function addRow() {
            const row = document.querySelector('.product-row').cloneNode(true);
            document.getElementById('product-rows').appendChild(row);
        }
    </script>

    <a href="cashier_dashboard.php" class="button">← Return to Dashboard</a>

    <!-- Entries selector -->
    <form method="GET" class="entries-form">
        <label>Show entries:</label>
        <select name="entries" onchange="this.form.submit()">
            <?php foreach($entries_options as $option): ?>
                <option value="<?= $option ?>" <?= ($entries == $option) ? 'selected' : '' ?>><?= $option ?></option>
            <?php endforeach; ?>
            <option value="all" <?= ($entries === 'all') ? 'selected' : '' ?>>All</option>
        </select>
    </form>

    <h3>Today's Sales</h3>
    <table>
        <tr>
            <th>Receipt</th>
            <th>Date</th>
            <th>Time</th>
            <th>Cashier</th>
            <th>Product</th>
            <th>Qty</th>
            <th>Buying Price (Avg)</th>
            <th>Selling Price</th>
            <th>Discount</th>
            <th>Total Sale</th>
            <th>Profit</th>
            <th>Refund</th>
        </tr>

        <?php
        $page_total_sale = 0;
        $page_total_profit = 0;
        $page_total_discount = 0;
        while($row = mysqli_fetch_assoc($sales)):
            $page_total_sale += $row['total_sale'];
            $page_total_profit += $row['profit'];
            $page_total_discount += $row['discount'];
        ?>
        <tr>
            <td><?= $row['receipt_id'] ?></td>
            <td><?= date('Y-m-d', strtotime($row['sale_datetime'])) ?></td>
            <td><?= date('H:i', strtotime($row['sale_datetime'])) ?></td>
            <td><?= $row['cashier'] ?></td>
            <td><?= $row['product_name'] ?></td>
            <td><?= $row['quantity'] ?></td>
            <td><?= number_format($row['buying_price'],2) ?></td>
            <td><?= number_format($row['selling_price'],2) ?></td>
            <td><?= number_format($row['discount'],2) ?></td>
            <td><?= number_format($row['total_sale'],2) ?></td>
            <td><?= number_format($row['profit'],2) ?></td>
            <td>
                <?php if($row['refunded']==0): ?>
                    <a class="btn" style="background:red;padding:6px 10px;" href="refund_sale.php?id=<?= $row['id'] ?>" onclick="return confirm('Refund this sale?')">Refund</a>
                <?php else: ?>
                    Refunded
                <?php endif; ?>
            </td>
        </tr>
        <?php endwhile; ?>

        <tr class="totals-row">
            <td colspan="8">Page Total</td>
            <td><?= number_format($page_total_discount,2) ?></td>
            <td><?= number_format($page_total_sale,2) ?></td>
            <td><?= number_format($page_total_profit,2) ?></td>
            <td></td>
        </tr>
        <tr class="totals-row">
            <td colspan="8">Grand Total (All Today)</td>
            <td><?= number_format($grand_total_discount,2) ?></td>
            <td><?= number_format($grand_total_sale,2) ?></td>
            <td><?= number_format($grand_total_profit,2) ?></td>
            <td></td>
        </tr>
    </table>
</div>
</body>
</html>
