<?php
require_once __DIR__.'/../app/bootstrap.php';
use App\Core\Auth;use App\Core\Database;use App\Core\WalletService;
Auth::requireRole(['customer','affiliate','admin','staff'],'public/login.php');
$panelType='customer';$title=$panelTitle??'Customer Module';$pageTitle=$title.' | Customer Dashboard';$slug=basename($_SERVER['SCRIPT_NAME'],'.php');$uid=(int)Auth::id();$errors=[];

if($_SERVER['REQUEST_METHOD']==='POST'){
 if(!verify_csrf())$errors[]='Invalid security token.';else try{
  $action=(string)($_POST['_action']??'');
  if($slug==='addresses'){
   if($action==='save'){if(trim((string)($_POST['recipient_name']??''))===''||trim((string)($_POST['address_line']??''))==='')throw new RuntimeException('Recipient and address are required.');Database::execute('INSERT INTO addresses (user_id,label,recipient_name,phone,address_line,district_id,area_id,is_default,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,NOW(),NOW())',[$uid,$_POST['label']??'Home',$_POST['recipient_name'],$_POST['phone']??'',$_POST['address_line'],!empty($_POST['district_id'])?(int)$_POST['district_id']:null,!empty($_POST['area_id'])?(int)$_POST['area_id']:null,0]);}
   if($action==='default'){Database::transaction(function()use($uid){Database::execute('UPDATE addresses SET is_default=0 WHERE user_id=?',[$uid]);Database::execute('UPDATE addresses SET is_default=1 WHERE id=? AND user_id=?',[(int)$_POST['id'],$uid]);});}
   if($action==='delete')Database::execute('DELETE FROM addresses WHERE id=? AND user_id=?',[(int)$_POST['id'],$uid]);
  }elseif($slug==='returns'&&$action==='create'){Database::execute('INSERT INTO returns (order_id,product_id,user_id,reason,preferred_solution,status,created_at,updated_at) VALUES (?,?,?,?,?,"pending",NOW(),NOW())',[(int)$_POST['order_id'],!empty($_POST['product_id'])?(int)$_POST['product_id']:null,$uid,trim((string)$_POST['reason']),$_POST['preferred_solution']??'refund']);
  }elseif($slug==='reviews'&&$action==='create'){Database::execute('INSERT INTO product_reviews (product_id,user_id,rating,review,status,created_at) VALUES (?,?,?,?,"pending",NOW())',[(int)$_POST['product_id'],$uid,max(1,min(5,(int)$_POST['rating'])),trim((string)$_POST['review'])]);
  }elseif($slug==='support'&&$action==='create'){Database::execute('INSERT INTO support_tickets (user_id,subject,message,status,created_at,updated_at) VALUES (?,?,?,"open",NOW(),NOW())',[$uid,trim((string)$_POST['subject']),trim((string)$_POST['message'])]);
  }elseif($slug==='security'&&$action==='password'){$u=Database::fetchOne('SELECT password_hash,COALESCE(auth_version,1) auth_version,email FROM users WHERE id=?',[$uid]);if(!$u||!password_verify((string)$_POST['current_password'],(string)$u['password_hash']))throw new RuntimeException('Current password is incorrect.');if($passwordError=App\Core\Security::passwordError((string)$_POST['new_password'],(string)($u['email']??'')))throw new RuntimeException($passwordError);$newVersion=(int)$u['auth_version']+1;$columns=Database::columns('users');$sql=in_array('must_change_password',$columns,true)?'UPDATE users SET password_hash=?,auth_version=?,must_change_password=0,password_changed_at=NOW(),updated_at=NOW() WHERE id=?':'UPDATE users SET password_hash=?,auth_version=?,password_changed_at=NOW(),updated_at=NOW() WHERE id=?';Database::execute($sql,[password_hash((string)$_POST['new_password'],PASSWORD_DEFAULT),$newVersion,$uid]);App\Core\Auth::clearPasswordChangeRequirement($newVersion);
  }elseif($slug==='security'&&$action==='pin'){if(strlen((string)$_POST['pin'])<4)throw new RuntimeException('PIN must contain at least 4 characters.');Database::execute('UPDATE users SET transaction_pin_hash=?,two_factor_enabled=?,updated_at=NOW() WHERE id=?',[password_hash((string)$_POST['pin'],PASSWORD_DEFAULT),!empty($_POST['two_factor_enabled'])?1:0,$uid]);
  }
  set_flash('success','Saved successfully.');redirect('customer/'.basename($_SERVER['SCRIPT_NAME']));
 }catch(Throwable $e){$errors[]=$e->getMessage();}
}
$orders=Database::safeFetchAll('SELECT * FROM orders WHERE customer_id=? ORDER BY id DESC LIMIT 20',[$uid]);$wallets=Database::safeFetchAll('SELECT * FROM wallets WHERE user_id=? ORDER BY wallet_type',[$uid]);$points=(int)(Database::safeFetchOne('SELECT COALESCE(SUM(points),0) total FROM reward_points WHERE user_id=? AND (expires_at IS NULL OR expires_at>=CURDATE())',[$uid])['total']??0);$wishlistCount=db_count('wishlists','user_id=?',[$uid]);
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??'Customer dashboard module.') ?></p></div><a class="btn btn-primary" href="<?= url('public/products.php') ?>">Continue Shopping</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"><div class="small text-muted">Orders</div><strong><?= db_count('orders','customer_id=?',[$uid]) ?></strong></div></div><div class="col-md-3"><div class="stat-tile"><div class="small text-muted">Purchase Wallet</div><strong><?= money(WalletService::balance($uid,'purchase')) ?></strong></div></div><div class="col-md-3"><div class="stat-tile"><div class="small text-muted">Reward Points</div><strong><?= number_format($points) ?></strong></div></div><div class="col-md-3"><div class="stat-tile"><div class="small text-muted">Wishlist</div><strong><?= $wishlistCount ?></strong></div></div></div>

<?php if($slug==='dashboard'): ?>
<div class="row g-4"><div class="col-lg-8"><div class="card module-card"><div class="card-header bg-white"><strong>Recent orders</strong></div><div class="table-responsive"><table class="table mb-0"><thead><tr><th>Order</th><th>Total</th><th>Payment</th><th>Status</th><th></th></tr></thead><tbody><?php if(!$orders): ?><?= table_empty(5,'No orders yet.') ?><?php endif; ?><?php foreach(array_slice($orders,0,8) as $o): ?><tr><td><?= e($o['order_no']) ?></td><td><?= money($o['total_amount']) ?></td><td><?= badge($o['payment_status']) ?></td><td><?= badge($o['order_status']) ?></td><td><a class="btn btn-sm btn-outline-primary" href="<?= url('customer/orders.php?id='.$o['id']) ?>">View</a></td></tr><?php endforeach; ?></tbody></table></div></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('public/products.php') ?>">Shop Now</a><a class="btn btn-outline-primary" href="<?= url('customer/wallet.php') ?>">Wallet</a><a class="btn btn-outline-primary" href="<?= url('customer/support.php') ?>">Support Ticket</a></div></div></div></div></div>

<?php elseif($slug==='orders'): $selected=!empty($_GET['id'])?Database::safeFetchOne('SELECT * FROM orders WHERE id=? AND customer_id=?',[(int)$_GET['id'],$uid]):null; ?>
<div class="card module-card"><div class="card-header bg-white"><strong>Order history</strong></div><div class="table-responsive"><table class="table mb-0"><thead><tr><th>Order</th><th>Date</th><th>Total</th><th>Payment</th><th>Status</th><th></th></tr></thead><tbody><?php if(!$orders): ?><?= table_empty(6,'No orders yet.') ?><?php endif; ?><?php foreach($orders as $o): ?><tr><td><?= e($o['order_no']) ?></td><td><?= e($o['created_at']) ?></td><td><?= money($o['total_amount']) ?></td><td><?= badge($o['payment_status']) ?></td><td><?= badge($o['order_status']) ?></td><td><a class="btn btn-sm btn-outline-primary" href="?id=<?= (int)$o['id'] ?>">Details</a> <a class="btn btn-sm btn-outline-secondary" href="<?= url('customer/invoice.php?id='.$o['id']) ?>">Invoice</a></td></tr><?php endforeach; ?></tbody></table></div></div><?php if($selected): $items=Database::safeFetchAll('SELECT * FROM order_items WHERE order_id=?',[$selected['id']]); ?><div class="card module-card mt-4"><div class="card-body"><h4><?= e($selected['order_no']) ?></h4><p><?= e($selected['delivery_address']) ?></p><table class="table"><tr><th>Product</th><th>Qty</th><th>Price</th><th>Total</th></tr><?php foreach($items as $i): ?><tr><td><?= e($i['product_name']) ?></td><td><?= (int)$i['qty'] ?></td><td><?= money($i['unit_price']) ?></td><td><?= money($i['total_price']) ?></td></tr><?php endforeach; ?></table></div></div><?php endif; ?>

<?php elseif($slug==='addresses'): $addresses=Database::safeFetchAll('SELECT a.*,d.name district_name,ar.name area_name FROM addresses a LEFT JOIN districts d ON d.id=a.district_id LEFT JOIN areas ar ON ar.id=a.area_id WHERE a.user_id=? ORDER BY a.is_default DESC,a.id DESC',[$uid]);$districts=Database::safeFetchAll('SELECT * FROM districts WHERE status="active" ORDER BY name');$areas=Database::safeFetchAll('SELECT * FROM areas 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>Add address</h5><form method="post"><?= csrf_field() ?><input type="hidden" name="_action" value="save"><input class="form-control mb-2" name="label" placeholder="Label: Home/Office"><input class="form-control mb-2" name="recipient_name" placeholder="Recipient name" required><input class="form-control mb-2" name="phone" placeholder="Phone"><select class="form-select mb-2" name="district_id"><option value="">District</option><?php foreach($districts as $d): ?><option value="<?= (int)$d['id'] ?>"><?= e($d['name']) ?></option><?php endforeach; ?></select><select class="form-select mb-2" name="area_id"><option value="">Area</option><?php foreach($areas as $a): ?><option value="<?= (int)$a['id'] ?>"><?= e($a['name']) ?></option><?php endforeach; ?></select><textarea class="form-control mb-3" name="address_line" placeholder="Full address" required></textarea><button class="btn btn-primary">Save address</button></form></div></div></div><div class="col-lg-7"><div class="card module-card"><div class="card-body"><h5>Saved addresses</h5><?php if(!$addresses): ?><p class="text-muted">No saved addresses.</p><?php endif; ?><?php foreach($addresses as $a): ?><div class="border rounded p-3 mb-2"><div class="d-flex justify-content-between"><strong><?= e($a['label']?:'Address') ?> <?= $a['is_default']?'<span class="badge bg-success">Default</span>':'' ?></strong><div><form method="post" class="d-inline"><?= csrf_field() ?><input type="hidden" name="_action" value="default"><input type="hidden" name="id" value="<?= (int)$a['id'] ?>"><button class="btn btn-sm btn-outline-primary">Default</button></form> <form method="post" class="d-inline"><?= csrf_field() ?><input type="hidden" name="_action" value="delete"><input type="hidden" name="id" value="<?= (int)$a['id'] ?>"><button class="btn btn-sm btn-outline-danger">Delete</button></form></div></div><p class="mb-0"><?= e($a['recipient_name']) ?>, <?= e($a['phone']) ?><br><?= e($a['address_line']) ?>, <?= e($a['area_name']??'') ?> <?= e($a['district_name']??'') ?></p></div><?php endforeach; ?></div></div></div></div>

<?php elseif($slug==='wallet'): $tx=Database::safeFetchAll('SELECT * FROM wallet_transactions WHERE user_id=? ORDER BY id DESC LIMIT 50',[$uid]); ?>
<div class="row g-4"><div class="col-lg-7"><div class="card module-card"><div class="card-body"><h5>Wallet balances</h5><table class="table"><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><h5>Recent transactions</h5><table class="table"><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><div class="col-lg-5"><div class="card module-card"><div class="card-body"><h5>Cash to purchase wallet</h5><form onsubmit="event.preventDefault();fetch('<?= url('api/wallet-transfer.php') ?>',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams({csrf_token:'<?= e(csrf_token()) ?>',from:'cash',to:'purchase',amount:this.amount.value})}).then(r=>r.json()).then(x=>{alert(x.message);if(x.ok)location.reload();})"><input class="form-control mb-3" name="amount" type="number" min="1" step="0.01" required><button class="btn btn-primary">Transfer</button></form></div></div></div></div>

<?php elseif($slug==='rewards'): $history=Database::safeFetchAll('SELECT * FROM reward_points WHERE user_id=? ORDER BY id DESC LIMIT 50',[$uid]); ?>
<div class="row g-4"><div class="col-lg-7"><div class="card module-card"><div class="card-body"><h5>Reward history</h5><table class="table"><tr><th>Date</th><th>Type</th><th>Points</th><th>Expiry</th></tr><?php if(!$history): ?><?= table_empty(4,'No reward history.') ?><?php endif; ?><?php foreach($history as $h): ?><tr><td><?= e($h['created_at']) ?></td><td><?= e($h['point_type']) ?></td><td><?= (int)$h['points'] ?></td><td><?= e($h['expires_at']??'Never') ?></td></tr><?php endforeach; ?></table></div></div></div><div class="col-lg-5"><div class="card module-card"><div class="card-body"><h5>Convert points</h5><p>Available: <strong><?= number_format($points) ?></strong></p><form onsubmit="event.preventDefault();fetch('<?= url('api/reward-redeem.php') ?>',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams({csrf_token:'<?= e(csrf_token()) ?>',points:this.points.value})}).then(r=>r.json()).then(x=>{alert(x.message);if(x.ok)location.reload();})"><input class="form-control mb-3" name="points" type="number" min="1" required><button class="btn btn-primary">Convert to purchase wallet</button></form></div></div></div></div>

<?php elseif($slug==='wishlist'||$slug==='compare'): $table=$slug==='wishlist'?'wishlists':'compares';$items=Database::safeFetchAll("SELECT p.* FROM `{$table}` x JOIN products p ON p.id=x.product_id WHERE x.user_id=? ORDER BY x.id DESC",[$uid]); ?>
<div class="row g-4"><?php if(!$items): ?><div class="col-12"><div class="alert alert-info">No saved products.</div></div><?php endif; ?><?php foreach($items as $p): ?><div class="col-md-4"><div class="product-card"><img class="w-100" src="<?= e(product_image($p)) ?>"><div class="p-3"><h6><?= e($p['name']) ?></h6><div class="price"><?= money($p['sale_price']?:$p['regular_price']) ?></div><button class="btn btn-primary btn-sm" onclick="phAddCart(<?= (int)$p['id'] ?>,1)">Add cart</button></div></div></div><?php endforeach; ?></div>

<?php elseif($slug==='returns'): $returns=Database::safeFetchAll('SELECT r.*,o.order_no,p.name product_name FROM returns r LEFT JOIN orders o ON o.id=r.order_id LEFT JOIN products p ON p.id=r.product_id WHERE r.user_id=? ORDER BY r.id DESC',[$uid]); ?>
<div class="row g-4"><div class="col-lg-5"><div class="card module-card"><div class="card-body"><h5>Request return</h5><form method="post"><?= csrf_field() ?><input type="hidden" name="_action" value="create"><select class="form-select mb-2" name="order_id" required><option value="">Select order</option><?php foreach($orders as $o): ?><option value="<?= (int)$o['id'] ?>"><?= e($o['order_no']) ?></option><?php endforeach; ?></select><input class="form-control mb-2" name="product_id" type="number" placeholder="Product ID (optional)"><select class="form-select mb-2" name="preferred_solution"><option value="refund">Refund</option><option value="replacement">Replacement</option></select><textarea class="form-control mb-3" name="reason" required placeholder="Reason"></textarea><button class="btn btn-primary">Submit</button></form></div></div></div><div class="col-lg-7"><div class="card module-card"><div class="card-body"><h5>Return history</h5><table class="table"><tr><th>Order</th><th>Product</th><th>Solution</th><th>Status</th></tr><?php if(!$returns): ?><?= table_empty(4,'No returns.') ?><?php endif; ?><?php foreach($returns as $r): ?><tr><td><?= e($r['order_no']??'') ?></td><td><?= e($r['product_name']??'') ?></td><td><?= e($r['preferred_solution']) ?></td><td><?= badge($r['status']) ?></td></tr><?php endforeach; ?></table></div></div></div></div>

<?php elseif($slug==='reviews'): $purchases=Database::safeFetchAll('SELECT DISTINCT p.id,p.name FROM order_items oi JOIN orders o ON o.id=oi.order_id JOIN products p ON p.id=oi.product_id WHERE o.customer_id=? AND o.order_status="delivered"',[$uid]);$reviews=Database::safeFetchAll('SELECT pr.*,p.name product_name FROM product_reviews pr JOIN products p ON p.id=pr.product_id WHERE pr.user_id=? ORDER BY pr.id DESC',[$uid]); ?>
<div class="row g-4"><div class="col-lg-5"><div class="card module-card"><div class="card-body"><h5>Write review</h5><form method="post"><?= csrf_field() ?><input type="hidden" name="_action" value="create"><select name="product_id" class="form-select mb-2" required><option value="">Delivered product</option><?php foreach($purchases as $p): ?><option value="<?= (int)$p['id'] ?>"><?= e($p['name']) ?></option><?php endforeach; ?></select><select name="rating" class="form-select mb-2"><?php for($i=5;$i>=1;$i--): ?><option value="<?= $i ?>"><?= $i ?> star</option><?php endfor; ?></select><textarea class="form-control mb-3" name="review" required></textarea><button class="btn btn-primary">Submit</button></form></div></div></div><div class="col-lg-7"><div class="card module-card"><div class="card-body"><table class="table"><tr><th>Product</th><th>Rating</th><th>Status</th></tr><?php foreach($reviews as $r): ?><tr><td><?= e($r['product_name']) ?></td><td><?= (int)$r['rating'] ?>/5</td><td><?= badge($r['status']) ?></td></tr><?php endforeach; ?></table></div></div></div></div>

<?php elseif($slug==='security'): $history=Database::safeFetchAll('SELECT * FROM login_history WHERE user_id=? ORDER BY id DESC LIMIT 20',[$uid]); ?>
<div class="row g-4"><div class="col-lg-6"><div class="card module-card"><div class="card-body"><h5>Change password</h5><form method="post"><?= csrf_field() ?><input type="hidden" name="_action" value="password"><input class="form-control mb-2" type="password" name="current_password" placeholder="Current password" required><input class="form-control mb-3" type="password" name="new_password" minlength="8" placeholder="New password" required><button class="btn btn-primary">Update password</button></form><hr><h5>Transaction security</h5><form method="post"><?= csrf_field() ?><input type="hidden" name="_action" value="pin"><input class="form-control mb-2" type="password" name="pin" minlength="4" placeholder="New transaction PIN" required><label><input type="checkbox" name="two_factor_enabled" value="1"> Enable 2FA flag</label><br><button class="btn btn-outline-primary mt-2">Save security</button></form></div></div></div><div class="col-lg-6"><div class="card module-card"><div class="card-body"><h5>Login history</h5><table class="table"><tr><th>Date</th><th>IP</th></tr><?php foreach($history as $h): ?><tr><td><?= e($h['created_at']) ?></td><td><?= e($h['ip_address']) ?></td></tr><?php endforeach; ?></table></div></div></div></div>

<?php elseif($slug==='support'): $tickets=Database::safeFetchAll('SELECT * FROM support_tickets WHERE user_id=? ORDER BY id DESC',[$uid]); ?>
<div class="row g-4"><div class="col-lg-5"><div class="card module-card"><div class="card-body"><h5>Create ticket</h5><form method="post"><?= csrf_field() ?><input type="hidden" name="_action" value="create"><input class="form-control mb-2" name="subject" placeholder="Subject" required><textarea class="form-control mb-3" name="message" rows="5" required></textarea><button class="btn btn-primary">Send ticket</button></form></div></div></div><div class="col-lg-7"><div class="card module-card"><div class="card-body"><h5>Tickets</h5><table class="table"><tr><th>ID</th><th>Subject</th><th>Status</th><th>Date</th></tr><?php if(!$tickets): ?><?= table_empty(4,'No support tickets.') ?><?php endif; ?><?php foreach($tickets as $t): ?><tr><td>#<?= (int)$t['id'] ?></td><td><?= e($t['subject']) ?></td><td><?= badge($t['status']) ?></td><td><?= e($t['created_at']) ?></td></tr><?php endforeach; ?></table></div></div></div></div>

<?php elseif($slug==='invoice'): $order=Database::safeFetchOne('SELECT * FROM orders WHERE id=? AND customer_id=?',[(int)($_GET['id']??0),$uid]); ?>
<?php if(!$order): ?><div class="alert alert-warning">Invoice not found.</div><?php else: $items=Database::safeFetchAll('SELECT * FROM order_items WHERE order_id=?',[$order['id']]); ?><div class="card module-card"><div class="card-body p-4"><div class="d-flex justify-content-between"><div><h2><?= e(BRAND_NAME) ?></h2><p>Invoice for <?= e($order['order_no']) ?></p></div><button class="btn btn-outline-primary" onclick="window.print()">Print</button></div><hr><p><strong><?= e($order['customer_name']) ?></strong><br><?= nl2br(e($order['delivery_address'])) ?><br><?= e($order['customer_phone']) ?></p><table class="table"><tr><th>Product</th><th>Qty</th><th>Price</th><th>Total</th></tr><?php foreach($items as $i): ?><tr><td><?= e($i['product_name']) ?></td><td><?= (int)$i['qty'] ?></td><td><?= money($i['unit_price']) ?></td><td><?= money($i['total_price']) ?></td></tr><?php endforeach; ?><tr><th colspan="3" class="text-end">Grand total</th><th><?= money($order['total_amount']) ?></th></tr></table></div></div><?php endif; ?>

<?php elseif($slug==='referrals'): $refs=Database::safeFetchAll('SELECT r.*,u.name referred_name,u.email referred_email FROM referrals r LEFT JOIN users u ON u.id=r.referred_user_id WHERE r.referrer_user_id=? ORDER BY r.id DESC',[$uid]); ?>
<div class="card module-card"><div class="card-body"><h5>Referral activity</h5><table class="table"><tr><th>User</th><th>Code</th><th>Reward</th><th>Status</th></tr><?php if(!$refs): ?><?= table_empty(4,'No referral activity.') ?><?php endif; ?><?php foreach($refs as $r): ?><tr><td><?= e($r['referred_name']??$r['referred_email']??'') ?></td><td><?= e($r['referral_code']) ?></td><td><?= money($r['reward_amount']) ?></td><td><?= badge($r['status']) ?></td></tr><?php endforeach; ?></table></div></div>
<?php endif; ?>
<?php require ROOT_PATH.'/app/Layouts/panel_footer.php'; ?>
