<?php
// api-simple.php - Simple JSON API for wallpapers
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

include("db_config.php");

if ($conn->connect_error) {
    echo json_encode(['error' => 'Database connection failed']);
    exit();
}

$sql = "SELECT id, name as title, advertiser_name as category, image1, image2 
        FROM appstores 
        ORDER BY id DESC";

$result = $conn->query($sql);

$wallpapers = [];
$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";

while ($row = $result->fetch_assoc()) {
    // Get first image (you can modify this logic based on your needs)
    $image = '';
    if (!empty($row['image1'])) {
        $image = $base_url . '/upload/' . $row['image1'];
    } elseif (!empty($row['image2'])) {
        $image2_array = explode(",", $row['image2']);
        $first_image = trim($image2_array[0]);
        if (!empty($first_image)) {
            $image = $base_url . '/upload/' . $first_image;
        }
    }
    
    $wallpaper = [
        'id' => (int)$row['id'],
        'title' => $row['title'],
        'category' => $row['category'],
        'image' => $image
    ];
    
    $wallpapers[] = $wallpaper;
}

echo json_encode($wallpapers, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

$conn->close();
?>