<?php
session_start();
$_SESSION['admin_logged_in'] = true;

require_once 'db_config.php';

// Use the connection from db_config.php
$db = $conn;  // Already initialized in db_config.php

if ($db->connect_error) {
    die(json_encode(['success' => false, 'message' => 'DB: ' . $db->connect_error]));
}

// Load products from JSON
$json_file = __DIR__ . '/data/products.json';

if (!file_exists($json_file)) {
    die(json_encode(['success' => false, 'message' => 'File not found: ' . $json_file]));
}

$json_content = file_get_contents($json_file);
$products_raw = json_decode($json_content, true);

if (!is_array($products_raw)) {
    die(json_encode(['success' => false, 'message' => 'Invalid JSON in file']));
}

$products = [];
foreach ($products_raw as $prod) {
    $products[] = [
        'id' => $prod['id'] ?? 0,
        'title' => $prod['title'] ?? 'Unknown',
        'price' => $prod['price'] ?? 0,
        'seo_score' => 0
    ];
}

header('Content-Type: application/json');
echo json_encode([
    'success' => true,
    'products' => $products,
    'count' => count($products)
]);
?>
