<?php
include 'auth.php';
include 'db.php';

if (isset($_GET['customer_id']) && isset($_GET['product_id'])) {
    $customer_id = intval($_GET['customer_id']);
    $product_id = intval($_GET['product_id']);

    // Transactions aur sale_items tables ko join karke is customer ki last purchase price nikalna
    $query = "SELECT si.price 
              FROM sale_items si 
              JOIN transactions t ON si.transaction_id = t.id 
              WHERE t.reference_id = ? 
                AND t.reference_type = 'customer' 
                AND si.product_id = ? 
              ORDER BY t.date DESC, t.id DESC 
              LIMIT 1";

    $stmt = $conn->prepare($query);
    $stmt->bind_param("ii", $customer_id, $product_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        echo json_encode(['status' => 'success', 'price' => number_format($row['price'], 2, '.', '')]);
    } else {
        // Agar pehli baar purchase ho rahi hai to 0.00 bhejna
        echo json_encode(['status' => 'empty', 'price' => '0.00']);
    }
    $stmt->close();
    exit();
}
echo json_encode(['status' => 'error', 'price' => '0.00']);
?>