<?php
header('Content-Type: application/json; charset=utf-8');
require_once '../db.php';

try {
    // Fetch up to 10 products for slider:
    // Priority: products with discount (original_price > price) first, then newest
    $stmt = $conn->prepare("
        SELECT 
            product_id,
            product_name,
            image_url,
            price,
            original_price,
            category_id,
            badge,
            badge_text
        FROM products
        WHERE is_active = 1 AND approval_status = 'approved'
        ORDER BY 
            (original_price IS NOT NULL AND original_price > price) DESC,
            created_at DESC
        LIMIT 10
    ");
    $stmt->execute();
    $result = $stmt->get_result();
    
    $slides = [];
    while ($row = $result->fetch_assoc()) {
        $row['product_id'] = (int)$row['product_id'];
        $row['price'] = (float)$row['price'];
        $row['original_price'] = $row['original_price'] ? (float)$row['original_price'] : null;
        
        // Calculate discount percent if applicable
        if ($row['original_price'] && $row['original_price'] > $row['price']) {
            $row['discount_pct'] = round((1 - $row['price'] / $row['original_price']) * 100);
        } else {
            $row['discount_pct'] = 0;
        }
        $slides[] = $row;
    }
    $stmt->close();
    
    echo json_encode(['slides' => $slides]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Internal Server Error', 'slides' => []]);
}
?>
