<?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;

    if (!$shop_id) {
        jsonResponse(['success' => false, 'message' => 'Shop ID is required'], 400);
    }

    // Security check: ensure the current user owns the shop or is an admin
    if (!$auth->hasRole('admin') && !$shop->isOwner($shop_id, $user['id'])) {
        jsonResponse(['success' => false, 'message' => 'Unauthorized'], 403);
    }

    try {
        // Prepare data for update, only including image if it's new
        $updateData = [
            'name' => $input['name'] ?? null,
            'description' => $input['description'] ?? null,
            'location' => $input['location'] ?? null,
        ];

        // Only add the image to the update array if a new one was uploaded
        if (isset($input['image']) && !is_null($input['image'])) {
            $updateData['image'] = $input['image'];
        }

        $shop->updateShop($shop_id, $user['id'], $updateData);
        jsonResponse(['success' => true, 'message' => 'Shop settings updated successfully']);
    } catch (Exception $e) {
        jsonResponse(['success' => false, 'message' => $e->getMessage()], 500);
    }
} else {
    jsonResponse(['success' => false, 'message' => 'Method not allowed'], 405);
}
?>