<?php
declare(strict_types=1);
require __DIR__.'/bootstrap.php';
if(isset($_GET['logout'])){ session_destroy(); header('Location: cms.php'); exit; }
$error='';
if(!user() && $_SERVER['REQUEST_METHOD']==='POST'){
  $st=$pdo->prepare('SELECT * FROM users WHERE email=? AND active=1');
  $st->execute([strtolower(trim($_POST['email']??''))]);
  $u=$st->fetch();
  if($u && password_verify((string)($_POST['password']??''),$u['password_hash'])){
    unset($u['password_hash']); $_SESSION['user']=$u; csrf(); header('Location: cms.php'); exit;
  }
  $error='Invalid email or password.';
}
if(!user()):
?><!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>StoryBook CMS</title><style>*{box-sizing:border-box}body{margin:0;display:grid;min-height:100vh;place-items:center;background:#f4efe7;color:#241d18;font-family:Arial,sans-serif}.login{width:min(430px,92vw);padding:30px;border:1px solid #d9cfc2;border-radius:20px;background:#fffdf9;box-shadow:0 20px 60px #32211626}.brand{display:flex;align-items:center;gap:12px}.icon{display:grid;width:40px;height:40px;place-items:center;border-radius:12px;background:#8a3f32;color:white}.brand b{display:block;font:700 24px Georgia}.brand small{color:#8a776b;font-size:10px;font-weight:800;letter-spacing:.18em}.hint{color:#76665b;font-size:13px}label{display:block;margin-top:16px;font-size:13px;font-weight:700}input{width:100%;margin-top:6px;padding:12px;border:1px solid #cdbfb2;border-radius:9px;font:inherit}button{width:100%;margin-top:20px;padding:12px;border:0;border-radius:9px;background:#294c46;color:white;font-weight:800}.error{margin-top:15px;padding:10px;border-radius:8px;background:#fff0f0;color:#922b35;font-size:12px}</style></head><body><form class="login" method="post"><div class="brand"><span class="icon">&#128214;</span><span><b>StoryBook</b><small>PERSONALIZED STUDIO</small></span></div><p class="hint">Sign in to continue to the production CMS.</p><?php if($error):?><div class="error"><?=e($error)?></div><?php endif?><label>Email<input type="email" name="email" required autofocus></label><label>Password<input type="password" name="password" required></label><button>Sign in</button></form></body></html><?php exit; endif;
$rows=$pdo->query('SELECT state_key,state_json FROM cms_state')->fetchAll(); $state=[];foreach($rows as $r)$state[$r['state_key']]=json_decode($r['state_json'],true)??[];if(user()['role']==='manager'){unset($state['storybook-overheads']);}
$bookRows=$pdo->query('SELECT book_json FROM production_books ORDER BY updated_at DESC')->fetchAll();$books=[];foreach($bookRows as $r){$b=json_decode($r['book_json'],true);if(is_array($b))$books[]=$b;}
$users=$pdo->query('SELECT id,name,role,active FROM users ORDER BY name')->fetchAll();
$html=file_get_contents(__DIR__.'/app.html');
$jsonFlags=JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT;
$bootstrap='<script>window.__CMS_ROLE__='.json_encode(user()['role']).';window.__CMS_USER_ADMIN__='.(user()['role']==='admin'?'true':'false').';window.__CMS_CURRENT_USER__='.json_encode(['id'=>(int)user()['id'],'name'=>user()['name'],'role'=>user()['role']],$jsonFlags).';window.__CMS_USERS__='.json_encode($users,$jsonFlags).';window.__CMS_BOOKS__='.json_encode($books,$jsonFlags).';const __csrf='.json_encode(csrf()).',__isAdmin='.(user()['role']==='admin'?'true':'false').',__s='.json_encode($state,$jsonFlags).';if(!__isAdmin){localStorage.removeItem("storybook-overheads")}for(const [k,v] of Object.entries(__s)){try{localStorage.setItem(k,JSON.stringify(v))}catch(e){}}const __set=localStorage.setItem.bind(localStorage);localStorage.setItem=(k,v)=>{try{__set(k,v)}catch(e){}if(["storybook-orders","storybook-production","storybook-print-batches"].includes(k)||(__isAdmin&&k==="storybook-overheads"))fetch("api.php",{method:"POST",headers:{"Content-Type":"application/json","X-CSRF-Token":__csrf},body:JSON.stringify({key:k,value:JSON.parse(v)})}).catch(()=>{})};window.__CMS_SAVE_BOOK__=async(book)=>{const r=await fetch("api.php",{method:"POST",headers:{"Content-Type":"application/json","X-CSRF-Token":__csrf},body:JSON.stringify({action:"save_book",book})});const j=await r.json();if(!r.ok||!j.ok)throw new Error(j.error||"Save failed");return j.book};window.__CMS_UPLOAD_IMAGE__=async(file,kind)=>{const f=new FormData();f.append("image",file);f.append("kind",kind);const r=await fetch("upload.php",{method:"POST",headers:{"X-CSRF-Token":__csrf},body:f});const j=await r.json();if(!r.ok||!j.ok)throw new Error(j.error||"Upload failed");return j.url};</script>';
$bootstrap=str_replace('</script>','window.__CMS_PREVIEW_LINK__=async(bookId)=>{const r=await fetch("api.php",{method:"POST",headers:{"Content-Type":"application/json","X-CSRF-Token":__csrf},body:JSON.stringify({action:"preview_link",book_id:bookId})});const j=await r.json();if(!r.ok||!j.ok)throw new Error(j.error||"Could not create customer link");return new URL(j.url,window.location.href).href};</script>',$bootstrap);
$html=str_replace('<div id="root"></div>',$bootstrap.'<div id="root"></div>',$html);
$html=str_replace(['src="/assets/','href="/assets/'],['src="assets/','href="assets/'],$html);
echo $html;
