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

// Ensure sale_id exists
if (!isset($_GET['id'])) {
    die("Sale ID missing");
}

$sale_id = intval($_GET['id']);

// ------------------------------
// FETCH SALE HEADER
// ------------------------------
$stmt = $pdo->prepare("SELECT * FROM sales WHERE id = ?");
$stmt->execute([$sale_id]);
$sale = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$sale) {
    die("Sale not found");
}

// ------------------------------
// FETCH SALE LINES
// ------------------------------
$stmt = $pdo->prepare("
    SELECT 
        sl.id AS line_id,
        sl.product_id,
        sl.batch_id,
        sl.qty,
        sl.unit_price,
        sl.discount,
        sl.line_total,
        p.name AS product_name,
        b.batch_no
    FROM sale_lines sl
    JOIN products p ON sl.product_id = p.id
    LEFT JOIN product_batches b ON sl.batch_id = b.id
    WHERE sl.sale_id = ?
");
$stmt->execute([$sale_id]);
$lines = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ------------------------------
// DELETE A LINE
// ------------------------------
if (isset($_GET['delete_line'])) {

    $line_id = intval($_GET['delete_line']);

    $del = $pdo->prepare("DELETE FROM sale_lines WHERE id=? AND sale_id=?");
    $del->execute([$line_id, $sale_id]);

    // Recalculate sale total
    $stmt = $pdo->prepare("SELECT SUM(line_total) AS new_total FROM sale_lines WHERE sale_id=?");
    $stmt->execute([$sale_id]);
    $total = $stmt->fetch()['new_total'] ?? 0;

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

    echo "<script>alert('Line deleted'); window.location='edit_sale.php?id=$sale_id';</script>";
    exit;
}

// ------------------------------
// UPDATE SALE LINES
// ------------------------------
if (isset($_POST['update_sale'])) {

    $new_total = 0;

    foreach ($_POST['lines'] as $line_id => $data) {

        $qty        = intval($data['qty']);
        $unit_price = floatval($data['unit_price']);
        $discount   = floatval($data['discount']);

        $line_total = ($qty * $unit_price) - $discount;

        // Update sale line
        $stmt = $pdo->prepare("
            UPDATE sale_lines 
            SET qty=?, unit_price=?, discount=?, line_total=?
            WHERE id=? AND sale_id=?
        ");
        $stmt->execute([$qty, $unit_price, $discount, $line_total, $line_id, $sale_id]);

        $new_total += $line_total;
    }

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

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

?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit Sale</title>
    <link rel="stylesheet" href="../libraries/bootstrap.css">
</head>
<body class="p-4">

<h4>Edit Sale — Invoice: <b><?php echo htmlspecialchars($sale['invoice_no']); ?></b></h4>
<hr>

<form method="POST">

<table class="table table-bordered table-sm">
    <thead>
        <tr>
            <th>#</th>
            <th>Product</th>
            <th>Batch</th>
            <th width="80px">Qty</th>
            <th width="120px">Unit Price</th>
            <th width="100px">Discount</th>
            <th width="120px">Line Total</th>
            <th width="60px">Delete</th>
        </tr>
    </thead>

    <tbody>
        <?php foreach ($lines as $i => $line){ ?>
        <tr>
            <td><?php echo $i + 1; ?></td>
            <td><?php echo htmlspecialchars($line['product_name']); ?></td>
            <td><?php echo htmlspecialchars($line['batch_no'] ?? '-'); ?></td>

            <td>
                <input type="number"
                       name="lines[<?php echo $line['line_id']; ?>][qty]"
                       value="<?php echo $line['qty']; ?>"
                       class="form-control form-control-sm"
                       min="1">
            </td>

            <td>
                <input type="text"
                       name="lines[<?php echo $line['line_id']; ?>][unit_price]"
                       value="<?php echo $line['unit_price']; ?>"
                       class="form-control form-control-sm">
            </td>

            <td>
                <input type="text"
                       name="lines[<?php echo $line['line_id']; ?>][discount]"
                       value="<?php echo $line['discount']; ?>"
                       class="form-control form-control-sm">
            </td>

            <td><?php echo number_format($line['line_total'], 2); ?></td>

            <td>
                <a href="edit_sale.php?id=<?php echo $sale_id; ?>&delete_line=<?php echo $line['line_id']; ?>"
                   class="btn btn-danger btn-sm"
                   onclick="return confirm('Delete this item?');">
                    X
                </a>
            </td>
        </tr>
        <?php } ?>
    </tbody>
</table>

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

</form>

</body>
</html>
