<?php
include 'auth_check.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $product_name = trim($_POST['product_name']);
    $purchasing_price = $_POST['purchasing_price'];
    $selling_price = $_POST['selling_price'];
    $purchased_qty = $_POST['purchased_qty'];
    $unit = trim($_POST['unit']);
    $total_purchasing_price = $_POST['total_purchasing_price'];
    $date = date('Y-m-d');
    $time = date('H:i:s');
    $user = $_SESSION['name'];

    if ($product_name && $purchasing_price && $selling_price && $purchased_qty && $unit) {
        $stmt1 = $conn->prepare("INSERT INTO all_purchasing_product_data (product_name,purchasing_price,selling_price,purchased_qty,unit,total_purchasing_price,entered_date,entered_time,entered_user) VALUES (?,?,?,?,?,?,?,?,?)");
        $stmt1->bind_param("sdddsssss", $product_name, $purchasing_price, $selling_price, $purchased_qty, $unit, $total_purchasing_price, $date, $time, $user);
        $stmt1->execute();

        $check = $conn->prepare("SELECT id, purchased_qty, total_purchasing_price FROM stock WHERE product_name=?");
        $check->bind_param("s", $product_name);
        $check->execute();
        $res = $check->get_result();

        if ($res->num_rows > 0) {
            $row = $res->fetch_assoc();
            $newQty = $row['purchased_qty'] + $purchased_qty;
            $newTotal = $row['total_purchasing_price'] + $total_purchasing_price;
            $up = $conn->prepare("UPDATE stock SET purchasing_price=?, selling_price=?, purchased_qty=?, unit=?, total_purchasing_price=?, entered_date=?, entered_time=?, entered_user=? WHERE id=?");
            $up->bind_param("dddsssssi", $purchasing_price, $selling_price, $newQty, $unit, $newTotal, $date, $time, $user, $row['id']);
            $up->execute();
        } else {
            $stmt2 = $conn->prepare("INSERT INTO stock (product_name,purchasing_price,selling_price,purchased_qty,unit,total_purchasing_price,entered_date,entered_time,entered_user) VALUES (?,?,?,?,?,?,?,?,?)");
            $stmt2->bind_param("sdddsssss", $product_name, $purchasing_price, $selling_price, $purchased_qty, $unit, $total_purchasing_price, $date, $time, $user);
            $stmt2->execute();
        }

        header("Location: add_products.php?success=1");
        exit();
    }
}

$stock = $conn->query("SELECT * FROM all_purchasing_product_data ORDER BY product_name ASC");
?>
<!DOCTYPE html>
<html>
<head>
    <title>Add New Products</title>
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>
<div class="layout">
    <aside class="sidebar">
        <h2>Krushi Sewa Piyasa</h2>
        <a href="dashboard.php">Dashboard</a>
        <a href="sale.php">Sale</a>
        <a href="add_products.php">Add New Products</a>
        <a href="daily_purchasing.php">Daily Purchasing</a>
        <a href="stock.php">Stock</a>
        <a href="logout.php">Logout</a>
    </aside>
    <main class="main-content">
        <div class="topbar">Logged User: <?php echo $_SESSION['name']; ?></div>
        <div class="form-card">
            <h2>Add New Products</h2>
            <form method="POST" onsubmit="return validateProductForm()">
                <input type="hidden" name="id" id="edit_id" required>
                <input type="text" name="product_name" id="search_product" placeholder="Search Product Name" onkeyup="filterTable()" required>
                <input type="number" step="0.01" name="purchasing_price" id="edit_purchasing_price" placeholder="Purchasing Price" required>
                <input type="number" step="0.01" name="selling_price" id="edit_selling_price" placeholder="Selling Price" required>
                <input type="number" step="0.01" name="purchased_qty" id="edit_purchased_qty" placeholder="Purchased QTY" oninput="calcDailyPurchaseTotal()" required>
                <input type="text" name="unit" id="edit_unit" placeholder="Unit" required>
                <input type="number" step="0.01" name="total_purchasing_price" id="edit_total_purchasing_price" readonly required>
                <button type="submit">Submit</button>
            </form>
        </div>

        <div class="table-card">
            <h3>Current Products</h3>
            <table>
                <tr>
                    <th>ID</th><th>Product</th><th>Purchase</th><th>Sell</th><th>Qty</th><th>Unit</th><th>Total</th><th>Date</th><th>User</th>
                </tr>
                <?php while($row = $stock->fetch_assoc()) { ?>
                <tr onclick="fillEditForm('<?php echo $row['id']; ?>','<?php echo htmlspecialchars($row['product_name'], ENT_QUOTES); ?>','<?php echo $row['purchasing_price']; ?>','<?php echo $row['selling_price']; ?>','<?php echo $row['purchased_qty']; ?>','<?php echo $row['unit']; ?>','<?php echo $row['total_purchasing_price']; ?>')">
                    <td><?php echo $row['id']; ?></td>
                    <td><?php echo $row['product_name']; ?></td>
                    <td><?php echo $row['purchasing_price']; ?></td>
                    <td><?php echo $row['selling_price']; ?></td>
                    <td><?php echo $row['purchased_qty']; ?></td>
                    <td><?php echo $row['unit']; ?></td>
                    <td><?php echo $row['total_purchasing_price']; ?></td>
                    <td><?php echo $row['entered_date'].' '.$row['entered_time']; ?></td>
                    <td><?php echo $row['entered_user']; ?></td>
                </tr>
                <?php } ?>
            </table>
        </div>
    </main>
</div>
<script src="assets/app.js"></script>
</body>
</html>