<?php
require_once __DIR__ . '/includes/admin_bootstrap.php';

$action = $_GET['action'] ?? 'list';
$editId = (int)($_GET['id'] ?? 0);
$msg    = '';

if ($action === 'delete' && $editId) {
    $pdo->prepare("DELETE FROM products WHERE id=?")->execute([$editId]);
    redirect(BASE_URL.'/admin/products.php?deleted=1');
}

if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_product'])) {
    $name    = trim($_POST['name']        ?? '');
    $desc    = trim($_POST['description'] ?? '');
    $price   = (float)($_POST['price']       ?? 0);
    $stock   = (int)($_POST['stock']         ?? 0);
    $catId   = (int)($_POST['category_id']   ?? 0);
    $isFlash = isset($_POST['is_flash']) ? 1 : 0;
    $pid     = (int)($_POST['product_id']    ?? 0);
    $slug    = makeSlug($name);

    $image   = $_POST['existing_image'] ?? '';
    if (!empty($_FILES['image']['name'])) {
        $up = uploadImage($_FILES['image'],'products');
        if ($up) $image = $up;
        else $msg .= '<div class="alert alert-error">ছবি আপলোড ব্যর্থ: '.e(uploadError($_FILES['image'])).'</div>';
    }

    if (!$name || $price < 0) {
        $msg .= '<div class="alert alert-error">পণ্যের নাম ও মূল্য আবশ্যক।</div>';
    } else {
        $slugBase=$slug; $i=1;
        while(true){
            $chk=$pdo->prepare("SELECT id FROM products WHERE slug=? AND id!=?");
            $chk->execute([$slug,$pid]);
            if(!$chk->fetch()) break;
            $slug=$slugBase.'-'.$i++;
        }
        if ($pid) {
            $pdo->prepare("UPDATE products SET name=?,slug=?,description=?,price=?,stock=?,category_id=?,image=?,is_flash=? WHERE id=?")
                ->execute([$name,$slug,$desc,$price,$stock,$catId,$image,$isFlash,$pid]);
        } else {
            $pdo->prepare("INSERT INTO products (name,slug,description,price,stock,category_id,image,is_flash) VALUES(?,?,?,?,?,?,?,?)")
                ->execute([$name,$slug,$desc,$price,$stock,$catId,$image,$isFlash]);
            $pid = $pdo->lastInsertId();
        }
        $pdo->prepare("DELETE FROM flash_sale_products WHERE product_id=?")->execute([$pid]);
        if ($isFlash) {
            $mo=$pdo->query("SELECT COALESCE(MAX(flash_order),0)+1 FROM flash_sale_products")->fetchColumn();
            $pdo->prepare("INSERT INTO flash_sale_products (product_id,flash_order) VALUES(?,?)")->execute([$pid,$mo]);
        }
        $pdo->prepare("DELETE FROM product_variations WHERE product_id=?")->execute([$pid]);
        $vn=$_POST['var_name']??[]; $vv=$_POST['var_value']??[]; $vp=$_POST['var_price']??[];
        foreach($vn as $k=>$name_v){
            $name_v=trim($name_v); $val=trim($vv[$k]??''); $pr=(float)($vp[$k]??0);
            if($name_v && $val) $pdo->prepare("INSERT INTO product_variations (product_id,variation_name,variation_value,extra_price) VALUES(?,?,?,?)")->execute([$pid,$name_v,$val,$pr]);
        }
        redirect(BASE_URL.'/admin/products.php?action=edit&id='.$pid.'&saved=1');
    }
    $action = $pid ? 'edit' : 'add'; $editId = $pid;
}

$categories = $pdo->query("SELECT * FROM categories WHERE status=1 ORDER BY name")->fetchAll();

if ($action === 'list'):
    $search = trim($_GET['search']??'');
    $where  = $search ? "WHERE p.name LIKE ?" : '';
    $params = $search ? ["%$search%"] : [];
    $stmt   = $pdo->prepare("SELECT p.*,c.name as cat_name FROM products p LEFT JOIN categories c ON p.category_id=c.id $where ORDER BY p.created_at DESC");
    $stmt->execute($params);
    $products = $stmt->fetchAll();

    

// ── HTML output starts ──
include __DIR__ . '/includes/admin_header.php';

?>
<h2>পণ্য ব্যবস্থাপনা</h2>
<?php if(isset($_GET['deleted'])): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> পণ্য মুছে ফেলা হয়েছে।</div><?php endif; ?>
<div class="card">
    <div class="card-header">
        <form method="GET" style="display:flex;gap:8px;">
            <input type="text" class="form-control" name="search" placeholder="পণ্য খুঁজুন..." value="<?=e($search)?>" style="max-width:240px;">
            <button type="submit" class="topbar-btn btn-navy"><i class="fas fa-search"></i></button>
            <?php if($search): ?><a href="?" class="topbar-btn btn-gray">রিসেট</a><?php endif; ?>
        </form>
        <a href="?action=add" class="topbar-btn btn-gold"><i class="fas fa-plus"></i> নতুন পণ্য</a>
    </div>
    <div class="table-wrap">
        <table>
            <thead><tr><th>ছবি</th><th>নাম</th><th>ক্যাটেগরি</th><th>মূল্য</th><th>স্টক</th><th>ফ্ল্যাশ</th><th>অ্যাকশন</th></tr></thead>
            <tbody>
            <?php foreach($products as $p): ?>
            <tr>
                <td><?php if($p['image']): ?><img src="<?=UPLOADS_URL.e($p['image'])?>" class="thumb"><?php else: ?><div class="thumb-placeholder"><i class="fas fa-image"></i></div><?php endif; ?></td>
                <td><strong><?=e($p['name'])?></strong></td>
                <td><?=e($p['cat_name']??'-')?></td>
                <td>৳<?=number_format($p['price'],2)?></td>
                <td class="<?=$p['stock']<=5?'stock-low':'stock-ok'?>"><?=$p['stock']?></td>
                <td><?=$p['is_flash']?'<span class="badge badge-approved">হ্যাঁ</span>':'<span class="badge badge-inactive">না</span>'?></td>
                <td><div class="actions">
                    <a href="?action=edit&id=<?=$p['id']?>" class="topbar-btn btn-navy"><i class="fas fa-edit"></i></a>
                    <a href="?action=delete&id=<?=$p['id']?>" class="topbar-btn btn-red" data-confirm="মুছে ফেলবেন?"><i class="fas fa-trash"></i></a>
                    <a href="<?=BASE_URL?>/product.php?id=<?=$p['id']?>" target="_blank" class="topbar-btn btn-gray"><i class="fas fa-eye"></i></a>
                </div></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php else:
    $product=['name'=>'','description'=>'','price'=>'','stock'=>'','category_id'=>'','is_flash'=>0,'image'=>''];
    $variations=[];
    if ($editId) {
        $stmt=$pdo->prepare("SELECT * FROM products WHERE id=?"); $stmt->execute([$editId]);
        $product=$stmt->fetch()?:$product;
        $vs=$pdo->prepare("SELECT * FROM product_variations WHERE product_id=?"); $vs->execute([$editId]);
        $variations=$vs->fetchAll();
    }
    
?>
<h2><?=$editId?'পণ্য সম্পাদনা':'নতুন পণ্য যোগ'?></h2>
<?= $msg ?>
<?php if(isset($_GET['saved'])): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> পণ্য সংরক্ষণ সফল।</div><?php endif; ?>

<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="product_id" value="<?=$editId?>">
<input type="hidden" name="existing_image" value="<?=e($product['image'])?>">
<div class="card" style="margin-bottom:16px;">
    <div class="card-header"><h3>মৌলিক তথ্য</h3></div>
    <div class="card-body">
        <div class="form-grid">
            <div class="form-group form-full"><label class="form-label">পণ্যের নাম *</label><input type="text" class="form-control" name="name" value="<?=e($product['name'])?>" required></div>
            <div class="form-group"><label class="form-label">মূল্য (৳) *</label><input type="number" class="form-control" name="price" value="<?=$product['price']?>" step="0.01" min="0" required></div>
            <div class="form-group"><label class="form-label">স্টক পরিমাণ</label><input type="number" class="form-control" name="stock" value="<?=$product['stock']?>" min="0"></div>
            <div class="form-group"><label class="form-label">ক্যাটেগরি</label>
                <select class="form-control" name="category_id"><option value="">-- বাছাই করুন --</option>
                    <?php foreach($categories as $cat): ?><option value="<?=$cat['id']?>" <?=$product['category_id']==$cat['id']?'selected':''?>><?=e($cat['name'])?></option><?php endforeach; ?>
                </select>
            </div>
            <div class="form-group"><label class="form-label">পণ্যের ছবি</label>
                <input type="file" class="form-control" name="image" accept="image/*">
                <div class="form-hint">JPG/PNG/WebP, সর্বোচ্চ ৮ MB</div>
                <?php if($product['image']): ?><img src="<?=UPLOADS_URL.e($product['image'])?>" style="margin-top:8px;height:80px;border-radius:6px;"><?php endif; ?>
            </div>
            <div class="form-group" style="display:flex;align-items:center;padding-top:24px;">
                <label class="form-check"><input type="checkbox" name="is_flash" value="1" <?=$product['is_flash']?'checked':''?>> ফ্ল্যাশ সেল পণ্য</label>
            </div>
            <div class="form-group form-full"><label class="form-label">বিবরণ</label><textarea class="form-control" name="description" rows="5"><?=e($product['description'])?></textarea></div>
        </div>
    </div>
</div>

<div class="card" style="margin-bottom:16px;">
    <div class="card-header"><h3>ভ্যারিয়েশন</h3><button type="button" class="topbar-btn btn-gold" onclick="addVar()"><i class="fas fa-plus"></i> যোগ করুন</button></div>
    <div class="card-body" id="varContainer">
        <?php if(empty($variations)): ?>
        <div class="variation-row" id="vr0">
            <div><label class="form-label">নাম (সাইজ/রঙ)</label><input type="text" class="form-control" name="var_name[]" placeholder="সাইজ"></div>
            <div><label class="form-label">মান</label><input type="text" class="form-control" name="var_value[]" placeholder="S"></div>
            <div><label class="form-label">অতিরিক্ত মূল্য (৳)</label><input type="number" class="form-control" name="var_price[]" value="0" min="0" step="0.01"></div>
            <div style="padding-top:24px;"><button type="button" class="btn-icon" style="background:var(--danger);color:#fff;" onclick="this.closest('.variation-row').remove()"><i class="fas fa-times"></i></button></div>
        </div>
        <?php else: ?>
        <?php foreach($variations as $vi=>$v): ?>
        <div class="variation-row" id="vr<?=$vi?>">
            <div><label class="form-label">নাম</label><input type="text" class="form-control" name="var_name[]" value="<?=e($v['variation_name'])?>"></div>
            <div><label class="form-label">মান</label><input type="text" class="form-control" name="var_value[]" value="<?=e($v['variation_value'])?>"></div>
            <div><label class="form-label">অতিরিক্ত মূল্য (৳)</label><input type="number" class="form-control" name="var_price[]" value="<?=$v['extra_price']?>" min="0" step="0.01"></div>
            <div style="padding-top:24px;"><button type="button" class="btn-icon" style="background:var(--danger);color:#fff;" onclick="this.closest('.variation-row').remove()"><i class="fas fa-times"></i></button></div>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<div style="display:flex;gap:12px;">
    <button type="submit" name="save_product" class="topbar-btn btn-gold" style="padding:10px 28px;font-size:.95rem;"><i class="fas fa-save"></i> সংরক্ষণ করুন</button>
    <a href="?action=list" class="topbar-btn btn-gray"><i class="fas fa-arrow-left"></i> ফিরে যান</a>
</div>
</form>

<script>
let vc=<?=max(count($variations),1)?>;
function addVar(){
    const c=document.getElementById('varContainer');
    const d=document.createElement('div');
    d.className='variation-row'; d.id='vr'+vc;
    d.innerHTML=`<div><label class="form-label">নাম</label><input type="text" class="form-control" name="var_name[]" placeholder="সাইজ/রঙ"></div>
    <div><label class="form-label">মান</label><input type="text" class="form-control" name="var_value[]" placeholder="S/লাল"></div>
    <div><label class="form-label">অতিরিক্ত মূল্য (৳)</label><input type="number" class="form-control" name="var_price[]" value="0" min="0" step="0.01"></div>
    <div style="padding-top:24px;"><button type="button" class="btn-icon" style="background:var(--danger);color:#fff;" onclick="this.closest('.variation-row').remove()"><i class="fas fa-times"></i></button></div>`;
    c.appendChild(d); vc++;
}
</script>
<?php endif; ?>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
