<?php
require_once __DIR__ . '/../app/bootstrap.php';
use App\Core\Auth;use App\Core\Database;use App\Core\Security;
Auth::requireRole(['admin','staff']);
$pageTitle='Customers | Admin';$errors=[];$editingId=max(0,(int)($_GET['edit']??$_POST['id']??0));
$editing=$editingId?Database::safeFetchOne('SELECT id,name,email,phone,status,created_at,last_login_at,must_change_password FROM users WHERE id=? AND role="customer" LIMIT 1',[$editingId]):null;
if($_SERVER['REQUEST_METHOD']==='POST'){
 if(!verify_csrf())$errors[]='Invalid security token.';else try{
  $action=(string)($_POST['_action']??'save');$id=(int)($_POST['id']??0);
  if($action==='status'){$status=(string)($_POST['status']??'suspended');if(!in_array($status,['active','suspended'],true))throw new RuntimeException('Invalid status.');Database::execute('UPDATE users SET status=?,auth_version=COALESCE(auth_version,1)+1,updated_at=NOW() WHERE id=? AND role="customer"',[$status,$id]);Security::logActivity(Auth::id(),'customer_status_changed',['customer_id'=>$id,'status'=>$status]);set_flash('success','Customer status updated.');}
  else{$name=mb_substr(trim((string)($_POST['name']??'')),0,150);$email=strtolower(mb_substr(trim((string)($_POST['email']??'')),0,150));$phone=mb_substr(trim((string)($_POST['phone']??'')),0,50);$status=(string)($_POST['status']??'active');$password=(string)($_POST['password']??'');if($name===''||!filter_var($email,FILTER_VALIDATE_EMAIL))throw new RuntimeException('Enter a valid name and email.');if(!in_array($status,['active','suspended'],true))throw new RuntimeException('Invalid status.');if(Database::safeFetchOne('SELECT id FROM users WHERE LOWER(email)=? AND id<>? LIMIT 1',[$email,$id]))throw new RuntimeException('That email is already registered.');
   if($id){if(!$editing)throw new RuntimeException('Customer not found.');$params=[$name,$email,$phone?:null,$status];$sql='UPDATE users SET name=?,email=?,phone=?,status=?';if($password!==''){if($m=Security::passwordError($password,$email))throw new RuntimeException($m);$sql.=',password_hash=?,auth_version=COALESCE(auth_version,1)+1,must_change_password=1,password_changed_at=NULL';$params[]=password_hash($password,PASSWORD_DEFAULT);}$sql.=',updated_at=NOW() WHERE id=? AND role="customer"';$params[]=$id;Database::execute($sql,$params);Security::logActivity(Auth::id(),'customer_updated',['customer_id'=>$id,'password_reset'=>$password!=='']);set_flash('success','Customer updated.');}
   else{if($m=Security::passwordError($password,$email))throw new RuntimeException($m);$id=Database::transaction(function()use($name,$email,$phone,$password,$status){Database::execute('INSERT INTO users (role,name,email,phone,password_hash,auth_version,must_change_password,status,created_at,updated_at) VALUES ("customer",?,?,?,?,1,1,?,NOW(),NOW())',[$name,$email,$phone?:null,password_hash($password,PASSWORD_DEFAULT),$status]);$id=Database::lastInsertId();foreach(['cash','purchase','point','reward'] as $type)Database::safeExecute('INSERT IGNORE INTO wallets (user_id,wallet_type,balance,created_at,updated_at) VALUES (?,?,0,NOW(),NOW())',[$id,$type]);return $id;});Security::logActivity(Auth::id(),'customer_created',['customer_id'=>$id]);set_flash('success','Customer created. A password change will be required at first login.');}
  }redirect('admin/customers.php');
 }catch(Throwable $e){$errors[]=$e->getMessage();}
}
$q=mb_substr(trim((string)($_GET['q']??'')),0,100);$params=[];$where='role="customer"';if($q!==''){$where.=' AND (name LIKE ? OR email LIKE ? OR phone LIKE ?)';$like='%'.$q.'%';$params=[$like,$like,$like];}$rows=Database::safeFetchAll("SELECT u.id,u.name,u.email,u.phone,u.status,u.last_login_at,u.created_at,u.must_change_password,(SELECT COUNT(*) FROM orders o WHERE o.customer_id=u.id) order_count,(SELECT COALESCE(SUM(o.total_amount),0) FROM orders o WHERE o.customer_id=u.id AND o.order_status='delivered') lifetime_value FROM users u WHERE {$where} ORDER BY u.id DESC LIMIT 300",$params);
require ROOT_PATH.'/app/Layouts/admin_header.php';
?>
<div class="d-flex justify-content-between align-items-start flex-wrap gap-3 mb-4"><div><h1 class="h3 mb-1">Customers</h1><p class="text-muted mb-0">Role-filtered customer accounts, status, order totals and secure temporary-password resets.</p></div></div><?php if($m=flash('success')): ?><div class="alert alert-success"><?= e($m) ?></div><?php endif; ?><?php foreach($errors as $error): ?><div class="alert alert-danger"><?= e($error) ?></div><?php endforeach; ?>
<div class="row g-4"><div class="col-lg-4"><div class="card module-card"><div class="card-header bg-white"><strong><?= $editing?'Edit customer':'Create customer' ?></strong></div><div class="card-body"><form method="post"><?= csrf_field() ?><input type="hidden" name="_action" value="save"><input type="hidden" name="id" value="<?= (int)($editing['id']??0) ?>"><input class="form-control mb-3" name="name" maxlength="150" value="<?= e($editing['name']??'') ?>" placeholder="Name" required><input class="form-control mb-3" type="email" name="email" maxlength="150" value="<?= e($editing['email']??'') ?>" placeholder="Email" required><input class="form-control mb-3" name="phone" maxlength="50" value="<?= e($editing['phone']??'') ?>" placeholder="Phone"><input class="form-control mb-3" type="password" name="password" minlength="<?= PASSWORD_MIN_LENGTH ?>" placeholder="<?= $editing?'New temporary password (optional)':'Temporary password' ?>" <?= $editing?'':'required' ?>><select class="form-select mb-3" name="status"><option value="active" <?= ($editing['status']??'active')==='active'?'selected':'' ?>>Active</option><option value="suspended" <?= ($editing['status']??'')==='suspended'?'selected':'' ?>>Suspended</option></select><button class="btn btn-primary"><?= $editing?'Update':'Create' ?></button><?php if($editing): ?> <a class="btn btn-link" href="<?= url('admin/customers.php') ?>">Cancel</a><?php endif; ?></form></div></div></div>
<div class="col-lg-8"><div class="card module-card"><div class="card-header bg-white"><form method="get" class="d-flex gap-2"><input class="form-control" name="q" value="<?= e($q) ?>" placeholder="Search customers"><button class="btn btn-outline-primary">Search</button><a class="btn btn-outline-secondary" href="<?= url('api/export.php?table=users&module=customers') ?>">Export</a></form></div><div class="table-responsive"><table class="table align-middle mb-0"><thead><tr><th>Customer</th><th>Status</th><th>Orders</th><th>Delivered value</th><th>Actions</th></tr></thead><tbody><?php if(!$rows): ?><?= table_empty(5,'No customer accounts found.') ?><?php endif; ?><?php foreach($rows as $row): ?><tr><td><strong><?= e($row['name']) ?></strong><?php if(!empty($row['must_change_password'])): ?><span class="badge bg-warning text-dark ms-1">Password change required</span><?php endif; ?><div class="small text-muted"><?= e($row['email']) ?> · <?= e($row['phone']??'') ?></div></td><td><?= badge($row['status']) ?></td><td><?= (int)$row['order_count'] ?></td><td><?= money($row['lifetime_value']) ?></td><td class="text-nowrap"><a class="btn btn-sm btn-outline-primary" href="?edit=<?= (int)$row['id'] ?>">Edit</a> <form method="post" class="d-inline"><?= csrf_field() ?><input type="hidden" name="_action" value="status"><input type="hidden" name="id" value="<?= (int)$row['id'] ?>"><input type="hidden" name="status" value="<?= $row['status']==='active'?'suspended':'active' ?>"><button class="btn btn-sm btn-outline-<?= $row['status']==='active'?'danger':'success' ?>" onclick="return confirm('Change this customer status?')"><?= $row['status']==='active'?'Suspend':'Activate' ?></button></form></td></tr><?php endforeach; ?></tbody></table></div></div></div></div>
<?php require ROOT_PATH.'/app/Layouts/admin_footer.php'; ?>
