<?php
declare(strict_types=1);
require __DIR__ . '/app/bootstrap.php';

$path = request_path();
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
const PP_VERSION = '0.4.0';
function pp_asset(string $path): string { return base_url($path) . '?v=' . rawurlencode(PP_VERSION); }
function pp_no_cache(): void { header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0'); header('Pragma: no-cache'); header('Expires: 0'); }

function require_login(Auth $auth): void { if (!$auth->check()) redirect('/admin/login'); }
function admin_header(string $title, Auth $auth): void {
    $user = $auth->user();
    $current = request_path();
    $contentActive = str_starts_with($current, '/admin/content');
    $nav = static function (string $icon, string $label, string $href, bool $active = false, string $badge = ''): string {
        return '<a class="'.($active?'active':'').'" href="'.e($href).'"><span>'.e($icon).'</span><b>'.e($label).'</b>'.($badge!==''?'<small>'.e($badge).'</small>':'').'</a>';
    };
    echo '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>'.e($title).' — 1ProPress</title><link rel="stylesheet" href="'.e(pp_asset('/assets/css/admin.css')).'"></head><body class="admin-body"><aside class="admin-sidebar"><a class="admin-logo" href="'.e(base_url('/admin')).'"><span class="brand-mark">1P</span><span><strong>1ProPress</strong><small>Core Demo</small></span></a><nav>'
        .$nav('⌂','Dashboard',base_url('/admin'),$current==='/admin')
        .$nav('▣','Pages',base_url('/admin/content'),$contentActive)
        .$nav('✎','Posts',base_url('/admin/content'),false)
        .$nav('▧','Media','#',false,'Soon')
        .$nav('◈','Studio',base_url('/admin/content'),false)
        .$nav('◇','Templates','#',false,'Soon')
        .$nav('◉','Themes','#',false,'Preview')
        .$nav('⌘','Plugins','#',false,'Soon')
        .$nav('▦','Widgets','#',false,'Soon')
        .$nav('♙','Users','#',false,'Soon')
        .$nav('⚙','Settings','#',false,'Soon')
        .$nav('✦','AI Assist','#',false,'Beta')
        .'</nav><div class="sidebar-user"><span>'.e((string)($user['name'] ?? '')).'</span><a href="'.e(base_url('/admin/logout')).'">Log out</a></div></aside><main class="admin-main">';
}
function admin_footer(): void { echo '</main></body></html>'; }

if ($path === '/admin/login') {
    pp_no_cache();
    if ($auth->check()) redirect('/admin');
    $error = '';
    if ($method === 'POST') {
        require_csrf($_POST['_csrf'] ?? null);
        if ($auth->attempt((string)($_POST['email'] ?? ''), (string)($_POST['password'] ?? ''))) redirect('/admin');
        $error = 'Email or password is incorrect.';
    }
    echo '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Client Login — 1ProPress</title><link rel="stylesheet" href="'.e(pp_asset('/assets/css/admin.css')).'"></head><body class="login-page"><main class="login-shell"><section class="login-story"><span class="brand-mark">1P</span><h1>Modern publishing without the weight.</h1><p>Manage content in the backend or edit the live website visually.</p><div class="login-points"><span>Fast PHP/MySQL Core</span><span>Frontend Visual Editing</span><span>Revisions & Rollback</span></div></section><section class="login-card"><span class="admin-kicker">Welcome back</span><h2>Sign in to 1ProPress</h2><p>Choose how you want to edit after login.</p>'.($error?'<div class="notice error">'.e($error).'</div>':'').'<form method="post"><input type="hidden" name="_csrf" value="'.e(csrf_token()).'"><label>Email address<input type="email" name="email" autocomplete="email" required></label><label>Password<input type="password" name="password" autocomplete="current-password" required></label><label class="checkbox"><input type="checkbox" name="remember"> Remember me</label><button class="admin-button primary" type="submit">Sign in</button></form><a class="login-back" href="'.e(base_url('/')).'">← Back to website</a></section></main></body></html>'; exit;
}
if ($path === '/admin/logout') { $auth->logout(); redirect('/'); }

if ($path === '/admin') {
    pp_no_cache();
    require_login($auth); admin_header('Dashboard', $auth);
    $items = $contentRepository->all();
    echo '<div class="admin-top"><div><span class="admin-kicker">Welcome to 1ProPress</span><h1>How would you like to edit?</h1><p>Both options use the same lightweight block content.</p></div><a class="admin-button" href="'.e(base_url('/')).'">View website</a></div><div class="choice-grid"><a class="choice-card featured" href="'.e(base_url('/')).'"><span>Visual</span><h2>Edit Website Visually</h2><p>Open the live website, choose a page and click Edit Visually in the admin bar.</p><b>Open website →</b></a><a class="choice-card" href="'.e(base_url('/admin/content')).'"><span>Backend</span><h2>Manage Website</h2><p>Manage posts, pages, publishing status, SEO details and revisions.</p><b>Manage content →</b></a></div><section class="admin-panel"><div class="panel-heading"><h2>Recent content</h2><a href="'.e(base_url('/admin/content')).'">View all</a></div><div class="content-table">';
    foreach (array_slice($items,0,6) as $item) echo '<div class="content-row"><div><strong>'.e($item['title']).'</strong><small>'.e($item['content_type']).' · '.e($item['status']).'</small></div><div><a href="'.e(base_url('/admin/content/'.$item['id'].'/builder')).'">Edit visually</a><a href="'.e(base_url('/admin/content/'.$item['id'].'/edit')).'">Settings</a></div></div>';
    echo '</div></section>'; admin_footer(); exit;
}

if ($path === '/admin/content') {
    pp_no_cache();
    require_login($auth); admin_header('Posts & Pages', $auth); $items=$contentRepository->all();
    echo '<div class="admin-top"><div><span class="admin-kicker">Content</span><h1>Posts & Pages</h1></div><div><a class="admin-button" href="'.e(base_url('/admin/content/new?type=post')).'">New post</a> <a class="admin-button primary" href="'.e(base_url('/admin/content/new?type=page')).'">New page</a></div></div><section class="admin-panel"><div class="content-table">';
    foreach ($items as $item) echo '<div class="content-row"><div><strong>'.e($item['title']).'</strong><small>/'.e($item['slug']).' · '.e($item['content_type']).' · '.e($item['status']).'</small></div><div><a href="'.e(base_url('/admin/content/'.$item['id'].'/builder')).'">Builder</a><a href="'.e(base_url('/admin/content/'.$item['id'].'/edit')).'">Settings</a><a href="'.e(base_url('/admin/content/'.$item['id'].'/revisions')).'">Revisions</a></div></div>';
    echo '</div></section>'; admin_footer(); exit;
}

if ($path === '/admin/content/new') {
    require_login($auth); $type=($_GET['type']??'page')==='post'?'post':'page';
    $blocks=[['id'=>'block-'.bin2hex(random_bytes(3)),'type'=>'richtext','data'=>['html'=>'<h2>Start writing</h2><p>Click this block in the visual editor.</p>']]];
    $id=$contentRepository->create(['content_type'=>$type,'title'=>'Untitled '.ucfirst($type),'slug'=>'untitled-'.time(),'status'=>'draft','content_json'=>json_encode($blocks),'content_html'=>$renderer->renderBlocks($blocks)],(int)$auth->id());
    redirect('/admin/content/'.$id.'/builder');
}

if (preg_match('#^/admin/content/(\d+)/edit$#',$path,$m)) {
    pp_no_cache();
    require_login($auth); $id=(int)$m[1]; $item=$contentRepository->find($id); if(!$item){http_response_code(404);exit('Not found');}
    if($method==='POST'){require_csrf($_POST['_csrf']??null);$contentRepository->saveRevision($item,(int)$auth->id(),'Before metadata update');$contentRepository->update($id,['title'=>trim((string)$_POST['title']),'slug'=>sanitize_slug((string)$_POST['slug']),'status'=>in_array($_POST['status']??'draft',['draft','review','published'],true)?$_POST['status']:'draft','excerpt'=>trim((string)$_POST['excerpt']),'seo_title'=>trim((string)$_POST['seo_title']),'seo_description'=>trim((string)$_POST['seo_description'])]);flash('success','Content settings saved.');redirect('/admin/content/'.$id.'/edit');}
    admin_header('Edit '.$item['title'],$auth);$notice=flash('success'); echo '<div class="admin-top"><div><span class="admin-kicker">Backend Editing</span><h1>'.e($item['title']).'</h1><p>Manage publishing and SEO here, or open the visual builder.</p></div><a class="admin-button primary" href="'.e(base_url('/admin/content/'.$id.'/builder')).'">Open Visual Builder</a></div>'.($notice?'<div class="notice success">'.e($notice).'</div>':'').'<section class="admin-panel"><form method="post" class="form-grid"><input type="hidden" name="_csrf" value="'.e(csrf_token()).'"><label class="span-2">Title<input name="title" value="'.e($item['title']).'" required></label><label>Slug<input name="slug" value="'.e($item['slug']).'" required></label><label>Status<select name="status"><option value="draft"'.($item['status']==='draft'?' selected':'').'>Draft</option><option value="review"'.($item['status']==='review'?' selected':'').'>Review</option><option value="published"'.($item['status']==='published'?' selected':'').'>Published</option></select></label><label class="span-2">Excerpt<textarea name="excerpt">'.e($item['excerpt']).'</textarea></label><label class="span-2">SEO title<input name="seo_title" value="'.e($item['seo_title']).'"></label><label class="span-2">SEO description<textarea name="seo_description">'.e($item['seo_description']).'</textarea></label><div class="span-2 form-actions"><button class="admin-button primary">Save settings</button><a class="admin-button" href="'.e(base_url('/admin/content/'.$id.'/revisions')).'">View revisions</a></div></form></section>';admin_footer();exit;
}

if (preg_match('#^/admin/content/(\d+)/builder$#',$path,$m)) {
    pp_no_cache();
    require_login($auth);$id=(int)$m[1];$item=$contentRepository->find($id);if(!$item){http_response_code(404);exit('Not found');}$blocks=json_decode($item['content_json'],true)?:[];$builderUser=$auth->user()?:[];
    echo '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>1ProPress Studio — '.e($item['title']).'</title><link rel="stylesheet" href="'.e(pp_asset('/assets/css/core.css')).'"><link rel="stylesheet" href="'.e(pp_asset('/themes/nova/theme.css')).'"><link rel="stylesheet" href="'.e(pp_asset('/assets/css/admin.css')).'"></head><body class="builder-body"><div id="builderApp" data-save-url="'.e(base_url('/api/v1/content/'.$id)).'" data-view-url="'.e(base_url('/'.$item['slug'])).'" data-revisions-url="'.e(base_url('/admin/content/'.$id.'/revisions')).'" data-dashboard-url="'.e(base_url('/admin')).'" data-content-url="'.e(base_url('/admin/content')).'" data-logout-url="'.e(base_url('/admin/logout')).'" data-csrf="'.e(csrf_token()).'" data-title="'.e($item['title']).'" data-slug="'.e($item['slug']).'" data-status="'.e($item['status']).'" data-user-name="'.e((string)($builderUser['name']??'Administrator')).'" data-user-email="'.e((string)($builderUser['email']??'')).'" data-editor-version="'.e(PP_VERSION).'"></div><script>window.__PP_BLOCKS__='.json_encode($blocks,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE).';</script><script src="'.e(pp_asset('/assets/js/editor.js')).'"></script></body></html>';exit;
}

if (preg_match('#^/api/v1/content/(\d+)$#',$path,$m) && $method==='POST') {
    require_login($auth);$id=(int)$m[1];$item=$contentRepository->find($id);if(!$item)json_response(['ok'=>false,'message'=>'Not found'],404);$payload=json_decode(file_get_contents('php://input')?:'{}',true)?:[];if(!verify_csrf($payload['_csrf']??null))json_response(['ok'=>false,'message'=>'Security token expired'],419);$blocks=is_array($payload['blocks']??null)?$payload['blocks']:[];$contentRepository->saveRevision($item,(int)$auth->id(),'Builder save');$contentRepository->update($id,['title'=>trim((string)($payload['title']??$item['title'])),'slug'=>sanitize_slug((string)($payload['slug']??$item['slug'])),'status'=>in_array($payload['status']??'draft',['draft','review','published'],true)?$payload['status']:'draft','content_json'=>json_encode($blocks,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),'content_html'=>$renderer->renderBlocks($blocks)]);json_response(['ok'=>true,'message'=>'Saved','updated_at'=>date(DATE_ATOM)]);
}

if (preg_match('#^/admin/content/(\d+)/revisions$#',$path,$m)) {
    pp_no_cache();
    require_login($auth);$id=(int)$m[1];$item=$contentRepository->find($id);if(!$item){http_response_code(404);exit('Not found');}$revs=$contentRepository->revisions($id);admin_header('Revisions',$auth);echo '<div class="admin-top"><div><span class="admin-kicker">Revision History</span><h1>'.e($item['title']).'</h1><p>Preview or roll back to an earlier saved version.</p></div><a class="admin-button primary" href="'.e(base_url('/admin/content/'.$id.'/builder')).'">Back to Builder</a></div><section class="admin-panel"><div class="content-table">';foreach($revs as $r)echo '<div class="content-row"><div><strong>'.e($r['label']?:'Saved revision').'</strong><small>'.e($r['created_at']).' · '.e($r['user_name']??'User').' · '.e($r['status']).'</small></div><div><a target="_blank" href="'.e(base_url('/admin/revision/'.$r['id'].'/preview')).'">Preview</a><form method="post" action="'.e(base_url('/admin/revision/'.$r['id'].'/restore')).'" onsubmit="return confirm(\'Restore this revision?\')"><input type="hidden" name="_csrf" value="'.e(csrf_token()).'"><button class="link-button">Restore</button></form></div></div>';echo $revs?'':'<p>No revisions yet.</p>';echo '</div></section>';admin_footer();exit;
}
if (preg_match('#^/admin/revision/(\d+)/preview$#',$path,$m)) {require_login($auth);$r=$contentRepository->revision((int)$m[1]);if(!$r){http_response_code(404);exit('Not found');}$blocks=json_decode($r['content_json'],true)?:[];echo $renderer->page($r,$renderer->renderBlocks($blocks),null,true);exit;}
if (preg_match('#^/admin/revision/(\d+)/restore$#',$path,$m)&&$method==='POST'){require_login($auth);require_csrf($_POST['_csrf']??null);$id=$contentRepository->restoreRevision((int)$m[1],(int)$auth->id());redirect('/admin/content/'.$id.'/builder');}

if (preg_match('#^/api/v1/page/([a-z0-9-]+)$#',$path,$m)) {$item=$contentRepository->findPublishedBySlug($m[1]);if(!$item)json_response(['error'=>'Not found'],404);json_response(['id'=>(int)$item['id'],'type'=>$item['content_type'],'title'=>$item['title'],'slug'=>$item['slug'],'excerpt'=>$item['excerpt'],'blocks'=>json_decode($item['content_json'],true)?:[],'html'=>$item['content_html'],'updated_at'=>$item['updated_at']]);}

$slug=trim($path,'/');if($slug==='' ){$homeId=(int)setting($db,'home_content_id',0);$page=$homeId?$contentRepository->find($homeId):$contentRepository->findPublishedBySlug('home');}elseif($slug==='blog'){$page=['id'=>0,'title'=>'Insights','slug'=>'blog','excerpt'=>'Latest posts','seo_title'=>'Insights','seo_description'=>'Latest articles'];$blocks=[['type'=>'blog_list','data'=>['title'=>'Latest insights','limit'=>12]]];echo $renderer->page($page,$renderer->renderBlocks($blocks),$auth->user());exit;}else{$page=$contentRepository->findPublishedBySlug($slug);}
if(!$page){http_response_code(404);$page=['id'=>0,'title'=>'Page not found','slug'=>'404','excerpt'=>'The requested page could not be found.','seo_title'=>'Page not found','seo_description'=>''];$body='<section class="section"><div class="site-shell narrow"><h1>Page not found</h1><p>The page may have moved or no longer exists.</p><a class="button button-primary" href="'.e(base_url('/')).'">Return home</a></div></section>';echo $renderer->page($page,$body,$auth->user());exit;}
$blocks=json_decode($page['content_json'],true)?:[];$body=$page['content_html']?:$renderer->renderBlocks($blocks);echo $renderer->page($page,$body,$auth->user());
