<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

$sale_id = intval($_GET['sale_id'] ?? 0);
if(!$sale_id){
    echo "<script>alert('Invalid sale ID');window.location='sales.php';</script>";
    exit;
}

// Fetch sale info
$sale = $conn->query("SELECT * FROM sales WHERE id=$sale_id")->fetch_assoc();
if(!$sale){
    echo "<script>alert('Sale not found');window.location='sales.php';</script>";
    exit;
}

// Fetch sale items
$sale_items = $conn->query("
    SELECT si.*, p.name, p.sku, p.vat_rate
    FROM sale_items si
    JOIN products p ON si.product_id = p.id
    WHERE si.sale_id=$sale_id
");

// Fetch all products for adding new items
$all_products = $conn->query("SELECT * FROM products ORDER BY name ASC");

// Handle form submission
if(isset($_POST['update_sale'])){
    $discount = floatval($_POST['discount']);
    $payment_method = $conn->real_escape_string($_POST['payment_method']);

    // Update existing items
    foreach($_POST['item_qty'] as $item_id => $qty){
        $qty = intval($qty);
        if($qty <= 0){
            $conn->query("DELETE FROM sale_items WHERE id=$item_id");
        } else {
            $conn->query("UPDATE sale_items SET qty=$qty WHERE id=$item_id");
        }
    }

    // Add new item if selected
    if(!empty($_POST['new_product_id']) && intval($_POST['new_qty']) > 0){
        $pid = intval($_POST['new_product_id']);
        $new_qty = intval($_POST['new_qty']);
        $product = $conn->query("SELECT * FROM products WHERE id=$pid")->fetch_assoc();
        if($product){
            $vat = ($product['selling_price'] * $new_qty) * ($product['vat_rate']/100);
            $conn->query("INSERT INTO sale_items(sale_id, product_id, qty, price, vat) 
                         VALUES($sale_id, $pid, $new_qty, {$product['selling_price']}, $vat)");
        }
    }

    // Recalculate totals
    $subtotal = 0;
    $vat_total = 0;
    $items = $conn->query("SELECT si.*, p.vat_rate FROM sale_items si JOIN products p ON si.product_id=p.id WHERE si.sale_id=$sale_id");
    while($item = $items->fetch_assoc()){
        $line_total = $item['price'] * $item['qty'];
        $vat = $line_total * ($item['vat_rate']/100);
        $subtotal += $line_total;
        $vat_total += $vat;

        // Update line VAT
        $conn->query("UPDATE sale_items SET vat=$vat WHERE id={$item['id']}");
    }
    $total = $subtotal + $vat_total - $discount;

    // Update sale
    $conn->query("UPDATE sales SET total=$total, vat_total=$vat_total, discount=$discount, payment_method='$payment_method' WHERE id=$sale_id");

    echo "<script>alert('Sale updated successfully');window.location='sales.php';</script>";
    exit;
}
?>

<div class="container mt-4">
      <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>
    <h3 class="text-center">Edit Sale #<?= $sale_id ?></h3>
    <hr>

    <form method="POST">
        <table class="table table-bordered table-striped">
            <thead class="bg-dark text-white">
                <tr>
                    <th>SKU</th>
                    <th>Product</th>
                    <th>Price (MK)</th>
                    <th>Qty</th>
                    <th>Line Total (MK)</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $grand_total = 0;
                while($item = $sale_items->fetch_assoc()):
                    $line_total = $item['price'] * $item['qty'] + $item['vat'];
                    $grand_total += $line_total;
                ?>
                    <tr>
                        <td><?= $item['sku'] ?></td>
                        <td><?= $item['name'] ?></td>
                        <td><?= number_format($item['price'],2) ?></td>
                        <td>
                            <input type="number" name="item_qty[<?= $item['id'] ?>]" value="<?= $item['qty'] ?>" min="0" class="form-control">
                        </td>
                        <td><?= number_format($line_total,2) ?></td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>

        <h5>Add New Item</h5>
        <div class="row g-3 mb-3">
            <div class="col-md-6">
                <select name="new_product_id" class="form-control">
                    <option value="">-- Select Product --</option>
                    <?php while($p = $all_products->fetch_assoc()): ?>
                        <option value="<?= $p['id'] ?>"><?= $p['name'] ?> (<?= $p['sku'] ?>) - MK <?= $p['selling_price'] ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="col-md-3">
                <input type="number" name="new_qty" value="1" min="1" class="form-control" placeholder="Qty">
            </div>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-md-4">
                <label>Discount (MK)</label>
                <input type="number" step="0.01" name="discount" value="<?= $sale['discount'] ?>" class="form-control">
            </div>
            <div class="col-md-4">
                <label>Payment Method</label>
                <select name="payment_method" class="form-control" required>
                    <option value="">-- Select Method --</option>
                    <option value="Cash" <?= $sale['payment_method']=='Cash'?'selected':'' ?>>Cash</option>
                    <option value="Mobile Money" <?= $sale['payment_method']=='Mobile Money'?'selected':'' ?>>Mobile Money</option>
                    <option value="Card" <?= $sale['payment_method']=='Card'?'selected':'' ?>>Card</option>
                </select>
            </div>
        </div>

        <button type="submit" name="update_sale" class="btn btn-success w-100">Update Sale</button>
    </form>
</div>

<?php include 'includes/footer.php'; ?>
