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

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

$product_id = (int)($_GET['product_id'] ?? 0);
if (!$product_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid product']);
    exit;
}

try {
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT current_stock, product_type FROM products WHERE id = ? AND status = 1");
    $stmt->execute([$product_id]);
    $p = $stmt->fetch();

    if (!$p) {
        echo json_encode(['success' => false, 'message' => 'Product not found']);
        exit;
    }

    if ($p['product_type'] === 'phone') {
        $imei_stmt = $pdo->prepare("SELECT COUNT(*) FROM product_imei WHERE product_id = ? AND status = 'Available'");
        $imei_stmt->execute([$product_id]);
        echo json_encode(['success' => true, 'current_stock' => (int)$imei_stmt->fetchColumn(), 'product_type' => 'phone']);
    } else {
        echo json_encode(['success' => true, 'current_stock' => (int)$p['current_stock'], 'product_type' => $p['product_type']]);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error checking stock']);
}
