<?php
declare(strict_types=1);
require __DIR__.'/bootstrap.php';
require_admin();
$ok=''; $error='';
if($_SERVER['REQUEST_METHOD']==='POST'){
  try{
    check_csrf();
    $id=(int)($_POST['id']??0); $name=trim((string)($_POST['name']??''));
    $email=strtolower(trim((string)($_POST['email']??''))); $password=(string)($_POST['password']??'');
    $role=in_array($_POST['role']??'', ['admin','manager'],true)?$_POST['role']:'manager';
    $active=isset($_POST['active'])?1:0;
    if($name===''||!filter_var($email,FILTER_VALIDATE_EMAIL)) throw new RuntimeException('Valid name and email are required.');
    if($id===(int)user()['id']){$role='admin';$active=1;}
    if($id){
      if($password!=='' && strlen($password)<8) throw new RuntimeException('New password must contain at least 8 characters.');
      if($password!==''){$st=$pdo->prepare('UPDATE users SET name=?,email=?,role=?,active=?,password_hash=? WHERE id=?');$st->execute([$name,$email,$role,$active,password_hash($password,PASSWORD_DEFAULT),$id]);}
      else{$st=$pdo->prepare('UPDATE users SET name=?,email=?,role=?,active=? WHERE id=?');$st->execute([$name,$email,$role,$active,$id]);}
      if($id===(int)user()['id']){$_SESSION['user']['name']=$name;$_SESSION['user']['email']=$email;}
      $ok='User account updated successfully.';
    }else{
      if(strlen($password)<8) throw new RuntimeException('Password must contain at least 8 characters.');
      $st=$pdo->prepare('INSERT INTO users(name,email,password_hash,role,active) VALUES(?,?,?,?,1)');$st->execute([$name,$email,password_hash($password,PASSWORD_DEFAULT),$role]);
      $ok='New user account created successfully.';
    }
  }catch(Throwable $e){$error=$e instanceof PDOException?'This email is already used by another account.':$e->getMessage();}
}
$users=$pdo->query('SELECT id,name,email,role,active,created_at FROM users ORDER BY role,id')->fetchAll();
?><!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Users · StoryBook CMS</title><style>:root{--ink:#241d18;--paper:#f4efe7;--card:#fffdf9;--line:#d9cfc2;--red:#8a3f32;--green:#294c46}*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font-family:Arial,sans-serif}header{position:sticky;top:0;z-index:5;display:flex;align-items:center;gap:12px;min-height:64px;padding:9px max(16px,calc((100vw - 1500px)/2));border-bottom:1px solid var(--line);background:#fffdf9f5}.brand{display:flex;align-items:center;gap:11px;color:var(--ink);text-decoration:none}.icon{display:grid;width:36px;height:36px;place-items:center;border-radius:12px;background:var(--red);color:#fff}.brand b{display:block;font:700 20px Georgia}.brand small{display:block;margin-top:4px;color:#8a776b;font-size:10px;font-weight:800;letter-spacing:.16em}.back{margin-left:auto;padding:9px 13px;border:1px solid #cdbfb2;border-radius:9px;background:white;color:var(--ink);text-decoration:none;font-size:13px;font-weight:800}main{max-width:1250px;margin:auto;padding:25px 18px}h1,h2{font-family:Georgia,serif}.subtitle{color:#8a776b;font-size:12px;font-weight:800;letter-spacing:.16em}.layout{display:grid;grid-template-columns:340px 1fr;gap:18px}.card{padding:20px;border:1px solid var(--line);border-radius:16px;background:var(--card);box-shadow:0 4px 14px #39291c12}label{display:block;margin-top:12px;font-size:12px;font-weight:800}input,select{width:100%;margin-top:6px;padding:10px;border:1px solid #cfc2b6;border-radius:8px;background:white;font:inherit}button{margin-top:16px;padding:10px 15px;border:0;border-radius:9px;background:var(--green);color:#fff;font-weight:800;cursor:pointer}.notice{margin-bottom:15px;padding:11px;border-radius:9px}.ok{background:#e6f7ef;color:#176447}.error{background:#feecec;color:#922b35}.user{display:grid;grid-template-columns:1fr 1.35fr .8fr 1.15fr auto auto;gap:8px;align-items:end;padding:13px 0;border-bottom:1px solid #eee5dc}.check{display:flex;align-items:center;gap:6px;margin-bottom:10px}.check input{width:auto;margin:0}.user button{margin:0 0 1px}.hint{color:#8a776b;font-size:11px}@media(max-width:900px){.layout{grid-template-columns:1fr}.user{grid-template-columns:1fr 1fr}.user button{width:100%}}@media(max-width:550px){.user{grid-template-columns:1fr}}</style></head><body><header><a class="brand" href="index.php"><span class="icon">&#128214;</span><span><b>StoryBook</b><small>PERSONALIZED STUDIO</small></span></a><a class="back" href="index.php">Back to CMS</a></header><main><p class="subtitle">ADMIN PANEL</p><h1>User management</h1><?php if($ok):?><div class="notice ok"><?=e($ok)?></div><?php endif?><?php if($error):?><div class="notice error"><?=e($error)?></div><?php endif?><div class="layout"><section class="card"><h2>Add account</h2><p class="hint">Create another Admin or Production Manager.</p><form method="post"><input type="hidden" name="csrf" value="<?=csrf()?>"><label>Name<input name="name" required></label><label>Email<input type="email" name="email" required></label><label>Password<input type="password" name="password" minlength="8" required></label><label>Role<select name="role"><option value="manager">Production Manager</option><option value="admin">Admin</option></select></label><input type="hidden" name="active" value="1"><button>Create account</button></form></section><section class="card"><h2>Admin & Production Managers</h2><?php foreach($users as $u):?><form method="post" class="user"><input type="hidden" name="csrf" value="<?=csrf()?>"><input type="hidden" name="id" value="<?=$u['id']?>"><label>Name<input name="name" value="<?=e($u['name'])?>" required></label><label>Email<input type="email" name="email" value="<?=e($u['email'])?>" required></label><label>Role<select name="role" <?=$u['id']==user()['id']?'disabled':''?>><option value="manager" <?=$u['role']==='manager'?'selected':''?>>Production Manager</option><option value="admin" <?=$u['role']==='admin'?'selected':''?>>Admin</option></select><?php if($u['id']==user()['id']):?><input type="hidden" name="role" value="admin"><?php endif?></label><label>New password<input type="password" name="password" minlength="8" placeholder="Keep blank if unchanged"></label><label class="check"><input type="checkbox" name="active" <?=$u['active']?'checked':''?> <?=$u['id']==user()['id']?'disabled':''?>> Active<?php if($u['id']==user()['id']):?><input type="hidden" name="active" value="1"><?php endif?></label><button>Save</button></form><?php endforeach?></section></div></main></body></html>
