<?php
declare(strict_types=1);
if(is_file(__DIR__.'/config.php')) exit('Already installed. Delete install.php for security. Open index.php for the Storefront or cms.php for CMS login.');
$error='';
if($_SERVER['REQUEST_METHOD']==='POST'){
  try {
    $host=trim($_POST['db_host']??'localhost'); $name=trim($_POST['db_name']??''); $dbuser=trim($_POST['db_user']??''); $pass=(string)($_POST['db_pass']??'');
    $admin=trim($_POST['admin_name']??''); $email=strtolower(trim($_POST['admin_email']??'')); $adminPass=(string)($_POST['admin_password']??'');
    if(!$name||!$dbuser||!$admin||!filter_var($email,FILTER_VALIDATE_EMAIL)||strlen($adminPass)<8) throw new RuntimeException('Complete every field. Admin password needs at least 8 characters.');
    $pdo=new PDO("mysql:host=$host;dbname=$name;charset=utf8mb4",$dbuser,$pass,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
    $sql=file_get_contents(__DIR__.'/schema.sql'); foreach(array_filter(array_map('trim',preg_split('/;\s*(?:\r?\n|$)/',$sql))) as $q) $pdo->exec($q);
    $st=$pdo->prepare('INSERT INTO users(name,email,password_hash,role,active) VALUES(?,?,?,?,1)'); $st->execute([$admin,$email,password_hash($adminPass,PASSWORD_DEFAULT),'admin']);
    $cfg="<?php\nreturn ".var_export(['db_host'=>$host,'db_name'=>$name,'db_user'=>$dbuser,'db_pass'=>$pass,'base_url'=>''],true).";\n";
    if(file_put_contents(__DIR__.'/config.php',$cfg,LOCK_EX)===false) throw new RuntimeException('Could not write config.php. Temporarily set this folder writable and retry.');
    header('Location: cms.php?page=login&installed=1'); exit;
  } catch(Throwable $e){ $error=$e->getMessage(); }
}
?><!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Install StoryBook CMS</title><link rel="stylesheet" href="assets/install.css"></head><body class="install"><form method="post" class="install-card"><h1>Install StoryBook CMS</h1><p>Enter the MySQL details created in cPanel.</p><?php if($error):?><div class="alert error"><?=htmlspecialchars($error)?></div><?php endif?><div class="grid two"><label>Database host<input name="db_host" value="localhost" required></label><label>Database name<input name="db_name" required></label><label>Database user<input name="db_user" required></label><label>Database password<input type="password" name="db_pass"></label></div><h2>First Admin</h2><label>Admin name<input name="admin_name" required></label><label>Admin email<input type="email" name="admin_email" required></label><label>Admin password<input type="password" name="admin_password" minlength="8" required></label><button>Install CMS</button></form></body></html>
