<?php
require_once __DIR__ . '/../app/bootstrap.php';

use App\Core\Auth;
use App\Core\Database;
use App\Core\Security;

Auth::requireRole(['admin']);
$pageTitle = 'Staff Users | 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="staff" LIMIT 1',[$editingId]) : null;

if($_SERVER['REQUEST_METHOD']==='POST'){
    if(!verify_csrf()) $errors[]='Invalid security token.';
    else{
        try{
            $action=(string)($_POST['_action']??'save');
            if($action==='status'){
                $id=(int)($_POST['id']??0);$status=(string)($_POST['status']??'suspended');
                if(!in_array($status,['active','suspended'],true)) throw new RuntimeException('Invalid staff status.');
                Database::execute('UPDATE users SET status=?,auth_version=COALESCE(auth_version,1)+1,updated_at=NOW() WHERE id=? AND role="staff"',[$status,$id]);
                Security::logActivity(Auth::id(),'staff_status_changed',['staff_user_id'=>$id,'status'=>$status]);
                set_flash('success','Staff status updated.');
            }else{
                $id=(int)($_POST['id']??0);
                $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 address.');
                if(!in_array($status,['active','suspended'],true)) throw new RuntimeException('Invalid staff status.');
                $duplicate=Database::safeFetchOne('SELECT id FROM users WHERE LOWER(email)=? AND id<>? LIMIT 1',[$email,$id]);
                if($duplicate) throw new RuntimeException('That email address is already used by another account.');
                if($id>0){
                    if(!Database::safeFetchOne('SELECT id FROM users WHERE id=? AND role="staff" LIMIT 1',[$id])) throw new RuntimeException('Staff account not found.');
                    $params=[$name,$email,$phone?:null,$status];
                    $sql='UPDATE users SET name=?,email=?,phone=?,status=?';
                    if($password!==''){
                        if($message=Security::passwordError($password,$email)) throw new RuntimeException($message);
                        $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="staff"';$params[]=$id;
                    Database::execute($sql,$params);
                    Security::logActivity(Auth::id(),'staff_updated',['staff_user_id'=>$id,'password_reset'=>$password!=='']);
                    set_flash('success','Staff account updated.');
                }else{
                    if($message=Security::passwordError($password,$email)) throw new RuntimeException($message);
                    Database::execute('INSERT INTO users (role,name,email,phone,password_hash,auth_version,must_change_password,status,created_at,updated_at) VALUES ("staff",?,?,?,?,1,1,?,NOW(),NOW())',[$name,$email,$phone?:null,password_hash($password,PASSWORD_DEFAULT),$status]);
                    $id=Database::lastInsertId();
                    Security::logActivity(Auth::id(),'staff_created',['staff_user_id'=>$id]);
                    set_flash('success','Staff account created. The user must change the temporary password at first login.');
                }
            }
            redirect('admin/staff.php');
        }catch(Throwable $e){$errors[]=$e->getMessage();}
    }
}

$q=mb_substr(trim((string)($_GET['q']??'')),0,100);$params=[];$where='role="staff"';
if($q!==''){$where.=' AND (name LIKE ? OR email LIKE ? OR phone LIKE ?)';$like='%'.$q.'%';$params=[$like,$like,$like];}
$staff=Database::safeFetchAll("SELECT id,name,email,phone,status,last_login_at,created_at,must_change_password FROM users WHERE {$where} ORDER BY id DESC LIMIT 200",$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">Staff Users</h1><p class="text-muted mb-0">Create staff accounts and manage their login status. Module access is assigned from Roles & Permissions.</p></div><a class="btn btn-outline-primary" href="<?= url('admin/roles.php') ?>">Roles & Permissions</a></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 staff account':'Create staff account' ?></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) ?>"><label class="form-label">Name</label><input class="form-control mb-3" name="name" maxlength="150" value="<?= e($editing['name']??'') ?>" required><label class="form-label">Email</label><input class="form-control mb-3" type="email" name="email" maxlength="150" value="<?= e($editing['email']??'') ?>" required><label class="form-label">Phone</label><input class="form-control mb-3" name="phone" maxlength="50" value="<?= e($editing['phone']??'') ?>"><label class="form-label"><?= $editing?'New temporary password (optional)':'Temporary password' ?></label><input class="form-control mb-3" type="password" name="password" minlength="<?= PASSWORD_MIN_LENGTH ?>" <?= $editing?'':'required' ?> autocomplete="new-password"><label class="form-label">Status</label><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 staff':'Create staff' ?></button><?php if($editing): ?> <a class="btn btn-link" href="<?= url('admin/staff.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 class="d-flex gap-2" method="get"><input class="form-control" name="q" value="<?= e($q) ?>" placeholder="Search staff"><button class="btn btn-outline-primary">Search</button><a class="btn btn-outline-secondary" href="<?= url('api/export.php?table=users&module=staff') ?>">Export</a></form></div><div class="table-responsive"><table class="table align-middle mb-0"><thead><tr><th>Name</th><th>Contact</th><th>Status</th><th>Last login</th><th>Actions</th></tr></thead><tbody><?php if(!$staff): ?><?= table_empty(5,'No staff accounts found.') ?><?php endif; ?><?php foreach($staff 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; ?></td><td><?= e($row['email']) ?><div class="small text-muted"><?= e($row['phone']??'') ?></div></td><td><?= badge($row['status']) ?></td><td><?= e($row['last_login_at']??'Never') ?></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 staff account 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'; ?>
