<?php
session_start();
header('Content-Type: application/json');

// Only admin allowed
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] ?? '') !== 'admin') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$product_id = isset($_POST['product_id']) ? trim($_POST['product_id']) : '';
if ($product_id === '') {
    echo json_encode(['success' => false, 'message' => 'Missing product_id']);
    exit;
}

$shop_file = __DIR__ . '/shop.php';
if (!file_exists($shop_file)) {
    echo json_encode(['success' => false, 'message' => 'shop.php not found']);
    exit;
}

$content = @file_get_contents($shop_file);
if ($content === false) {
    echo json_encode(['success' => false, 'message' => 'Unable to read shop.php']);
    exit;
}

$needle = 'data-product-id="' . $product_id . '"';
$pos = stripos($content, $needle);
if ($pos === false) {
    echo json_encode(['success' => false, 'message' => 'Product not found in shop.php']);
    exit;
}

// find start of product-card before this position
$substr = substr($content, 0, $pos);
$card_start = strripos($substr, '<div class="product-card"');
if ($card_start === false) {
    echo json_encode(['success' => false, 'message' => 'Product block start not found']);
    exit;
}

// find matching closing </div> for this product-card
$start_pos = $card_start;
$open_tag_end = strpos($content, '>', $start_pos);
if ($open_tag_end === false) {
    echo json_encode(['success' => false, 'message' => 'Malformed product block']);
    exit;
}

$search_pos = $open_tag_end + 1;
$depth = 1;
while ($depth > 0) {
    $next_open = stripos($content, '<div', $search_pos);
    $next_close = stripos($content, '</div>', $search_pos);
    if ($next_close === false) break;
    if ($next_open !== false && $next_open < $next_close) {
        $depth++;
        $search_pos = $next_open + 4;
    } else {
        $depth--;
        $search_pos = $next_close + 6;
    }
}

if ($depth !== 0) {
    echo json_encode(['success' => false, 'message' => 'Could not locate end of product block']);
    exit;
}

$end_pos = $search_pos; // after closing </div>
$block = substr($content, $start_pos, $end_pos - $start_pos);

// Try to extract image src from block to delete file (if in assets/img/product/)
$img_path = null;
if (preg_match('/<img[^>]*class=["\']product-image["\'][^>]*src=["\']([^"\']+)["\']/i', $block, $m)) {
    $img_path = $m[1];
}

// Backup
$backup = $shop_file . '.bak.' . date('Ymd_His');
@copy($shop_file, $backup);

// Remove the block
$new_content = substr($content, 0, $start_pos) . substr($content, $end_pos);
$written = @file_put_contents($shop_file, $new_content);
if ($written === false) {
    echo json_encode(['success' => false, 'message' => 'Failed to write shop.php']);
    exit;
}

// Optionally delete image file if it's inside assets/img/product/
if ($img_path && strpos($img_path, 'assets/img/product/') === 0) {
    $img_file = __DIR__ . '/' . $img_path;
    if (file_exists($img_file)) {
        @unlink($img_file);
    }
}

echo json_encode(['success' => true]);
exit;
