<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/admin_layout.php';

$admin = require_admin();
$cats = categories();
$ibans = ibans_all();
$error = '';
$product = [
    'status' => 'active',
    'member_year' => '1',
    'listing_date' => date('d.m.Y'),
    'stock' => 1,
    'iban_id' => iban_site()['id'] ?? '',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $result = product_from_admin_post($_POST, $admin);
    if (is_string($result)) {
        $error = $result;
        $product = array_merge($product, $_POST);
        $product['_seed_comments'] = parse_seed_comments($_POST);
        $product['price'] = parse_money_int((string) ($_POST['price'] ?? '0'));
    } else {
        store_upsert('products', $result);
        $seeded = save_seed_comments($result['id'], parse_seed_comments($_POST));
        $share = product_share_url($result['id']);
        flash('success', 'Ürün yayınlandı.' . ($seeded ? " {$seeded} yorum eklendi." : ''));
        redirect(url('admin/urunler.php?ok=' . urlencode($result['id']) . '&link=' . urlencode($share)));
    }
}

admin_layout_start('Ürün Ekle', 'product-add');
?>

<section class="admin-panel">
    <h2>Yeni ürün ilanı</h2>
    <?php product_form_render($product, $cats, $ibans, $error, false); ?>
</section>

<?php admin_layout_end(); ?>
