<?php
session_start();
require '../assets/db_connect.php';

// Redirect if not logged in or not seller
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'seller') {
    header("Location: ../login.php");
    exit;
}

// Fetch products with available batches
$stmt = $pdo->query("
    SELECT p.id AS product_id, p.name AS product_name, pb.id AS batch_id, pb.sell_price, pb.qty
    FROM products p
    JOIN product_batches pb ON pb.product_id = p.id
    WHERE pb.qty > 0
    ORDER BY p.name
");
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch customers
$customers = $pdo->query("SELECT * FROM customers ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

// Handle new sale submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['customer_id'])) {
    $customer_id = intval($_POST['customer_id']);
    $total = 0;

    // Insert new sale
    $stmt = $pdo->prepare("INSERT INTO sales (customer_id, total, status, created_by) VALUES (?, 0, 'open', ?)");
    $stmt->execute([$customer_id, $_SESSION['user']['id']]);
    $sale_id = $pdo->lastInsertId();

    foreach ($_POST['lines'] as $line) {
        $product_id = intval($line['product_id']);
        $batch_id   = intval($line['batch_id']);
        $qty        = intval($line['qty']);
        $unit_price = floatval($line['unit_price']);
        $discount   = floatval($line['discount']);
        $line_total = ($qty * $unit_price) - $discount;

        $stmt = $pdo->prepare("
            INSERT INTO sale_lines (sale_id, product_id, batch_id, qty, unit_price, discount, line_total)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([$sale_id, $product_id, $batch_id, $qty, $unit_price, $discount, $line_total]);

        $total += $line_total;

        // Update batch quantity
        $pdo->prepare("UPDATE product_batches SET qty = qty - ? WHERE id = ?")->execute([$qty, $batch_id]);
    }

    // Update sale total
    $pdo->prepare("UPDATE sales SET total = ? WHERE id = ?")->execute([$total, $sale_id]);

    header("Location: view_sale.php?sale_id=$sale_id");
    exit;
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Seller Dashboard</title>
    <link rel="stylesheet" href="../libraries/bootstrap.css">
    <script src="../libraries/jquery.js"></script>
</head>
<body class="p-4">
<h3>New Sale</h3>
<form method="POST" id="saleForm">
    <div class="form-group mb-3">
        <label>Customer</label>
        <select name="customer_id" class="form-control" required>
            <option value="">-- Select Customer --</option>
            <?php foreach($customers as $c): ?>
                <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['name']) ?></option>
            <?php endforeach; ?>
        </select>
    </div>

    <table class="table table-bordered" id="saleLinesTable">
        <thead>
            <tr>
                <th>Product</th>
                <th>Qty</th>
                <th>Unit Price</th>
                <th>Discount</th>
                <th>Line Total</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

    <button type="button" class="btn btn-success" id="addLine">Add Product</button>
    <button type="submit" class="btn btn-primary">Submit Sale</button>
</form>

<script>
let lineCount = 0;
const products = <?php echo json_encode($products); ?>;

function updateLineTotal(row) {
    const qty = parseFloat(row.find('.qty').val()) || 0;
    const price = parseFloat(row.find('.unit_price').val()) || 0;
    const discount = parseFloat(row.find('.discount').val()) || 0;
    const total = (qty * price) - discount;
    row.find('.line_total').text(total.toFixed(2));
}

$('#addLine').click(function() {
    lineCount++;
    let row = $('<tr></tr>');
    let options = '<option value="">-- Select --</option>';
    products.forEach(p => {
        options += `<option value="${p.product_id}" data-price="${p.sell_price}" data-batch="${p.batch_id}">${p.product_name} (${p.sell_price})</option>`;
    });
    row.append(`<td>
        <select name="lines[${lineCount}][product_id]" class="form-control productSelect" required>${options}</select>
        <input type="hidden" name="lines[${lineCount}][batch_id]" class="batch_id">
    </td>`);
    row.append('<td><input type="number" name="lines['+lineCount+'][qty]" class="form-control qty" min="1" value="1"></td>');
    row.append('<td><input type="text" name="lines['+lineCount+'][unit_price]" class="form-control unit_price" readonly></td>');
    row.append('<td><input type="text" name="lines['+lineCount+'][discount]" class="form-control discount" value="0"></td>');
    row.append('<td class="line_total">0.00</td>');
    row.append('<td><button type="button" class="btn btn-danger btn-sm removeLine">X</button></td>');
    $('#saleLinesTable tbody').append(row);
});

$('#saleLinesTable').on('change', '.productSelect', function() {
    const selected = $(this).find('option:selected');
    const price = selected.data('price') || 0;
    const batch = selected.data('batch') || 0;
    const row = $(this).closest('tr');
    row.find('.unit_price').val(price);
    row.find('.batch_id').val(batch);
    updateLineTotal(row);
});

$('#saleLinesTable').on('input', '.qty, .discount', function() {
    const row = $(this).closest('tr');
    updateLineTotal(row);
});

$('#saleLinesTable').on('click', '.removeLine', function() {
    $(this).closest('tr').remove();
});
</script>
</body>
</html>
