<?php
session_start();
require_once "db.php";
if(!isset($_SESSION['username'])) exit;

if($_SERVER['REQUEST_METHOD']==='POST'){
    $purchase_id = intval($_POST['purchase_id']);
    $supplier_id = intval($_POST['supplier']);
    $purchase_date = $_POST['purchase_date'];
    $paid = floatval($_POST['paid']);
    $products = $_POST['product'] ?? [];
    $sizes = $_POST['size'] ?? [];
    $rates = $_POST['rate'] ?? [];
    $qtys = $_POST['qty'] ?? [];

    $total=0;
    $subtotals=[];
    $count = count($products);
    for($i=0;$i<$count;$i++){
        $r = floatval($rates[$i]);
        $q = intval($qtys[$i]);
        $st = $r*$q;
        $subtotals[$i]=$st;
        $total+=$st;
    }
    $due = max($total-$paid,0);

    // Update purchases
    $stmt = $conn->prepare("UPDATE purchases SET supplier_id=?, purchase_date=?, total=?, paid=?, due=? WHERE purchase_id=?");
    $stmt->bind_param("isdddi",$supplier_id,$purchase_date,$total,$paid,$due,$purchase_id);
    $stmt->execute();

    // Delete old items
    $conn->query("DELETE FROM purchase_items WHERE purchase_id=$purchase_id");

    // Insert new items
    $stmtItem = $conn->prepare("INSERT INTO purchase_items (purchase_id, product, size, rate, qty, subtotal) VALUES (?,?,?,?,?,?)");
    for($i=0;$i<$count;$i++){
        if(trim($products[$i])=='') continue;
        $stmtItem->bind_param("issdid",$purchase_id,$products[$i],$sizes[$i],$rates[$i],$qtys[$i],$subtotals[$i]);
        $stmtItem->execute();
    }

    header("Location: purchase-list.php");
    exit;
}
