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

$auth = new Auth();
$user = $auth->requireRole(['shop_owner', 'admin']);

$db = new Database();
// Check if shop creation is allowed
$stmt = $db->query("SELECT setting_value FROM settings WHERE setting_key = 'allow_shop_creation'");
$allow_shop_creation = $stmt->fetchColumn();

if ($allow_shop_creation === 'false' && !$auth->hasRole('admin')) {
    jsonResponse(['success' => false, 'message' => 'Shop creation is currently disabled by the administrator.'], 403);
}

$shop = new Shop();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    // Validate required fields
    if (empty($input['name']) || empty($input['location'])) {
        jsonResponse([
            'success' => false,
            'message' => 'Shop name and location are required'
        ], 400);
    }
    
    try {
        $shopData = [
            'name' => trim($input['name']),
            'description' => trim($input['description'] ?? ''),
            'location' => trim($input['location']),
            'latitude' => $input['latitude'] ?? null,
            'longitude' => $input['longitude'] ?? null,
            'image' => $input['image'] ?? null
        ];
        
        $shop_id = $shop->createShop($user['id'], $shopData);
        
        jsonResponse([
            'success' => true,
            'message' => 'Shop created successfully',
            'shop_id' => $shop_id
        ]);
    } catch (Exception $e) {
        jsonResponse([
            'success' => false,
            'message' => $e->getMessage()
        ], 500);
    }
} else {
    jsonResponse([
        'success' => false,
        'message' => 'Method not allowed'
    ], 405);
}
?>