<?php
include 'includes/config.php';
header('Content-Type: application/json');

try {
    $stmt = $conn->prepare("
        SELECT 
            ds.invoice,
            ds.product_id,
            p.name AS product_name,
            ds.product_code,
            ds.product_name AS defective_name,
            ds.category,
            ds.unit,
            ds.price,
            ds.sale_qty,
            ds.total_amount,
            ds.date_sale,
            c.name AS customer_name
        FROM 
            defective_sale ds
        LEFT JOIN 
            products p ON p.id = ds.product_id
        LEFT JOIN 
            contacts c ON c.id = ds.customer_id AND c.type = 'customer'
        ORDER BY 
            ds.date_sale DESC
    ");

    $stmt->execute();
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($results ?: []);

} catch (PDOException $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
