<?php
include('shikanisha.kts.php');

$stock_data = isset($_POST['stock_data']) ? $_POST['stock_data'] : [];
$stock_take_date = isset($_POST['stock_take_date']) ? $_POST['stock_take_date'] : '';
$taken_by = isset($_POST['taken_by']) ? $_POST['taken_by'] : '';

if (!empty($stock_data) && !empty($stock_take_date) && !empty($taken_by)) {
    // Check if the date already exists in stock_count
    $query = "SELECT COUNT(*) FROM stock_count WHERE date = ?";
    if ($stmt = $conn->prepare($query)) {
        $stmt->bind_param('s', $stock_take_date);
        $stmt->execute();
        $stmt->bind_result($count);
        $stmt->fetch();
        $stmt->close();
        
        if ($count > 0) {
            // Date already exists
            $response = ['status' => 'error', 'message' => 'Stock take for this date already exists.'];
        } else {
            // Insert into stock_count
            $query = "INSERT INTO stock_count (taken_by, date) VALUES (?, ?)";
            if ($stmt = $conn->prepare($query)) {
                $stmt->bind_param('ss', $taken_by, $stock_take_date);
                if ($stmt->execute()) {
                    $stock_count_id = $stmt->insert_id;
                    $stmt->close();
                    
                    foreach ($stock_data as $item) {
                        $product_id = intval($item['product_id']);
                        $product_name = $item['name'];
                        $category = $item['category'];
                        $new_quantity = floatval($item['new_quantity']);

                        $query = "INSERT INTO product_update (count_id, product_id, product_name, category, quantity) 
                                  VALUES (?, ?, ?, ?, ?)";
                        if ($stmt = $conn->prepare($query)) {
                            $stmt->bind_param('iissi', $stock_count_id, $product_id, $product_name, $category, $new_quantity);
                            $stmt->execute();
                            $stmt->close();
                        }
                    }

                    $response = ['status' => 'success', 'message' => 'Stock updated successfully.'];
                } else {
                    $response = ['status' => 'error', 'message' => 'Failed to insert stock count.'];
                }
            } else {
                $response = ['status' => 'error', 'message' => 'Failed to prepare stock count query.'];
            }
        }
    } else {
        $response = ['status' => 'error', 'message' => 'Failed to prepare date check query.'];
    }
} else {
    $response = ['status' => 'error', 'message' => 'Invalid input data.'];
}

$conn->close();
header('Content-Type: application/json');
echo json_encode($response);
?>
