<?php
session_start();

// Only admin can access
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] ?? '') !== 'admin') {
    header('Location: shop.php');
    exit;
}

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($id <= 0) {
    die('Invalid product id');
}

$shop_file = __DIR__ . '/shop.php';
if (!file_exists($shop_file)) {
    die('shop.php not found');
}

$shop_content = @file_get_contents($shop_file);
if ($shop_content === false) {
    die('Unable to read shop.php');
}

// Find the product-card block containing this product id by locating the data attribute
$needle = 'data-product-id="' . $id . '"';
$pos_data = stripos($shop_content, $needle);
if ($pos_data === false) {
    die('Product block not found in shop.php');
}

// Find the nearest preceding '<div class="product-card"' before the data attribute
$substr_up_to = substr($shop_content, 0, $pos_data);
$pos_card_start = strripos($substr_up_to, '<div class="product-card"');
if ($pos_card_start === false) {
    die('Product block not found in shop.php');
}

$start_pos = $pos_card_start;
// find end of opening tag
$open_tag_end = strpos($shop_content, '>', $start_pos);
if ($open_tag_end === false) {
    die('Malformed product block in shop.php');
}

$search_pos = $open_tag_end + 1;
$depth = 1;
while ($depth > 0) {
    $next_open = stripos($shop_content, '<div', $search_pos);
    $next_close = stripos($shop_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) {
    die('Could not determine end of product block in shop.php');
}

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

// Extract current values
$current_name = '';
$current_price = '';
$current_image = '';

if (preg_match('/<div\s+class="product-name">\s*(.*?)\s*<\/div>/si', $block, $m)) {
    $current_name = trim(strip_tags($m[1]));
}
if (preg_match('/<div\s+class="product-price">\s*(.*?)\s*<\/div>/si', $block, $m)) {
    $current_price = trim(strip_tags($m[1]));
}
if (preg_match('/<img[^>]*class=["\']product-image["\'][^>]*src=["\']([^"\']+)["\'][^>]*>/si', $block, $m)) {
    $current_image = trim($m[1]);
}

// Also try to get data-* attributes if available
if (preg_match('/data-product-id=["\']' . preg_quote((string)$id, '/') . '["\'][^>]*data-name=["\']([^"\']+)["\']/si', $block, $m)) {
    $current_name = html_entity_decode($m[1]);
}
if (preg_match('/data-product-id=["\']' . preg_quote((string)$id, '/') . '["\'][^>]*data-price=["\']([^"\']+)["\']/si', $block, $m)) {
    $current_price = $m[1];
}
if (preg_match('/data-product-id=["\']' . preg_quote((string)$id, '/') . '["\'][^>]*data-image=["\']([^"\']+)["\']/si', $block, $m)) {
    $current_image = $m[1];
}

// Normalize price value for form (remove non-digits)
$current_price_numeric = preg_replace('/[^0-9.]/', '', $current_price);

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $price = trim($_POST['price'] ?? '');
    $image = trim($_POST['image'] ?? '');

    if ($name === '' || $price === '') {
        $message = 'Name and price are required.';
    } else {
        // Prepare formatted price for display
        $formatted_price = 'Rs. ' . number_format((float)$price, 0);

        $new_block = $block;

        // Replace product name div
        $new_block = preg_replace('/<div\s+class="product-name">.*?<\/div>/si', '<div class="product-name">' . htmlspecialchars($name) . '</div>', $new_block);

        // Replace product price div
        $new_block = preg_replace('/<div\s+class="product-price">.*?<\/div>/si', '<div class="product-price">' . htmlspecialchars($formatted_price) . '</div>', $new_block);

        // Replace img src inside the block (product-image)
        if ($image !== '') {
            $new_block = preg_replace('/(<img[^>]*class=["\']product-image["\'][^>]*src=["\'])([^"\']+)(["\'][^>]*>)/si', '$1' . htmlspecialchars($image) . '$3', $new_block);
        }

        // Update data-* attributes (data-name, data-price, data-image) for any element inside the block
        $new_block = preg_replace_callback('/data-product-id=["\']' . preg_quote((string)$id, '/') . '["\']([^>]*)/si', function($m) use ($name, $price, $image, $id) {
            $attrs = $m[1];

            // Update or add data-name
            if (preg_match('/data-name=["\']([^"\']+)["\']/si', $attrs)) {
                $attrs = preg_replace('/data-name=["\']([^"\']+)["\']/si', 'data-name="' . htmlspecialchars($name) . '"', $attrs);
            } else {
                $attrs .= ' data-name="' . htmlspecialchars($name) . '"';
            }

            // Update or add data-price (store numeric value)
            if (preg_match('/data-price=["\']([^"\']+)["\']/si', $attrs)) {
                $attrs = preg_replace('/data-price=["\']([^"\']+)["\']/si', 'data-price="' . htmlspecialchars($price) . '"', $attrs);
            } else {
                $attrs .= ' data-price="' . htmlspecialchars($price) . '"';
            }

            // Update or add data-image
            if ($image !== '') {
                if (preg_match('/data-image=["\']([^"\']+)["\']/si', $attrs)) {
                    $attrs = preg_replace('/data-image=["\']([^"\']+)["\']/si', 'data-image="' . htmlspecialchars($image) . '"', $attrs);
                } else {
                    $attrs .= ' data-image="' . htmlspecialchars($image) . '"';
                }
            }

            return 'data-product-id="' . $id . '"' . $attrs;
        }, $new_block);

        // Replace the old block in shop content
        $new_shop_content = str_replace($block, $new_block, $shop_content);

        // Write back to shop.php
        $written = @file_put_contents($shop_file, $new_shop_content);
        if ($written === false) {
            $message = 'Failed to write updates to shop.php. Check file permissions.';
        } else {
            // Success: redirect back to admin dashboard
            header('Location: admin-dashboard.php?msg=product_updated');
            exit;
        }
    }
}

?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Edit Product #<?php echo $id; ?></title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <style>body{padding:20px;background:#f8f9fa} .form-card{max-width:800px;margin:0 auto;background:#fff;padding:20px;border-radius:8px;box-shadow:0 6px 24px rgba(0,0,0,0.08)}</style>
</head>
<body>
    <div class="form-card">
        <h2>Edit Product #<?php echo $id; ?></h2>
        <?php if ($message): ?>
            <div class="alert alert-warning"><?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>
        <form method="post">
            <div class="mb-3">
                <label class="form-label">Name</label>
                <input type="text" name="name" class="form-control" value="<?php echo htmlspecialchars($current_name); ?>" required>
            </div>
            <div class="mb-3">
                <label class="form-label">Price (numeric)</label>
                <input type="text" name="price" class="form-control" value="<?php echo htmlspecialchars($current_price_numeric); ?>" required>
            </div>
            <div class="mb-3">
                <label class="form-label">Image path (relative)</label>
                <input type="text" name="image" class="form-control" value="<?php echo htmlspecialchars($current_image); ?>">
            </div>
            <?php if ($current_image): ?>
                <div class="mb-3">
                    <label class="form-label">Preview</label><br>
                    <img src="<?php echo htmlspecialchars($current_image); ?>" alt="preview" style="max-width:200px;border-radius:6px;">
                </div>
            <?php endif; ?>
            <div class="d-flex gap-2">
                <button class="btn btn-primary" type="submit">Save Changes</button>
                <a class="btn btn-secondary" href="admin-dashboard.php">Cancel</a>
            </div>
        </form>
    </div>
</body>
</html>
