<?php
include 'includes/config.php';

$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : '';

$sql = "SELECT p.name AS product_name, SUM(ss.sale_qty) AS total_sold
FROM variations v
JOIN products p ON v.product_id = p.id
JOIN stock_sale ss ON v.product_id = ss.product_id
WHERE ss.customer_id IS NOT NULL";

if($search) $sql .= " AND p.name LIKE :search";
if($start_date && $end_date) $sql .= " AND ss.date_sale BETWEEN :start AND :end";

$sql .= " GROUP BY p.id ORDER BY total_sold DESC LIMIT 10"; // Top 10 trending items

$stmt = $conn->prepare($sql);
if($search) $stmt->bindValue(':search','%'.$search.'%');
if($start_date && $end_date){
    $stmt->bindValue(':start',$start_date);
    $stmt->bindValue(':end',$end_date);
}
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

header('Content-Type: application/json');
echo json_encode($data);
