<?php
require_once __DIR__.'/../app/bootstrap.php';
use App\Core\Auth;use App\Core\Database;use App\Core\WalletService;
Auth::requireRole(['vendor','admin'],'public/login.php');$user=current_user();$vendor=Auth::role()==='vendor'?Database::safeFetchOne('SELECT * FROM vendors WHERE user_id=? AND status IN ("approved","active") LIMIT 1',[Auth::id()]):Database::safeFetchOne('SELECT * FROM vendors WHERE id=? AND status IN ("approved","active") LIMIT 1',[(int)($_GET['vendor_id']??0)]);if(!$vendor){http_response_code(403);exit('Vendor profile not found, not approved, or not selected.');}
$vendorId=(int)$vendor['id'];$panelType='vendor';$title=$panelTitle??'Vendor Module';$pageTitle=$title.' | Vendor';$slug=basename($_SERVER['SCRIPT_NAME'],'.php');$errors=[];
if(in_array($slug,['products','product-create'],true)){require __DIR__.'/_product_manager.php';exit;}
if($_SERVER['REQUEST_METHOD']==='POST'){
 if(!verify_csrf())$errors[]='Invalid security token.';else try{$a=(string)($_POST['_action']??'');
  if(in_array($slug,['products','product-create'],true)&&$a==='save'){$id=(int)($_POST['id']??0);$name=trim((string)($_POST['name']??''));if($name==='')throw new RuntimeException('Product name is required.');$data=[$_POST['category_id']?:null,$_POST['brand_id']?:null,$name,$id?($_POST['slug']??slugify($name)):unique_slug('products',$name),trim((string)$_POST['sku']),trim((string)($_POST['barcode']??'')),(float)$_POST['purchase_price'],(float)$_POST['regular_price'],(float)$_POST['sale_price'],(int)$_POST['stock'],$_POST['image']??'',$_POST['short_description']??'',$_POST['description']??'',(int)($_POST['reward_points']??0),(float)($_POST['shipping_charge']??0),$_POST['status']??'pending'];if($id){Database::execute('UPDATE products SET category_id=?,brand_id=?,name=?,slug=?,sku=?,barcode=?,purchase_price=?,regular_price=?,sale_price=?,stock=?,image=?,short_description=?,description=?,reward_points=?,shipping_charge=?,status=?,updated_at=NOW() WHERE id=? AND vendor_id=?',[...$data,$id,$vendorId]);}else{Database::execute('INSERT INTO products (vendor_id,category_id,brand_id,name,slug,sku,barcode,purchase_price,regular_price,sale_price,stock,image,short_description,description,reward_points,shipping_charge,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW())',[$vendorId,...$data]);}}
  elseif(in_array($slug,['products','product-create'],true)&&$a==='delete')Database::execute('UPDATE products SET status="deleted" WHERE id=? AND vendor_id=?',[(int)$_POST['id'],$vendorId]);
  elseif($slug==='orders'&&$a==='status'){$status=(string)$_POST['status'];if(!in_array($status,['confirmed','processing','shipped','delivered','cancelled'],true))throw new RuntimeException('Invalid fulfillment status.');$item=Database::fetchOne('SELECT order_id FROM order_items WHERE id=? AND vendor_id=? LIMIT 1',[(int)$_POST['item_id'],$vendorId]);if(!$item)throw new RuntimeException('Order item not found.');Database::execute('UPDATE order_items SET fulfillment_status=?,tracking_no=? WHERE id=? AND vendor_id=?',[$status,trim((string)($_POST['tracking_no']??'')),(int)$_POST['item_id'],$vendorId]);$remaining=db_count('order_items','order_id=? AND fulfillment_status<>"delivered"',[(int)$item['order_id']]);if($remaining===0){Database::execute('UPDATE orders SET order_status="delivered",payment_status=CASE WHEN payment_method="cod" THEN "paid" ELSE payment_status END,paid_amount=CASE WHEN payment_method="cod" THEN total_amount ELSE paid_amount END,due_amount=CASE WHEN payment_method="cod" THEN 0 ELSE due_amount END,updated_at=NOW() WHERE id=?',[(int)$item['order_id']]);Database::safeExecute('INSERT INTO order_status_history (order_id,status,note,created_by,created_at) VALUES (?,"delivered","All vendor items delivered",?,NOW())',[(int)$item['order_id'],Auth::id()]);App\Core\AffiliateService::processOrder((int)$item['order_id']);}}
  elseif(in_array($slug,['shop','landing'],true)&&$a==='shop')Database::execute('UPDATE vendors SET shop_name=?,slug=?,logo=?,banner=?,address=?,policies=?,social_json=?,updated_at=NOW() WHERE id=?',[trim((string)$_POST['shop_name']),unique_slug('vendors',(string)$_POST['shop_name'],$vendorId),$_POST['logo']??'',$_POST['banner']??'',$_POST['address']??'',$_POST['policies']??'',json_encode(['facebook'=>$_POST['facebook']??'','whatsapp'=>$_POST['whatsapp']??'']),$vendorId]);
  elseif($slug==='variants'&&$a==='save'){if(!Database::safeFetchOne('SELECT id FROM products WHERE id=? AND vendor_id=?',[(int)$_POST['product_id'],$vendorId]))throw new RuntimeException('Product not found.');Database::execute('INSERT INTO product_variants (product_id,variant_name,sku,options_json,price,stock,created_at,updated_at) VALUES (?,?,?,?,?,?,NOW(),NOW())',[(int)$_POST['product_id'],trim((string)$_POST['variant_name']),trim((string)$_POST['sku']),json_encode(['option'=>$_POST['option']??'']),(float)$_POST['price'],(int)$_POST['stock']]);}
  elseif($slug==='coupons'&&$a==='save')Database::execute('INSERT INTO coupons (vendor_id,code,discount_type,discount_value,min_order_amount,starts_at,ends_at,usage_limit,status) VALUES (?,?,?,?,?,?,?,?,"active")',[$vendorId,strtoupper(trim((string)$_POST['code'])),$_POST['discount_type'],(float)$_POST['discount_value'],(float)$_POST['min_order_amount'],$_POST['starts_at']?:null,$_POST['ends_at']?:null,(int)$_POST['usage_limit']]);
  elseif($slug==='delivery'&&$a==='save')Database::execute('INSERT INTO vendor_shipping_methods (vendor_id,method_name,courier_id,pickup_address,charge,status,created_at) VALUES (?,?,?,?,?,"active",NOW())',[$vendorId,trim((string)$_POST['method_name']),!empty($_POST['courier_id'])?(int)$_POST['courier_id']:null,$_POST['pickup_address']??'',(float)$_POST['charge']]);
  set_flash('success','Saved successfully.');redirect('vendor/'.basename($_SERVER['SCRIPT_NAME']));
 }catch(Throwable $e){$errors[]=$e->getMessage();}
}
$productCount=db_count('products','vendor_id=? AND status<>"deleted"',[$vendorId]);$orderCount=db_count('order_items','vendor_id=?',[$vendorId]);$sales=(float)(Database::safeFetchOne('SELECT COALESCE(SUM(total_price),0) total FROM order_items WHERE vendor_id=?',[$vendorId])['total']??0);$wallet=WalletService::balance((int)$vendor['user_id'],'cash');
require ROOT_PATH.'/app/Layouts/panel_header.php';
?>
<div class="d-flex justify-content-between align-items-start flex-wrap gap-3 mb-3"><div><h1 class="h3 mb-1"><?= e($title) ?></h1><p class="text-muted mb-0"><?= e($panelDescription??'Vendor module.') ?></p></div><a class="btn btn-outline-primary" target="_blank" href="<?= url('shop/'.$vendor['slug']) ?>">View Shop</a></div><?php if($m=flash('success')): ?><div class="alert alert-success"><?= e($m) ?></div><?php endif; ?><?php foreach($errors as $er): ?><div class="alert alert-danger"><?= e($er) ?></div><?php endforeach; ?>
<div class="row g-3 mb-4"><div class="col-md-3"><div class="stat-tile"><small>Products</small><strong><?= $productCount ?></strong></div></div><div class="col-md-3"><div class="stat-tile"><small>Order items</small><strong><?= $orderCount ?></strong></div></div><div class="col-md-3"><div class="stat-tile"><small>Gross sales</small><strong><?= money($sales) ?></strong></div></div><div class="col-md-3"><div class="stat-tile"><small>Cash wallet</small><strong><?= money($wallet) ?></strong></div></div></div>

<?php if($slug==='index'): $recent=Database::safeFetchAll('SELECT oi.*,o.order_no,o.customer_name,o.order_status FROM order_items oi JOIN orders o ON o.id=oi.order_id WHERE oi.vendor_id=? ORDER BY oi.id DESC LIMIT 10',[$vendorId]); ?>
<div class="row g-4"><div class="col-lg-8"><div class="card module-card"><div class="card-header bg-white"><strong>Recent order items</strong></div><table class="table mb-0"><tr><th>Order</th><th>Product</th><th>Qty</th><th>Total</th><th>Status</th></tr><?php if(!$recent): ?><?= table_empty(5,'No orders yet.') ?><?php endif; ?><?php foreach($recent as $r): ?><tr><td><?= e($r['order_no']) ?></td><td><?= e($r['product_name']) ?></td><td><?= (int)$r['qty'] ?></td><td><?= money($r['total_price']) ?></td><td><?= badge($r['fulfillment_status']??$r['order_status']) ?></td></tr><?php endforeach; ?></table></div></div><div class="col-lg-4"><div class="card module-card"><div class="card-body"><h5>Quick actions</h5><div class="d-grid gap-2"><a class="btn btn-primary" href="<?= url('vendor/product-create.php') ?>">Add Product</a><a class="btn btn-outline-primary" href="<?= url('vendor/orders.php') ?>">Fulfil Orders</a><a class="btn btn-outline-primary" href="<?= url('vendor/pos.php') ?>">Open POS</a></div></div></div></div></div>

<?php elseif(in_array($slug,['products','product-create'],true)): $products=Database::safeFetchAll('SELECT * FROM products WHERE vendor_id=? AND status<>"deleted" ORDER BY id DESC',[$vendorId]);$edit=!empty($_GET['edit'])?Database::safeFetchOne('SELECT * FROM products WHERE id=? AND vendor_id=?',[(int)$_GET['edit'],$vendorId]):null;$cats=Database::safeFetchAll('SELECT * FROM categories WHERE status="active" ORDER BY name');$brands=Database::safeFetchAll('SELECT * FROM brands WHERE status="active" ORDER BY name'); ?>
<div class="row g-4"><div class="col-lg-5"><div class="card module-card"><div class="card-body"><h5><?= $edit?'Edit product':'Add product' ?></h5><form method="post"><?= csrf_field() ?><input type="hidden" name="_action" value="save"><input type="hidden" name="id" value="<?= (int)($edit['id']??0) ?>"><input type="hidden" name="slug" value="<?= e($edit['slug']??'') ?>"><input class="form-control mb-2" name="name" value="<?= e($edit['name']??'') ?>" placeholder="Product name" required><div class="row g-2"><div class="col-6"><select class="form-select" name="category_id"><option value="">Category</option><?php foreach($cats as $c): ?><option value="<?= (int)$c['id'] ?>" <?= ($edit['category_id']??0)==$c['id']?'selected':'' ?>><?= e($c['name']) ?></option><?php endforeach; ?></select></div><div class="col-6"><select class="form-select" name="brand_id"><option value="">Brand</option><?php foreach($brands as $b): ?><option value="<?= (int)$b['id'] ?>" <?= ($edit['brand_id']??0)==$b['id']?'selected':'' ?>><?= e($b['name']) ?></option><?php endforeach; ?></select></div></div><input class="form-control my-2" name="sku" value="<?= e($edit['sku']??'') ?>" placeholder="SKU" required><input class="form-control mb-2" name="barcode" value="<?= e($edit['barcode']??'') ?>" placeholder="Barcode"><div class="row g-2"><div class="col-4"><input class="form-control" type="number" step="0.01" name="purchase_price" value="<?= e($edit['purchase_price']??0) ?>" placeholder="Cost"></div><div class="col-4"><input class="form-control" type="number" step="0.01" name="regular_price" value="<?= e($edit['regular_price']??0) ?>" placeholder="Regular"></div><div class="col-4"><input class="form-control" type="number" step="0.01" name="sale_price" value="<?= e($edit['sale_price']??0) ?>" placeholder="Sale"></div></div><input class="form-control my-2" type="number" name="stock" value="<?= e($edit['stock']??0) ?>" placeholder="Stock"><input class="form-control mb-2" name="image" value="<?= e($edit['image']??'') ?>" placeholder="Image path"><textarea class="form-control mb-2" name="short_description" placeholder="Short description"><?= e($edit['short_description']??'') ?></textarea><textarea class="form-control mb-2" name="description" rows="4" placeholder="Description"><?= e($edit['description']??'') ?></textarea><div class="row g-2"><div class="col"><input class="form-control" type="number" name="reward_points" value="<?= e($edit['reward_points']??0) ?>" placeholder="Reward points"></div><div class="col"><input class="form-control" type="number" step="0.01" name="shipping_charge" value="<?= e($edit['shipping_charge']??0) ?>" placeholder="Shipping"></div></div><select class="form-select my-2" name="status"><option value="pending">Pending approval</option><option value="published" <?= ($edit['status']??'')==='published'?'selected':'' ?>>Published</option><option value="disabled">Disabled</option></select><button class="btn btn-primary"><?= $edit?'Update':'Save' ?></button></form></div></div></div><div class="col-lg-7"><div class="card module-card"><div class="table-responsive"><table class="table mb-0"><tr><th>Product</th><th>Price</th><th>Stock</th><th>Status</th><th></th></tr><?php if(!$products): ?><?= table_empty(5,'No products.') ?><?php endif; ?><?php foreach($products as $p): ?><tr><td><?= e($p['name']) ?><small class="d-block text-muted"><?= e($p['sku']) ?></small></td><td><?= money($p['sale_price']?:$p['regular_price']) ?></td><td><?= (int)$p['stock'] ?></td><td><?= badge($p['status']) ?></td><td><a class="btn btn-sm btn-outline-primary" href="?edit=<?= (int)$p['id'] ?>">Edit</a><form method="post" class="d-inline"><?= csrf_field() ?><input type="hidden" name="_action" value="delete"><input type="hidden" name="id" value="<?= (int)$p['id'] ?>"><button class="btn btn-sm btn-outline-danger">Delete</button></form></td></tr><?php endforeach; ?></table></div></div></div></div>

<?php elseif($slug==='orders'): $items=Database::safeFetchAll('SELECT oi.*,o.order_no,o.customer_name,o.customer_phone,o.delivery_address,o.payment_status,o.created_at FROM order_items oi JOIN orders o ON o.id=oi.order_id WHERE oi.vendor_id=? ORDER BY oi.id DESC LIMIT 100',[$vendorId]); ?>
<div class="card module-card"><div class="table-responsive"><table class="table mb-0"><tr><th>Order</th><th>Customer</th><th>Product</th><th>Total</th><th>Payment</th><th>Fulfillment</th></tr><?php if(!$items): ?><?= table_empty(6,'No order items.') ?><?php endif; ?><?php foreach($items as $i): ?><tr><td><?= e($i['order_no']) ?><small class="d-block"><?= e($i['created_at']) ?></small></td><td><?= e($i['customer_name']) ?><small class="d-block"><?= e($i['customer_phone']) ?></small></td><td><?= e($i['product_name']) ?> × <?= (int)$i['qty'] ?></td><td><?= money($i['total_price']) ?></td><td><?= badge($i['payment_status']) ?></td><td><form method="post" class="d-flex gap-1"><?= csrf_field() ?><input type="hidden" name="_action" value="status"><input type="hidden" name="item_id" value="<?= (int)$i['id'] ?>"><select class="form-select form-select-sm" name="status"><?php foreach(['confirmed','processing','shipped','delivered','cancelled'] as $s): ?><option value="<?= $s ?>" <?= ($i['fulfillment_status']??'')===$s?'selected':'' ?>><?= ucfirst($s) ?></option><?php endforeach; ?></select><input class="form-control form-control-sm" name="tracking_no" value="<?= e($i['tracking_no']??'') ?>" placeholder="Tracking"><button class="btn btn-sm btn-primary">Save</button></form></td></tr><?php endforeach; ?></table></div></div>

<?php elseif(in_array($slug,['shop','landing'],true)): ?>
<div class="row g-4"><div class="col-lg-8"><div class="card module-card"><div class="card-body"><h5>Shop profile</h5><form method="post"><?= csrf_field() ?><input type="hidden" name="_action" value="shop"><input class="form-control mb-2" name="shop_name" value="<?= e($vendor['shop_name']) ?>" required><input class="form-control mb-2" name="logo" value="<?= e($vendor['logo']??'') ?>" placeholder="Logo path"><input class="form-control mb-2" name="banner" value="<?= e($vendor['banner']??'') ?>" placeholder="Banner path"><textarea class="form-control mb-2" name="address" placeholder="Address"><?= e($vendor['address']??'') ?></textarea><textarea class="form-control mb-2" name="policies" rows="5" placeholder="Policies"><?= e($vendor['policies']??'') ?></textarea><input class="form-control mb-2" name="facebook" placeholder="Facebook URL"><input class="form-control mb-3" name="whatsapp" placeholder="WhatsApp number"><button class="btn btn-primary">Update shop</button></form></div></div></div><div class="col-lg-4"><div class="card module-card"><div class="card-body"><h5>Public link</h5><code><?= e(url('shop/'.$vendor['slug'])) ?></code><hr><p>Status: <?= badge($vendor['status']) ?></p><p>Commission: <?= e($vendor['commission_value']) ?>%</p></div></div></div></div>

<?php elseif($slug==='variants'): $products=Database::safeFetchAll('SELECT id,name FROM products WHERE vendor_id=? AND status<>"deleted" ORDER BY name',[$vendorId]);$variants=Database::safeFetchAll('SELECT pv.*,p.name product_name FROM product_variants pv JOIN products p ON p.id=pv.product_id WHERE p.vendor_id=? ORDER BY pv.id DESC',[$vendorId]); ?>
<div class="row g-4"><div class="col-lg-5"><div class="card module-card"><div class="card-body"><h5>Add variant</h5><form method="post"><?= csrf_field() ?><input type="hidden" name="_action" value="save"><select class="form-select mb-2" name="product_id" required><?php foreach($products as $p): ?><option value="<?= (int)$p['id'] ?>"><?= e($p['name']) ?></option><?php endforeach; ?></select><input class="form-control mb-2" name="variant_name" placeholder="Variant name" required><input class="form-control mb-2" name="option" placeholder="Options"><input class="form-control mb-2" name="sku" placeholder="SKU" required><input class="form-control mb-2" type="number" step="0.01" name="price" placeholder="Price" required><input class="form-control mb-3" type="number" name="stock" placeholder="Stock" required><button class="btn btn-primary">Add variant</button></form></div></div></div><div class="col-lg-7"><div class="card module-card"><table class="table mb-0"><tr><th>Product</th><th>Variant</th><th>SKU</th><th>Price</th><th>Stock</th></tr><?php foreach($variants as $v): ?><tr><td><?= e($v['product_name']) ?></td><td><?= e($v['variant_name']) ?></td><td><?= e($v['sku']) ?></td><td><?= money($v['price']) ?></td><td><?= (int)$v['stock'] ?></td></tr><?php endforeach; ?></table></div></div></div>

<?php elseif($slug==='wallet'): $tx=Database::safeFetchAll('SELECT * FROM wallet_transactions WHERE user_id=? ORDER BY id DESC LIMIT 100',[$vendor['user_id']]);$wallets=Database::safeFetchAll('SELECT * FROM wallets WHERE user_id=? ORDER BY wallet_type',[$vendor['user_id']]); ?>
<div class="row g-4"><div class="col-lg-5"><div class="card module-card"><table class="table mb-0"><tr><th>Wallet</th><th>Balance</th></tr><?php foreach($wallets as $w): ?><tr><td><?= e(ucwords($w['wallet_type'])) ?></td><td><?= money($w['balance']) ?></td></tr><?php endforeach; ?></table></div></div><div class="col-lg-7"><div class="card module-card"><table class="table mb-0"><tr><th>Date</th><th>Wallet</th><th>Type</th><th>Amount</th></tr><?php foreach($tx as $t): ?><tr><td><?= e($t['created_at']) ?></td><td><?= e($t['wallet_type']) ?></td><td><?= e($t['transaction_type']) ?></td><td><?= money($t['amount']) ?></td></tr><?php endforeach; ?></table></div></div></div>

<?php elseif($slug==='withdrawals'): $req=Database::safeFetchAll('SELECT * FROM withdraw_requests WHERE user_id=? ORDER BY id DESC',[$vendor['user_id']]); ?>
<div class="row g-4"><div class="col-lg-5"><div class="card module-card"><div class="card-body"><h5>Request withdrawal</h5><form id="vendorWithdraw"><input class="form-control mb-2" name="amount" type="number" min="1" step="0.01" placeholder="Amount" required><select class="form-select mb-2" name="wallet_type"><option value="cash">Cash</option><option value="commission">Commission</option></select><select class="form-select mb-2" name="method"><option>bKash</option><option>Nagad</option><option>Bank</option></select><input class="form-control mb-2" name="account_details" placeholder="Account details" required><input class="form-control mb-3" type="password" name="pin" placeholder="Transaction PIN"><button class="btn btn-primary">Submit</button></form><div id="withdrawMsg" class="mt-2"></div></div></div></div><div class="col-lg-7"><div class="card module-card"><table class="table mb-0"><tr><th>Date</th><th>Gross</th><th>Fee</th><th>Net</th><th>Status</th></tr><?php foreach($req as $r): ?><tr><td><?= e($r['created_at']) ?></td><td><?= money($r['amount']) ?></td><td><?= money($r['fee']) ?></td><td><?= money($r['net_amount']) ?></td><td><?= badge($r['status']) ?></td></tr><?php endforeach; ?></table></div></div></div><script>document.getElementById('vendorWithdraw').addEventListener('submit',function(e){e.preventDefault();const d=new FormData(this);d.append('csrf_token','<?= e(csrf_token()) ?>');fetch('<?= url('api/withdraw-request.php') ?>',{method:'POST',body:d}).then(r=>r.json()).then(x=>{document.getElementById('withdrawMsg').textContent=x.message;if(x.ok)location.reload();});});</script>

<?php elseif($slug==='coupons'): $coupons=Database::safeFetchAll('SELECT * FROM coupons WHERE vendor_id=? ORDER BY id DESC',[$vendorId]); ?>
<div class="row g-4"><div class="col-lg-5"><div class="card module-card"><div class="card-body"><h5>Create coupon</h5><form method="post"><?= csrf_field() ?><input type="hidden" name="_action" value="save"><input class="form-control mb-2" name="code" placeholder="Code" required><select class="form-select mb-2" name="discount_type"><option value="fixed">Fixed</option><option value="percentage">Percentage</option></select><input class="form-control mb-2" type="number" step="0.01" name="discount_value" placeholder="Discount" required><input class="form-control mb-2" type="number" step="0.01" name="min_order_amount" placeholder="Minimum order"><input class="form-control mb-2" type="datetime-local" name="starts_at"><input class="form-control mb-2" type="datetime-local" name="ends_at"><input class="form-control mb-3" type="number" name="usage_limit" placeholder="Usage limit"><button class="btn btn-primary">Create</button></form></div></div></div><div class="col-lg-7"><div class="card module-card"><table class="table mb-0"><tr><th>Code</th><th>Type</th><th>Value</th><th>Status</th></tr><?php foreach($coupons as $c): ?><tr><td><?= e($c['code']) ?></td><td><?= e($c['discount_type']) ?></td><td><?= e($c['discount_value']) ?></td><td><?= badge($c['status']) ?></td></tr><?php endforeach; ?></table></div></div></div>

<?php elseif($slug==='returns'): $rows=Database::safeFetchAll('SELECT r.*,o.order_no,p.name product_name FROM returns r JOIN products p ON p.id=r.product_id LEFT JOIN orders o ON o.id=r.order_id WHERE p.vendor_id=? ORDER BY r.id DESC',[$vendorId]); ?>
<div class="card module-card"><table class="table mb-0"><tr><th>Order</th><th>Product</th><th>Reason</th><th>Solution</th><th>Status</th></tr><?php if(!$rows): ?><?= table_empty(5,'No returns.') ?><?php endif; ?><?php foreach($rows as $r): ?><tr><td><?= e($r['order_no']??'') ?></td><td><?= e($r['product_name']) ?></td><td><?= e($r['reason']) ?></td><td><?= e($r['preferred_solution']) ?></td><td><?= badge($r['status']) ?></td></tr><?php endforeach; ?></table></div>

<?php elseif($slug==='reviews'): $rows=Database::safeFetchAll('SELECT pr.*,p.name product_name,u.name customer_name FROM product_reviews pr JOIN products p ON p.id=pr.product_id LEFT JOIN users u ON u.id=pr.user_id WHERE p.vendor_id=? ORDER BY pr.id DESC',[$vendorId]); ?>
<div class="card module-card"><table class="table mb-0"><tr><th>Product</th><th>Customer</th><th>Rating</th><th>Review</th><th>Status</th></tr><?php if(!$rows): ?><?= table_empty(5,'No reviews.') ?><?php endif; ?><?php foreach($rows as $r): ?><tr><td><?= e($r['product_name']) ?></td><td><?= e($r['customer_name']??'') ?></td><td><?= (int)$r['rating'] ?>/5</td><td><?= e($r['review']) ?></td><td><?= badge($r['status']) ?></td></tr><?php endforeach; ?></table></div>

<?php elseif($slug==='sales-report'): $rows=Database::safeFetchAll('SELECT DATE(oi.created_at) sale_date,SUM(oi.qty) qty,SUM(oi.total_price) sales,SUM(oi.commission_amount) commission FROM order_items oi WHERE oi.vendor_id=? GROUP BY DATE(oi.created_at) ORDER BY sale_date DESC LIMIT 90',[$vendorId]); ?>
<div class="card module-card"><table class="table mb-0"><tr><th>Date</th><th>Qty</th><th>Sales</th><th>Commission</th><th>Net</th></tr><?php foreach($rows as $r): ?><tr><td><?= e($r['sale_date']) ?></td><td><?= (int)$r['qty'] ?></td><td><?= money($r['sales']) ?></td><td><?= money($r['commission']) ?></td><td><?= money((float)$r['sales']-(float)$r['commission']) ?></td></tr><?php endforeach; ?></table></div>

<?php elseif($slug==='delivery'): $couriers=Database::safeFetchAll('SELECT * FROM couriers WHERE status="active" ORDER BY name');$methods=Database::safeFetchAll('SELECT vsm.*,c.name courier_name FROM vendor_shipping_methods vsm LEFT JOIN couriers c ON c.id=vsm.courier_id WHERE vsm.vendor_id=? ORDER BY vsm.id DESC',[$vendorId]); ?>
<div class="row g-4"><div class="col-lg-5"><div class="card module-card"><div class="card-body"><form method="post"><?= csrf_field() ?><input type="hidden" name="_action" value="save"><input class="form-control mb-2" name="method_name" placeholder="Method name" required><select class="form-select mb-2" name="courier_id"><option value="">Courier</option><?php foreach($couriers as $c): ?><option value="<?= (int)$c['id'] ?>"><?= e($c['name']) ?></option><?php endforeach; ?></select><textarea class="form-control mb-2" name="pickup_address" placeholder="Pickup address"></textarea><input class="form-control mb-3" name="charge" type="number" step="0.01" placeholder="Charge"><button class="btn btn-primary">Add method</button></form></div></div></div><div class="col-lg-7"><div class="card module-card"><table class="table mb-0"><tr><th>Method</th><th>Courier</th><th>Charge</th><th>Status</th></tr><?php foreach($methods as $m): ?><tr><td><?= e($m['method_name']) ?></td><td><?= e($m['courier_name']??'') ?></td><td><?= money($m['charge']) ?></td><td><?= badge($m['status']) ?></td></tr><?php endforeach; ?></table></div></div></div>

<?php elseif($slug==='subscription'): $sub=Database::safeFetchOne('SELECT vs.*,vp.name package_name,vp.product_limit FROM vendor_subscriptions vs LEFT JOIN vendor_packages vp ON vp.id=vs.package_id WHERE vs.vendor_id=? ORDER BY vs.id DESC LIMIT 1',[$vendorId]); ?>
<div class="card module-card"><div class="card-body"><h4>Subscription</h4><?php if($sub): ?><p>Package: <strong><?= e($sub['package_name']??'') ?></strong></p><p>Valid: <?= e($sub['starts_at']) ?> to <?= e($sub['ends_at']) ?></p><p>Product limit: <?= (int)($sub['product_limit']??0) ?> · Status <?= badge($sub['status']) ?></p><?php else: ?><div class="alert alert-info">No active vendor package. Contact the administrator.</div><?php endif; ?></div></div>

<?php elseif($slug==='notifications'): $rows=Database::safeFetchAll('SELECT * FROM notifications WHERE user_id=? ORDER BY id DESC LIMIT 100',[$vendor['user_id']]); ?>
<div class="card module-card"><div class="list-group list-group-flush"><?php if(!$rows): ?><div class="p-4 text-muted">No notifications.</div><?php endif; ?><?php foreach($rows as $n): ?><div class="list-group-item"><strong><?= e($n['title']) ?></strong><p class="mb-1"><?= e($n['message']) ?></p><small><?= e($n['created_at']) ?></small></div><?php endforeach; ?></div></div>

<?php elseif($slug==='barcode_print'): $products=Database::safeFetchAll('SELECT * FROM products WHERE vendor_id=? AND status="published" ORDER BY name',[$vendorId]); ?>
<div class="card module-card"><div class="card-body"><div class="d-flex justify-content-between"><h5>Product labels</h5><button class="btn btn-primary" onclick="window.print()">Print</button></div><div class="row g-3 mt-2"><?php foreach($products as $p): ?><div class="col-md-4"><div class="border p-3 text-center"><strong><?= e($p['name']) ?></strong><div><?= App\Core\CodeGenerator::barcodeSvg($p['barcode']?:$p['sku'],50) ?></div><small><?= e($p['sku']) ?> · <?= money($p['sale_price']?:$p['regular_price']) ?></small></div></div><?php endforeach; ?></div></div></div>
<?php endif; ?>
<?php require ROOT_PATH.'/app/Layouts/panel_footer.php'; ?>
