<?php
declare(strict_types=1);
session_start();
if (!isset($_SESSION['user_id']) || (int)$_SESSION['user_id'] <= 0) {
    http_response_code(401);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Please sign in to add an ad.');window.location.href='login.html';</script></body></html>";
    exit;
}

$dbHost = getenv('DB_HOST') ?: 'localhost';
$dbUser = getenv('DB_USER') ?: 'root';
$dbPass = getenv('DB_PASSWORD') ?: '';
$dbName = 'listbnb';

try {
    $pdo = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4", $dbUser, $dbPass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Database connection failed.');window.location.href='listing-ads.html';</script></body></html>";
    exit;
}

$pdo->exec(
    'CREATE TABLE IF NOT EXISTS products (
        id INT AUTO_INCREMENT PRIMARY KEY,
        product_title VARCHAR(255) NOT NULL,
        product_size ENUM("XS","Small","Medium","Large","XL") NOT NULL,
        price DECIMAL(10,2) NOT NULL,
        `condition` ENUM("New","Used") NOT NULL,
        category VARCHAR(50) NOT NULL,
        product_type VARCHAR(100) NOT NULL,
        brand VARCHAR(100),
        color VARCHAR(50),
        chart_chest VARCHAR(50),
        chart_waist VARCHAR(50),
        chart_hip VARCHAR(50),
        chart_shoulder VARCHAR(50),
        chart_sleeve VARCHAR(50),
        chart_length VARCHAR(50),
        chart_shirt_length VARCHAR(50),
        chart_trouser_length VARCHAR(50),
        description TEXT NOT NULL,
        image1 VARCHAR(255),
        image2 VARCHAR(255),
        image3 VARCHAR(255),
        image4 VARCHAR(255),
        image5 VARCHAR(255),
        status ENUM("Pending","Active","Inactive") NOT NULL DEFAULT "Pending",
        size_xs_chest VARCHAR(50),
        size_xs_waist VARCHAR(50),
        size_xs_hip VARCHAR(50),
        size_xs_length VARCHAR(50),
        size_s_chest VARCHAR(50),
        size_s_waist VARCHAR(50),
        size_s_hip VARCHAR(50),
        size_s_length VARCHAR(50),
        size_m_chest VARCHAR(50),
        size_m_waist VARCHAR(50),
        size_m_hip VARCHAR(50),
        size_m_length VARCHAR(50),
        size_l_chest VARCHAR(50),
        size_l_waist VARCHAR(50),
        size_l_hip VARCHAR(50),
        size_l_length VARCHAR(50),
        size_xl_chest VARCHAR(50),
        size_xl_waist VARCHAR(50),
        size_xl_hip VARCHAR(50),
        size_xl_length VARCHAR(50),
        size_xs_shoulder VARCHAR(50),
        size_xs_sleeve VARCHAR(50),
        size_xs_shirt_length VARCHAR(50),
        size_xs_trouser_length VARCHAR(50),
        size_s_shoulder VARCHAR(50),
        size_s_sleeve VARCHAR(50),
        size_s_shirt_length VARCHAR(50),
        size_s_trouser_length VARCHAR(50),
        size_m_shoulder VARCHAR(50),
        size_m_sleeve VARCHAR(50),
        size_m_shirt_length VARCHAR(50),
        size_m_trouser_length VARCHAR(50),
        size_l_shoulder VARCHAR(50),
        size_l_sleeve VARCHAR(50),
        size_l_shirt_length VARCHAR(50),
        size_l_trouser_length VARCHAR(50),
        size_xl_shoulder VARCHAR(50),
        size_xl_sleeve VARCHAR(50),
        size_xl_shirt_length VARCHAR(50),
        size_xl_trouser_length VARCHAR(50),
        user_id INT UNSIGNED,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'
);
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_xs_chest VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_xs_waist VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_xs_hip VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_xs_length VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_s_chest VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_s_waist VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_s_hip VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_s_length VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_m_chest VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_m_waist VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_m_hip VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_m_length VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_l_chest VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_l_waist VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_l_hip VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_l_length VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_xl_chest VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_xl_waist VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_xl_hip VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_xl_length VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN user_id INT UNSIGNED'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN color VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN chart_chest VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN chart_waist VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN chart_hip VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN chart_shoulder VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN chart_sleeve VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN chart_length VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN chart_shirt_length VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN chart_trouser_length VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN status ENUM("Pending","Active","Inactive") NOT NULL DEFAULT "Pending"'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_xs_shoulder VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_xs_sleeve VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_xs_shirt_length VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_xs_trouser_length VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_s_shoulder VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_s_sleeve VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_s_shirt_length VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_s_trouser_length VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_m_shoulder VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_m_sleeve VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_m_shirt_length VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_m_trouser_length VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_l_shoulder VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_l_sleeve VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_l_shirt_length VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_l_trouser_length VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_xl_shoulder VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_xl_sleeve VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_xl_shirt_length VARCHAR(50)'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN size_xl_trouser_length VARCHAR(50)'); } catch (Throwable $e) {}

try {
    $stmt = $pdo->prepare('SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=? AND TABLE_NAME=?');
    $stmt->execute([$dbName, 'products']);
    $cols = array_map(function($r){return strtolower($r['COLUMN_NAME']);}, $stmt->fetchAll());
    $need = [
        'user_id' => 'INT UNSIGNED',
        'color' => 'VARCHAR(50)',
        'chart_chest' => 'VARCHAR(50)',
        'chart_waist' => 'VARCHAR(50)',
        'chart_hip' => 'VARCHAR(50)',
        'chart_shoulder' => 'VARCHAR(50)',
        'chart_sleeve' => 'VARCHAR(50)',
        'chart_length' => 'VARCHAR(50)',
        'chart_shirt_length' => 'VARCHAR(50)',
        'chart_trouser_length' => 'VARCHAR(50)',
        'size_xs_chest' => 'VARCHAR(50)',
        'size_xs_waist' => 'VARCHAR(50)',
        'size_xs_hip' => 'VARCHAR(50)',
        'size_xs_length' => 'VARCHAR(50)',
        'size_s_chest' => 'VARCHAR(50)',
        'size_s_waist' => 'VARCHAR(50)',
        'size_s_hip' => 'VARCHAR(50)',
        'size_s_length' => 'VARCHAR(50)',
        'size_m_chest' => 'VARCHAR(50)',
        'size_m_waist' => 'VARCHAR(50)',
        'size_m_hip' => 'VARCHAR(50)',
        'size_m_length' => 'VARCHAR(50)',
        'size_l_chest' => 'VARCHAR(50)',
        'size_l_waist' => 'VARCHAR(50)',
        'size_l_hip' => 'VARCHAR(50)',
        'size_l_length' => 'VARCHAR(50)',
        'size_xl_chest' => 'VARCHAR(50)',
        'size_xl_waist' => 'VARCHAR(50)',
        'size_xl_hip' => 'VARCHAR(50)',
        'size_xl_length' => 'VARCHAR(50)',
        'size_xs_shoulder' => 'VARCHAR(50)',
        'size_xs_sleeve' => 'VARCHAR(50)',
        'size_xs_shirt_length' => 'VARCHAR(50)',
        'size_xs_trouser_length' => 'VARCHAR(50)',
        'size_s_shoulder' => 'VARCHAR(50)',
        'size_s_sleeve' => 'VARCHAR(50)',
        'size_s_shirt_length' => 'VARCHAR(50)',
        'size_s_trouser_length' => 'VARCHAR(50)',
        'size_m_shoulder' => 'VARCHAR(50)',
        'size_m_sleeve' => 'VARCHAR(50)',
        'size_m_shirt_length' => 'VARCHAR(50)',
        'size_m_trouser_length' => 'VARCHAR(50)',
        'size_l_shoulder' => 'VARCHAR(50)',
        'size_l_sleeve' => 'VARCHAR(50)',
        'size_l_shirt_length' => 'VARCHAR(50)',
        'size_l_trouser_length' => 'VARCHAR(50)',
        'size_xl_shoulder' => 'VARCHAR(50)',
        'size_xl_sleeve' => 'VARCHAR(50)',
        'size_xl_shirt_length' => 'VARCHAR(50)',
        'size_xl_trouser_length' => 'VARCHAR(50)'
    ];
    foreach ($need as $c => $t) {
        if (!in_array(strtolower($c), $cols, true)) {
            try { $pdo->exec("ALTER TABLE products ADD COLUMN $c $t"); } catch (Throwable $e) {}
        }
    }
} catch (Throwable $e) {}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Method not allowed.');window.location.href='listing-ads.html';</script></body></html>";
    exit;
}

$product_title = trim($_POST['product_title'] ?? '');
$product_size = trim($_POST['product_size'] ?? '');
$price = trim($_POST['price'] ?? '');
$condition = trim($_POST['condition'] ?? '');
$categoryCode = trim($_POST['category'] ?? '');
$product_type = trim($_POST['product_type'] ?? '');
$brand = trim($_POST['brand'] ?? '');
$color = trim($_POST['color'] ?? '');
$chart_chest = f('chart_chest');
$chart_waist = f('chart_waist');
$chart_hip = f('chart_hip');
$chart_shoulder = f('chart_shoulder');
$chart_sleeve = f('chart_sleeve');
$chart_length = f('chart_length');
$chart_shirt_length = f('chart_shirt_length');
$chart_trouser_length = f('chart_trouser_length');
$description = trim($_POST['description'] ?? '');
$userId = (int)($_SESSION['user_id'] ?? 0);
function f($k){ $v = trim($_POST[$k] ?? ''); return ($v !== '') ? $v : null; }
$size_xs_chest = f('size_xs_chest');
$size_xs_waist = f('size_xs_waist');
$size_xs_hip = f('size_xs_hip');
$size_xs_length = f('size_xs_length');
$size_s_chest = f('size_s_chest');
$size_s_waist = f('size_s_waist');
$size_s_hip = f('size_s_hip');
$size_s_length = f('size_s_length');
$size_m_chest = f('size_m_chest');
$size_m_waist = f('size_m_waist');
$size_m_hip = f('size_m_hip');
$size_m_length = f('size_m_length');
$size_l_chest = f('size_l_chest');
$size_l_waist = f('size_l_waist');
$size_l_hip = f('size_l_hip');
$size_l_length = f('size_l_length');
$size_xl_chest = f('size_xl_chest');
$size_xl_waist = f('size_xl_waist');
$size_xl_hip = f('size_xl_hip');
$size_xl_length = f('size_xl_length');
$size_xs_shoulder = f('size_xs_shoulder');
$size_xs_sleeve = f('size_xs_sleeve');
$size_xs_shirt_length = f('size_xs_shirt_length');
$size_xs_trouser_length = f('size_xs_trouser_length');
$size_s_shoulder = f('size_s_shoulder');
$size_s_sleeve = f('size_s_sleeve');
$size_s_shirt_length = f('size_s_shirt_length');
$size_s_trouser_length = f('size_s_trouser_length');
$size_m_shoulder = f('size_m_shoulder');
$size_m_sleeve = f('size_m_sleeve');
$size_m_shirt_length = f('size_m_shirt_length');
$size_m_trouser_length = f('size_m_trouser_length');
$size_l_shoulder = f('size_l_shoulder');
$size_l_sleeve = f('size_l_sleeve');
$size_l_shirt_length = f('size_l_shirt_length');
$size_l_trouser_length = f('size_l_trouser_length');
$size_xl_shoulder = f('size_xl_shoulder');
$size_xl_sleeve = f('size_xl_sleeve');
$size_xl_shirt_length = f('size_xl_shirt_length');
$size_xl_trouser_length = f('size_xl_trouser_length');

$categoryMap = [
    'summer' => 'Summer Clothing',
    'winter' => 'Winter Clothing',
    'dress_type' => 'By Dress Type',
    'party_formal' => 'Party & Formal Wear',
    'active' => 'Active Wear / Gym Wear',
    'nightwear' => 'Nightwear / Sleepwear',
    'modest' => 'Modest Wear',
    'casual' => 'Casual Wear',
    'spring' => 'Spring Clothing',
    'autumn' => 'Autumn / Fall Clothing',
];
$category = $categoryMap[$categoryCode] ?? $categoryCode;
$isAdmin = isset($_SESSION['role']) && $_SESSION['role'] === 'Admin';
$successRedirect = $isAdmin ? 'admin-products.php' : 'my-products.php';

if ($product_title === '' || $product_size === '' || $price === '' || $condition === '' || $category === '' || $product_type === '' || $description === '') {
    http_response_code(400);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('All required fields must be provided.');window.location.href='listing-ads.html';</script></body></html>";
    exit;
}

if (!in_array($product_size, ['XS','Small','Medium','Large','XL'], true)) {
    http_response_code(400);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Invalid product size.');window.location.href='listing-ads.html';</script></body></html>";
    exit;
}

if (!in_array($condition, ['New','Used'], true)) {
    http_response_code(400);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Invalid condition.');window.location.href='listing-ads.html';</script></body></html>";
    exit;
}

$priceNum = (float)$price;
if ($priceNum <= 0) {
    http_response_code(400);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Invalid price.');window.location.href='listing-ads.html';</script></body></html>";
    exit;
}

$uploadDir = __DIR__ . DIRECTORY_SEPARATOR . 'uploads';
if (!is_dir($uploadDir)) {
    @mkdir($uploadDir, 0775, true);
}

$paths = [null, null, null, null, null];
for ($i = 1; $i <= 5; $i++) {
    $key = 'image' . $i;
    if (!isset($_FILES[$key])) continue;
    $name = $_FILES[$key]['name'] ?? '';
    $tmp = $_FILES[$key]['tmp_name'] ?? '';
    $err = $_FILES[$key]['error'] ?? UPLOAD_ERR_NO_FILE;
    if ($err === UPLOAD_ERR_NO_FILE || $name === '' || $tmp === '') continue;
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    if (!in_array($ext, ['png','jpg','jpeg'], true)) continue;
    $safe = preg_replace('/[^a-zA-Z0-9_\.-]/', '_', pathinfo($name, PATHINFO_FILENAME));
    $final = $safe . '_' . uniqid('', true) . '.' . $ext;
    $dest = $uploadDir . DIRECTORY_SEPARATOR . $final;
    if (@move_uploaded_file($tmp, $dest)) {
        $paths[$i-1] = 'uploads/' . $final;
    }
}

try {
    $stmt = $pdo->prepare('INSERT INTO products (product_title, product_size, price, `condition`, category, product_type, brand, color, description, chart_chest, chart_waist, chart_hip, chart_shoulder, chart_sleeve, chart_length, chart_shirt_length, chart_trouser_length, image1, image2, image3, image4, image5, user_id) VALUES (:title, :size, :price, :cond, :cat, :ptype, :brand, :color, :descr, :chart_chest, :chart_waist, :chart_hip, :chart_shoulder, :chart_sleeve, :chart_length, :chart_shirt_length, :chart_trouser_length, :img1, :img2, :img3, :img4, :img5, :uid)');
    $stmt->execute([
        ':title' => $product_title,
        ':size' => $product_size,
        ':price' => number_format($priceNum, 2, '.', ''),
        ':cond' => $condition,
        ':cat' => $category,
        ':ptype' => $product_type,
        ':brand' => ($brand !== '' ? $brand : null),
        ':color' => ($color !== '' ? $color : null),
        ':chart_chest' => $chart_chest,
        ':chart_waist' => $chart_waist,
        ':chart_hip' => $chart_hip,
        ':chart_shoulder' => $chart_shoulder,
        ':chart_sleeve' => $chart_sleeve,
        ':chart_length' => $chart_length,
        ':chart_shirt_length' => $chart_shirt_length,
        ':chart_trouser_length' => $chart_trouser_length,
        ':descr' => $description,
        ':img1' => $paths[0],
        ':img2' => $paths[1],
        ':img3' => $paths[2],
        ':img4' => $paths[3],
        ':img5' => $paths[4],
        ':uid' => $userId,
    ]);
} catch (Throwable $e) {
    $msg = $e->getMessage() ?? '';
    if (strpos($msg, 'Unknown column') !== false) {
        try {
            $stmt = $pdo->prepare('INSERT INTO products (product_title, product_size, price, `condition`, category, product_type, brand, color, description, image1, image2, image3, image4, image5, user_id) VALUES (:title, :size, :price, :cond, :cat, :ptype, :brand, :color, :descr, :img1, :img2, :img3, :img4, :img5, :uid)');
            $stmt->execute([
                ':title' => $product_title,
                ':size' => $product_size,
                ':price' => number_format($priceNum, 2, '.', ''),
                ':cond' => $condition,
                ':cat' => $category,
                ':ptype' => $product_type,
                ':brand' => ($brand !== '' ? $brand : null),
                ':color' => ($color !== '' ? $color : null),
                ':descr' => $description,
                ':img1' => $paths[0],
                ':img2' => $paths[1],
                ':img3' => $paths[2],
                ':img4' => $paths[3],
                ':img5' => $paths[4],
                ':uid' => $userId,
            ]);
            echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Product successfully added');window.location.href='".$successRedirect."';</script></body></html>";
            exit;
        } catch (Throwable $e2) {
            http_response_code(500);
            $msg2 = addslashes($e2->getMessage() ?? 'Failed to add product.');
            echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Failed to add product: " . $msg2 . "');window.location.href='listing-ads.html';</script></body></html>";
            exit;
        }
    }
    http_response_code(500);
    $safe = addslashes($msg ?: 'Failed to add product.');
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Failed to add product: " . $safe . "');window.location.href='listing-ads.html';</script></body></html>";
    exit;
}

echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Product successfully added');window.location.href='".$successRedirect."';</script></body></html>";
?>
