<?php
require_once __DIR__ . '/../config/auth.php';
header('Content-Type: application/json');

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

try {
    $pdo = getDB();
    $where = "WHERE p.status = 1";
    $params = [];

    if (isset($_GET['category_id']) && $_GET['category_id'] !== '') {
        $where .= " AND p.category_id = ?";
        $params[] = (int)$_GET['category_id'];
    }
    if (isset($_GET['type']) && $_GET['type'] !== '') {
        $where .= " AND p.product_type = ?";
        $params[] = strtolower(str_replace(' ', '_', $_GET['type']));
    }

    $stmt = $pdo->prepare("
        SELECT p.id, p.product_code, p.product_name, p.category_id, p.brand_id, p.supplier_id,
               p.product_type, p.model, p.sku, p.barcode, p.cost_price, p.selling_price,
               p.wholesale_price, p.current_stock, p.low_stock_qty, p.product_image,
               p.warranty_period_days, p.status,
               c.category_name, b.brand_name, s.company_name as supplier_name
        FROM products p
        LEFT JOIN categories c ON p.category_id = c.id
        LEFT JOIN brands b ON p.brand_id = b.id
        LEFT JOIN suppliers s ON p.supplier_id = s.id
        $where
        ORDER BY p.product_name
        LIMIT 100
    ");
    $stmt->execute($params);
    $products = $stmt->fetchAll();

    $result = [];
    $currency_symbol = getSetting('currency_symbol', 'Rs.');

    foreach ($products as $p) {
        $type = $p['product_type'];
        $stock_ok = false;

        if ($type === 'phone') {
            $imei_stmt = $pdo->prepare("SELECT COUNT(*) FROM product_imei WHERE product_id = ? AND status = 'Available'");
            $imei_stmt->execute([$p['id']]);
            $available_imei = (int)$imei_stmt->fetchColumn();
            $stock_ok = $available_imei > 0;
            $p['available_imei_count'] = $available_imei;
            $p['display_stock'] = $available_imei;
        } else {
            $stock_ok = $p['current_stock'] > 0;
            $p['available_imei_count'] = 0;
            $p['display_stock'] = $p['current_stock'];
        }

        if (!$stock_ok) continue;

        $p['selling_price_formatted'] = $currency_symbol . ' ' . number_format($p['selling_price'], 2);
        $p['display_type'] = ($type === 'phone' ? 'Phone' : ($type === 'accessory' ? 'Accessory' : 'Spare Part'));
        $result[] = $p;
    }

    echo json_encode(['success' => true, 'products' => $result]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Failed to load products']);
}
