<?php
declare(strict_types=1); require __DIR__.'/bootstrap.php'; header('Content-Type: application/json; charset=utf-8');
if(!user()){http_response_code(401);echo json_encode(['ok'=>false]);exit;} if($_SERVER['REQUEST_METHOD']!=='POST'){http_response_code(405);exit;}
if(!hash_equals($_SESSION['csrf']??'',$_SERVER['HTTP_X_CSRF_TOKEN']??'')){http_response_code(419);echo json_encode(['ok'=>false,'error'=>'csrf']);exit;}
$in=json_decode(file_get_contents('php://input'),true)?:[]; $action=(string)($in['action']??'state');
if($action==='preview_link'){
 $id=preg_replace('/[^A-Za-z0-9_-]/','',(string)($in['book_id']??''));
 if(!$id){http_response_code(422);echo json_encode(['ok'=>false,'error'=>'Save the book first']);exit;}
 $st=$pdo->prepare('SELECT id FROM production_books WHERE id=?');$st->execute([$id]);
 if(!$st->fetch()){http_response_code(404);echo json_encode(['ok'=>false,'error'=>'Book not found']);exit;}
 $secret=hash('sha256',(string)($config['db_pass']??'').':'.(string)($config['db_name']??'').':storybook-preview');
 $token=hash_hmac('sha256',$id,$secret);
 $base=rtrim(dirname($_SERVER['SCRIPT_NAME']??'/'),'/\\');
 $url=($base===''?'':$base).'/preview.php?book='.rawurlencode($id).'&token='.$token;
 echo json_encode(['ok'=>true,'url'=>$url],JSON_UNESCAPED_SLASHES);exit;
}
if($action==='save_book'){
 $b=$in['book']??[];$id=preg_replace('/[^A-Za-z0-9_-]/','',(string)($b['id']??''));$oid=(string)($b['orderId']??'');
 if(!$id||!$oid||!is_array($b['pages']??null)){http_response_code(422);echo json_encode(['ok'=>false,'error'=>'invalid book']);exit;}
 $b['id']=$id;$b['updatedAt']=gmdate('c');$json=json_encode($b,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);if(strlen($json)>8*1024*1024){http_response_code(413);echo json_encode(['ok'=>false,'error'=>'book too large']);exit;}
 $st=$pdo->prepare('INSERT INTO production_books(id,order_id,theme,language,book_json,created_by,updated_by) VALUES(?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE order_id=VALUES(order_id),theme=VALUES(theme),language=VALUES(language),book_json=VALUES(book_json),updated_by=VALUES(updated_by)');$st->execute([$id,$oid,(string)($b['theme']??''),(string)($b['language']??'en'),$json,user()['id'],user()['id']]);echo json_encode(['ok'=>true,'book'=>$b],JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);exit;
}
$key=(string)($in['key']??'');$allowed=['storybook-orders','storybook-production','storybook-print-batches','storybook-overheads'];if(!in_array($key,$allowed,true)||!array_key_exists('value',$in)){http_response_code(422);echo json_encode(['ok'=>false]);exit;}$value=$in['value'];
if((user()['role']??'')==='manager'&&$key==='storybook-overheads'){http_response_code(403);echo json_encode(['ok'=>false,'error'=>'admin only']);exit;}
$json=json_encode($value,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);$st=$pdo->prepare('INSERT INTO cms_state(state_key,state_json,updated_by) VALUES(?,?,?) ON DUPLICATE KEY UPDATE state_json=VALUES(state_json),updated_by=VALUES(updated_by)');$st->execute([$key,$json,user()['id']]);echo json_encode(['ok'=>true]);
