<?php
declare(strict_types=1);

$root=dirname(__DIR__);
if(is_file($root.'/config.php')){http_response_code(403);exit('Exams.fit is already installed.');}
$errors=[];$done=false;
$checks=[
 'PHP 8.2+'=>PHP_VERSION_ID>=80200,
 'PDO MySQL'=>extension_loaded('pdo_mysql'),
 'Mbstring'=>extension_loaded('mbstring'),
 'ZIP'=>extension_loaded('zip'),
 'Fileinfo'=>extension_loaded('fileinfo'),
 'SimpleXML'=>extension_loaded('simplexml'),
 'OpenSSL'=>extension_loaded('openssl'),
 'Writable storage'=>is_writable($root.'/storage'),
 'Writable uploads'=>is_writable($root.'/uploads'),
 'Writable root'=>is_writable($root),
];

if($_SERVER['REQUEST_METHOD']==='POST'){
 foreach($checks as$name=>$ok)if(!$ok)$errors[]="$name is required.";
 $url=rtrim(trim((string)($_POST['url']??'')),'/');
 $email=filter_var($_POST['email']??'',FILTER_VALIDATE_EMAIL);
 $pass=(string)($_POST['password']??'');
 $adminPath=trim((string)($_POST['admin_path']??'adminji'),'/');
 $host=trim((string)($_POST['host']??'localhost'));
 $port=(int)($_POST['port']??3306);
 $dbName=trim((string)($_POST['name']??''));
 $dbUser=trim((string)($_POST['user']??''));
 $dbPass=(string)($_POST['dbpass']??'');
 if($url!=='https://exams.fit')$errors[]='Website URL must be exactly https://exams.fit';
 if(!$email)$errors[]='A valid admin email is required.';
 if(strlen($pass)<12)$errors[]='Admin password must contain at least 12 characters.';
 if(!preg_match('/^[a-zA-Z0-9_-]{3,40}$/',$adminPath))$errors[]='Invalid admin path.';
 if(!$dbName||!$dbUser)$errors[]='Database name and user are required.';
 if(!$errors){
  try{
   $pdo=new PDO("mysql:host={$host};port={$port};dbname={$dbName};charset=utf8mb4",$dbUser,$dbPass,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,PDO::ATTR_EMULATE_PREPARES=>false,PDO::MYSQL_ATTR_MULTI_STATEMENTS=>true]);
   $existing=(int)$pdo->query("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=".$pdo->quote($dbName))->fetchColumn();
   if($existing>0)throw new RuntimeException('The selected database is not empty. Use a new empty database or the documented upgrade migration.');
   $pdo->exec((string)file_get_contents($root.'/database/schema.sql'));
   $pdo->beginTransaction();
   $pdo->prepare('INSERT INTO admins(email,password,created_at) VALUES(?,?,NOW())')->execute([$email,password_hash($pass,PASSWORD_DEFAULT)]);
   $defaults=[
    'site_name'=>'Exams.fit','site_description'=>'Free USA school, college and exam study resources, practice tests and educational updates.',
    'theme_color'=>'#155eef','google_verification'=>'','bing_verification'=>'','analytics_enabled'=>'1','analytics_retention_days'=>'180',
    'ads_enabled'=>'0','ads_txt'=>'','auto_ads'=>'0','head_code'=>'','footer_code'=>'','robots_extra'=>'',
    'default_appearance'=>'light','contact_email'=>'','content_auto_publish'=>'0','blog_posts_per_page'=>'18','feed_user_agent'=>'Exams.fit Feed Reader/3.1','schema_version'=>'3.0.0'
   ];
   $set=$pdo->prepare('INSERT INTO settings(`key`,value) VALUES(?,?)');foreach($defaults as$k=>$v)$set->execute([$k,$v]);
   $sections=['School Study','College Study','Popular Subjects','Study Notes','Latest Study Blog','Popular Exams','Latest Exam Updates','College Admissions','Upcoming Deadlines','Practice Tests','Full Mock Exams','Daily Quiz','Study PDFs','Video Lessons','Flashcards','Worksheets','Study Tools','Latest Education News','Education Jobs','Recently Added','Recently Updated','Continue Studying','Popular Content'];
   $section=$pdo->prepare('INSERT INTO sections(external_id,title,content_types,layout,item_limit,position,enabled) VALUES(?,?,?,?,?,?,?)');
   foreach($sections as$i=>$title){$enabled=$i<10?1:0;$section->execute(['EF-SECTION-'.str_pad((string)($i+1),3,'0',STR_PAD_LEFT),$title,'[]',$i%3===1?'compact':($i%3===2?'list':'cards'),6,$i+1,$enabled]);}
   $menu=$pdo->prepare('INSERT INTO menus(label,url,location,position,enabled) VALUES(?,?,?,?,1)');foreach([['School','/school'],['College','/college'],['Exams','/exams'],['Practice','/practice-tests'],['Blog','/blog'],['Tools','/tools']] as$i=>$m)$menu->execute([$m[0],$m[1],'header',$i+1]);
   $seed=$pdo->prepare('INSERT INTO content(external_id,type,slug,title,excerpt,body,data,meta_title,meta_description,status,noindex,featured,author,reviewer,content_hash,published_at,reviewed_at,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW(),NOW(),NOW())');
   $pages=[
    ['EF-SYSTEM-ABOUT','about','About Exams.fit','Learn how Exams.fit publishes independent USA educational resources.','<h2>Our purpose</h2><p>Exams.fit provides accessible school, college and exam learning resources for people in the United States. Content is imported through a controlled editorial workflow and reviewed for usefulness, originality and source quality.</p><h2>Independence</h2><p>Exams.fit is not affiliated with exam owners, schools, colleges or government agencies unless a page explicitly states otherwise.</p>'],
    ['EF-SYSTEM-EDITORIAL','editorial-policy','Editorial Policy','Understand the standards used for Exams.fit educational content.','<h2>People-first standards</h2><p>We require original explanations, clear learning objectives, accurate metadata and primary sources for facts that can change.</p><h2>Corrections</h2><p>Readers may report possible errors. Important dates, fees, eligibility and official requirements should always be verified with the linked official organization.</p>'],
    ['EF-SYSTEM-PRIVACY','privacy','Privacy Policy','Learn what limited data Exams.fit records and how preferences are stored.','<h2>Privacy-conscious operation</h2><p>Exams.fit records limited first-party usage events when analytics is enabled. It does not require a student account for ordinary study activity. Reading preferences and saved lessons remain in the browser.</p><h2>External services</h2><p>Advertising and embedded media may use their own technologies when enabled. The administrator must configure legally required consent controls.</p>'],
    ['EF-SYSTEM-CONTACT','contact','Contact Exams.fit','Report a correction, rights concern, accessibility issue or technical problem.','<h2>Contact and corrections</h2><p>Use the configured contact address or the correction form on a content page. Include the page URL and a clear description. Copyright and accessibility concerns receive priority review.</p>']
   ];
   foreach($pages as$p)$seed->execute([$p[0],'article',$p[1],$p[2],$p[3],$p[4],'{}',substr($p[2].' | Exams.fit',0,65),$p[3],'published',0,0,'Exams.fit Editorial Team','Exams.fit Education Reviewer',hash('sha256',$p[4])]);
   $pdo->commit();
   $config=['app_url'=>$url,'timezone'=>'America/New_York','admin_path'=>$adminPath,'db'=>['host'=>$host,'port'=>$port,'name'=>$dbName,'user'=>$dbUser,'pass'=>$dbPass],'cron_token'=>bin2hex(random_bytes(32)),'installed'=>true,'version'=>'3.1.0'];
   if(file_put_contents($root.'/config.php',"<?php\nreturn ".var_export($config,true).";\n",LOCK_EX)===false)throw new RuntimeException('Could not write config.php.');
   file_put_contents($root.'/storage/install.lock',date(DATE_ATOM),LOCK_EX);$done=true;
  }catch(Throwable$e){if(isset($pdo)&&$pdo->inTransaction())$pdo->rollBack();$errors[]='Installation failed: '.$e->getMessage();}
 }
}
?><!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><meta name="robots" content="noindex"><title>Install Exams.fit</title><link rel="stylesheet" href="../assets/app.css?v=3"></head><body><main><section class="install"><h1>Install Exams.fit</h1><?php if($done):?><div class="notice success"><h2>Installation complete</h2><p>Your site and database are ready. The installer is locked.</p><a class="button" href="../<?=htmlspecialchars($adminPath)?>/login">Open admin</a></div><?php else:?><?php foreach($errors as$error):?><p class="notice error"><?=htmlspecialchars($error)?></p><?php endforeach?><div class="checks"><?php foreach($checks as$name=>$ok):?><span class="<?=$ok?'ok':'bad'?>"><?=htmlspecialchars($name)?>: <?=$ok?'Ready':'Check'?></span><?php endforeach?></div><form method="post" class="form"><label>Website URL<input name="url" value="https://exams.fit" readonly required></label><label>Admin path<input name="admin_path" value="<?=htmlspecialchars($_POST['admin_path']??'adminji')?>" pattern="[a-zA-Z0-9_-]+" required></label><label>DB host<input name="host" value="<?=htmlspecialchars($_POST['host']??'localhost')?>" required></label><label>DB port<input name="port" value="<?=htmlspecialchars($_POST['port']??'3306')?>" inputmode="numeric" required></label><label>DB name<input name="name" value="<?=htmlspecialchars($_POST['name']??'')?>" required></label><label>DB user<input name="user" value="<?=htmlspecialchars($_POST['user']??'')?>" required></label><label>DB password<input type="password" name="dbpass"></label><label>Admin email<input type="email" name="email" value="<?=htmlspecialchars($_POST['email']??'')?>" required></label><label>Admin password<input type="password" name="password" minlength="12" required></label><button class="button">Install Exams.fit</button></form><?php endif?></section></main></body></html>
