<?php
declare(strict_types=1);

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

$admin = require_admin();

$id = (string) ($_GET['id'] ?? $_POST['id'] ?? '');
$product = store_find('products', $id);
if (!$product) {
    flash('error', 'Ürün bulunamadı.');
    redirect(url('admin/urunler.php'));
}

$cats = categories();
$ibans = ibans_all();
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $result = product_from_admin_post($_POST, $admin, $product);
    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'));
        $product['id'] = $id;
    } else {
        store_upsert('products', $result);
        $seeded = save_seed_comments($result['id'], parse_seed_comments($_POST));
        flash('success', 'Ürün güncellendi.' . ($seeded ? " {$seeded} yeni yorum eklendi." : ''));
        redirect(url('admin/urun-duzenle.php?id=' . urlencode($id)));
    }
}

admin_layout_start('Ürün Düzenle', 'products');
?>

<section class="admin-panel">
    <div class="admin-panel-head">
        <h2><?= e($product['title'] ?? 'Ürün') ?></h2>
        <a class="admin-btn ghost sm" href="<?= e(product_share_url($id)) ?>" target="_blank" rel="noopener">Vitrinde aç</a>
    </div>
    <?php product_form_render($product, $cats, $ibans, $error, true); ?>
</section>

<?php admin_layout_end(); ?>
