<?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($action==='delimg'&&isset($_GET['img_id'])){
    $imgId=(int)$_GET['img_id'];$pid=(int)($_GET['pid']??0);
    $si=$pdo->prepare("SELECT image FROM product_images WHERE id=?");$si->execute([$imgId]);$img=$si->fetch();
    if($img){$pdo->prepare("DELETE FROM product_images WHERE id=?")->execute([$imgId]);}
    redirect(BASE_URL.'/admin/products.php?action=edit&id='.$pid.'&imgdel=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);
    $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&&!$msg){
        $slug=makeSlug($name);$base=$slug;$i=1;
        while(true){$c=$pdo->prepare("SELECT id FROM products WHERE slug=? AND id!=?");$c->execute([$slug,$pid]);if(!$c->fetch())break;$slug=$base.'-'.$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=>$n){$n=trim($n);$v=trim($vv[$k]??'');$p2=(float)($vp[$k]??0);if($n&&$v)$pdo->prepare("INSERT INTO product_variations(product_id,variation_name,variation_value,extra_price)VALUES(?,?,?,?)")->execute([$pid,$n,$v,$p2]);}
        // Multiple images
        if(!empty($_FILES['extra_images']['name'][0])){
            $totalImgs=(int)$pdo->prepare("SELECT COUNT(*) FROM product_images WHERE product_id=?")->execute([$pid])?:0;
            $curCount=$pdo->prepare("SELECT COUNT(*) FROM product_images WHERE product_id=?");$curCount->execute([$pid]);$cnt=(int)$curCount->fetchColumn();
            foreach($_FILES['extra_images']['error'] as $k=>$err){
                if($err===UPLOAD_ERR_OK&&$cnt<10){
                    $f=['name'=>$_FILES['extra_images']['name'][$k],'type'=>$_FILES['extra_images']['type'][$k],'tmp_name'=>$_FILES['extra_images']['tmp_name'][$k],'error'=>$_FILES['extra_images']['error'][$k],'size'=>$_FILES['extra_images']['size'][$k]];
                    $up=uploadImage($f,'products');
                    if($up){$pdo->prepare("INSERT INTO product_images(product_id,image,sort_order)VALUES(?,?,?)")->execute([$pid,$up,$cnt]);$cnt++;}
                }
            }
        }
        $msg='<div class="alert alert-success"><i class="fas fa-check-circle"></i> পণ্য সংরক্ষণ সফল।</div>';
        $action='edit';$editId=$pid;
    }elseif(!$name){$msg='<div class="alert alert-error">পণ্যের নাম আবশ্যক।</div>';$action=$pid?'edit':'add';$editId=$pid;}
}

$categories=$pdo->query("SELECT * FROM categories WHERE status=1 ORDER BY name")->fetchAll();
$product=['name'=>'','description'=>'','price'=>'','stock'=>0,'category_id'=>'','is_flash'=>0,'image'=>''];
$variations=[];$extraImages=[];
if(($action==='edit'||$action==='add')&&$editId){
    $s=$pdo->prepare("SELECT * FROM products WHERE id=?");$s->execute([$editId]);$product=$s->fetch()?:$product;
    $vs=$pdo->prepare("SELECT * FROM product_variations WHERE product_id=?");$vs->execute([$editId]);$variations=$vs->fetchAll();
    $eis=$pdo->prepare("SELECT * FROM product_images WHERE product_id=? ORDER BY sort_order");$eis->execute([$editId]);$extraImages=$eis->fetchAll();
}

$settings=getAllSettings($pdo);
include __DIR__.'/includes/admin_header.php';

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();
?>
<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;flex-wrap:wrap;"><input type="text" class="form-control" name="search" placeholder="পণ্য খুঁজুন..." value="<?=e($search)?>" style="max-width:220px;"><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-active">হ্যাঁ</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:?>
<h2><?=$editId?'পণ্য সম্পাদনা':'নতুন পণ্য'?></h2>
<?=$msg?>
<?php if(isset($_GET['imgdel'])):?><div class="alert alert-success">ছবি মুছে ফেলা হয়েছে।</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 form-full"><label class="form-check"><input type="checkbox" name="is_flash" value="1" <?=$product['is_flash']?'checked':''?>><span> ফ্ল্যাশ সেল পণ্য</span></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>

<!-- Images Section -->
<div class="card" style="margin-bottom:16px;">
    <div class="card-header"><h3><i class="fas fa-images"></i> পণ্যের ছবি</h3></div>
    <div class="card-body">
        <!-- Main image -->
        <div class="form-group">
            <label class="form-label">প্রধান ছবি <span style="color:var(--g600);font-size:.78rem;">(কার্ড ও থাম্বনেইলে দেখাবে)</span></label>
            <input type="file" class="form-control" name="image" accept="image/jpeg,image/png,image/webp,image/gif">
            <?php if($product['image']):?>
            <div style="margin-top:10px;display:flex;align-items:center;gap:10px;">
                <img src="<?=UPLOADS_URL.e($product['image'])?>" style="height:80px;border-radius:6px;border:2px solid var(--gold);">
                <span style="font-size:.82rem;color:var(--g600);">বর্তমান প্রধান ছবি</span>
            </div>
            <?php endif;?>
        </div>

        <!-- Extra images -->
        <div class="form-group" style="margin-top:20px;">
            <label class="form-label">অতিরিক্ত ছবি <span style="color:var(--g600);font-size:.78rem;">(সর্বোচ্চ ১০ টি, একসাথে একাধিক সিলেক্ট করুন)</span></label>
            <input type="file" class="form-control" name="extra_images[]" accept="image/jpeg,image/png,image/webp,image/gif" multiple>
            <div class="form-hint">Ctrl/Cmd চেপে একাধিক ছবি সিলেক্ট করুন</div>
        </div>

        <!-- Existing extra images -->
        <?php if(!empty($extraImages)):?>
        <div style="margin-top:16px;">
            <div style="font-weight:600;font-size:.88rem;color:var(--navy);margin-bottom:10px;">বর্তমান অতিরিক্ত ছবিসমূহ:</div>
            <div style="display:flex;flex-wrap:wrap;gap:10px;">
                <?php foreach($extraImages as $ei):?>
                <div style="position:relative;display:inline-block;">
                    <img src="<?=UPLOADS_URL.e($ei['image'])?>" style="width:80px;height:80px;object-fit:cover;border-radius:6px;border:1px solid var(--g200);">
                    <a href="?action=delimg&img_id=<?=$ei['id']?>&pid=<?=$editId?>"
                       style="position:absolute;top:-6px;right:-6px;width:20px;height:20px;background:var(--danger);color:#fff;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:.65rem;text-decoration:none;"
                       onclick="return confirm('এই ছবি মুছবেন?')" title="মুছুন">✕</a>
                </div>
                <?php endforeach;?>
            </div>
        </div>
        <?php endif;?>
    </div>
</div>

<!-- Variations -->
<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="varBox">
        <?php if(empty($variations)):?>
        <div class="variation-row"><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:22px;"><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 $v):?>
        <div class="variation-row"><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:22px;"><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:10px;flex-wrap:wrap;">
    <button type="submit" name="save_product" class="topbar-btn btn-gold" style="padding:11px 28px;font-size:.97rem;"><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 b=document.getElementById('varBox');const d=document.createElement('div');d.className='variation-row';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:22px;"><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>`;b.appendChild(d);vc++;}
</script>
<?php endif;?>
<?php include __DIR__.'/includes/admin_footer.php';?>
