<?php
require_once '../config.php';
require_once '../../includes/Auth.php';
require_once '../../includes/Shop.php';

$auth = new Auth();
$user = $auth->requireAuth();
$shop = new Shop();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    $shop_id = $input['shop_id'] ?? null;
    $shop_data = $shop->getShopById($shop_id);
    
    // Allow if user is the shop owner OR an admin
    if (!$shop_data || ($shop_data['owner_id'] != $user['id'] && !$auth->hasRole('admin'))) {
        jsonResponse(['success' => false, 'message' => 'Unauthorized'], 403);
    }
    
    try {
        $product_id = $shop->addProduct($shop_id, $input);
        
        jsonResponse([
            'success' => true,
            'message' => 'Product added successfully',
            'product_id' => $product_id
        ]);
    } catch (Exception $e) {
        jsonResponse([
            'success' => false,
            'message' => $e->getMessage()
        ], 500);
    }
} else {
    jsonResponse([
        'success' => false,
        'message' => 'Method not allowed'
    ], 405);
}
?>