<?php
session_start();

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

$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');
}

// Determine next product id by scanning existing data-product-id attributes
preg_match_all('/data-product-id=["\'](\d+)["\']/', $shop_content, $id_matches);
$existing_ids = array_map('intval', $id_matches[1] ?? []);
$next_id = $existing_ids ? (max($existing_ids) + 1) : 1;

$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 {
        // sanitize and prepare values
        $id = $next_id;
        $price_numeric = preg_replace('/[^0-9.]/', '', $price);
        $formatted_price = 'Rs. ' . number_format((float)$price_numeric, 0);
        $img = $image !== '' ? $image : 'assets/img/product/default.jpg';

        // Handle uploaded image (optional) — uploaded file takes precedence over manual path
        if (!empty($_FILES['image_file']) && $_FILES['image_file']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = __DIR__ . '/assets/img/product/';
            if (!is_dir($upload_dir)) @mkdir($upload_dir, 0755, true);
            $tmp = $_FILES['image_file']['tmp_name'];
            $orig_name = $_FILES['image_file']['name'];
            $ext = pathinfo($orig_name, PATHINFO_EXTENSION);
            $safe = preg_replace('/[^a-zA-Z0-9-_\.]/', '_', pathinfo($orig_name, PATHINFO_FILENAME));
            $filename = $safe . '_' . time() . ($ext ? '.' . $ext : '');
            $dest = $upload_dir . $filename;
            if (@move_uploaded_file($tmp, $dest)) {
                $img = 'assets/img/product/' . $filename;
            } else {
                $message = 'Failed to save uploaded image.';
            }
        }

        // Build product card HTML consistent with shop.php structure using a nowdoc template
        $new_block = <<<'HTML'
                <!-- Product {ID} -->
                <div class="product-card">
                    <img src="{IMG}" alt="{NAME}" class="product-image">
                    <div class="product-content">
                        <div class="product-header">
                            <div>
                                <div class="product-name">{NAME}</div>
                                <div class="product-price">{FORMATTED_PRICE}</div>
                            </div>
                            <?php if (isset($_SESSION['user_id']) && $_SESSION['user_role'] === 'customer'): ?>
                                <button class="btn-favorite" data-product-id="{ID}" data-name="{NAME}" data-price="{PRICE_NUM}" data-image="{IMG}" title="Add to favorites">♡</button>
                            <?php endif; ?>
                        </div>
                        <div class="product-controls">
                            <div class="quantity-group">
                                <input type="number" class="quantity-input qty-input" value="1" min="1" data-pid="{ID}">
                            </div>
                            <button class="btn-add-cart" data-product-id="{ID}" data-name="{NAME}" data-price="{PRICE_NUM}" data-image="{IMG}">➕ ADD TO CART</button>
                        </div>
                    </div>
                </div>
HTML;

        // Replace placeholders with safe values
        $replacements = [
            '{ID}' => $id,
            '{IMG}' => htmlspecialchars($img, ENT_QUOTES, 'UTF-8'),
            '{NAME}' => htmlspecialchars($name, ENT_QUOTES, 'UTF-8'),
            '{PRICE_NUM}' => htmlspecialchars($price_numeric, ENT_QUOTES, 'UTF-8'),
            '{FORMATTED_PRICE}' => htmlspecialchars($formatted_price, ENT_QUOTES, 'UTF-8')
        ];
        $new_block = str_replace(array_keys($replacements), array_values($replacements), $new_block);

        // Create backup of shop.php before writing
        $backup_file = $shop_file . '.bak.' . date('Ymd_His');
        @copy($shop_file, $backup_file);

        // Try to insert inside the products grid (<div class="products-grid">) by finding its matching closing tag.
        $inserted = false;
        $grid_start = stripos($shop_content, '<div class="products-grid"');
        if ($grid_start !== false) {
            // find end of the opening tag
            $open_tag_end = strpos($shop_content, '>', $grid_start);
            if ($open_tag_end !== false) {
                $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) {
                    // insert right before the closing </div> that ends products-grid
                    $insert_pos = $search_pos - 6; // position where '</div>' starts
                    $new_shop_content = substr($shop_content, 0, $insert_pos) . $new_block . substr($shop_content, $insert_pos);
                    $written = @file_put_contents($shop_file, $new_shop_content);
                    if ($written !== false) {
                        $inserted = true;
                    }
                }
            }
        }

        // Fallback: previous insertion method (Action Bar marker or end of file)
        if (!$inserted) {
            $insert_marker = "\n\n            <!-- Action Bar -->";
            $pos = strpos($shop_content, $insert_marker);
            if ($pos === false) {
                $pos = strrpos($shop_content, '</div>');
            }

            if ($pos === false) {
                $message = 'Could not find insertion point in shop.php';
            } else {
                $new_shop_content = substr($shop_content, 0, $pos) . $new_block . substr($shop_content, $pos);
                $written = @file_put_contents($shop_file, $new_shop_content);
                if ($written === false) {
                    $message = 'Failed to write to shop.php. Check permissions.';
                } else {
                    header('Location: admin-dashboard.php?msg=product_added');
                    exit;
                }
            }
        } else {
            // success via products-grid insertion
            header('Location: admin-dashboard.php?msg=product_added');
            exit;
        }
    }
}

?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Add Product</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>Add Product</h2>
        <?php if ($message): ?>
            <div class="alert alert-warning"><?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>
        <form method="post" enctype="multipart/form-data">
            <div class="mb-3">
                <label class="form-label">Name</label>
                <input type="text" name="name" class="form-control" value="" required>
            </div>
            <div class="mb-3">
                <label class="form-label">Price (numeric)</label>
                <input type="text" name="price" class="form-control" value="" required>
            </div>
            <div class="mb-3">
                <label class="form-label">Upload image (optional)</label>
                <input type="file" name="image_file" class="form-control">
                <small class="form-text text-muted">Or specify a relative image path below (used if no file uploaded)</small>
                <input type="text" name="image" class="form-control mt-2" value="assets/img/product/">
            </div>
            <div class="d-flex gap-2">
                <button class="btn btn-primary" type="submit">Add Product</button>
                <a class="btn btn-secondary" href="admin-dashboard.php">Cancel</a>
            </div>
        </form>
    </div>
</body>
</html>
