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

if (!is_file(__DIR__ . '/storage/installed.lock') && current_path() !== '/install.php') {
    redirect('/install.php');
}

$requestPath = current_path();
$queryString = trim((string) ($_SERVER['QUERY_STRING'] ?? ''));
$querySuffix = $queryString !== '' ? '?' . $queryString : '';

if ($requestPath === '/index.php') {
    redirect('/' . $querySuffix, 301);
}
if ($requestPath !== '/' && str_ends_with($requestPath, '/')) {
    redirect(rtrim($requestPath, '/') . $querySuffix, 301);
}

$path = rtrim($requestPath, '/') ?: '/';
$baseParts = parse_url(base_url());
$primaryHost = strtolower((string) ($baseParts['host'] ?? ''));
$primaryScheme = strtolower((string) ($baseParts['scheme'] ?? 'https'));
$requestHost = strtolower(preg_replace('/:\d+$/', '', (string) ($_SERVER['HTTP_HOST'] ?? '')) ?? '');
$requestIsHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
    || strtolower((string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https';
$ampHost = strtolower((string) parse_url((string) setting('amp_base_url', ''), PHP_URL_HOST));
$isAlternateAmpHost = $ampHost !== '' && $ampHost !== $primaryHost && $requestHost === $ampHost;

if (!$isAlternateAmpHost && $primaryHost !== ''
    && ($requestHost !== $primaryHost || ($primaryScheme === 'https' && !$requestIsHttps))) {
    redirect(base_url() . $requestPath . $querySuffix, 301);
}

// Aynı alan adındaki /amp URL'leri yalnız AMP açık ve sayfa türü izinliyse çalışır.
if (str_starts_with($path, '/amp')) {
    $canonicalPath = substr($path, 4) ?: '/';
    if (!amp_path_allowed($canonicalPath)) {
        redirect($canonicalPath . $querySuffix, 301);
    }
    define('NEKRUT_AMP', true);
    $path = $canonicalPath;
} elseif ($isAlternateAmpHost) {
    if (!amp_path_allowed($path)) {
        redirect(base_url() . $path . $querySuffix, 301);
    }
    define('NEKRUT_AMP', true);
}

// Database-managed 301/302 redirects.
if (db_table_exists('redirects')) {
    $stmt = db()->prepare('SELECT id,new_url,status_code FROM redirects WHERE old_path=? AND is_active=1 LIMIT 1');
    $stmt->execute([$path]);
    if ($redirect = $stmt->fetch()) {
        db()->prepare('UPDATE redirects SET hits=hits+1 WHERE id=?')->execute([$redirect['id']]);
        redirect($redirect['new_url'], (int)$redirect['status_code']);
    }
}

if ($path === '/robots.txt') {
    header('Content-Type: text/plain; charset=utf-8');
    echo "User-agent: *\nAllow: /\nDisallow: /admin/\nDisallow: /api/\nDisallow: /install.php\nDisallow: /rezervasyon/basarili/\nDisallow: /rezervasyon/yonet/\nSitemap: " . url('/sitemap.xml') . "\n";
    exit;
}

if (preg_match('~^/sitemap(?:-([a-z]+))?\.xml$~', $path, $m)) {
    require __DIR__ . '/sitemap.php';
    render_sitemap($m[1] ?? 'index');
    exit;
}

$seo = seo_defaults();

function render_not_found_page(array $seo): never
{
    http_response_code(404);
    $seo['title'] = 'Sayfa Bulunamadı | Nekrut Wellness & Spa';
    $seo['description'] = 'Aradığınız sayfa bulunamadı. Nekrut Wellness & Spa ana sayfasına veya wellness deneyimlerine dönebilirsiniz.';
    $seo['robots'] = 'noindex,follow';
    $seo['canonical'] = current_url();
    $seo['amp'] = null;
    render('404', compact('seo'));
    exit;
}

if ($path === '/') {
    $services = db()->query('SELECT * FROM services WHERE is_active=1 ORDER BY is_featured DESC,sort_order,id LIMIT 8')->fetchAll();
    $therapists = db()->query('SELECT id,name,title,nationality,languages,bio,photo FROM therapists WHERE is_active=1 ORDER BY sort_order,id LIMIT 4')->fetchAll();
    $posts = db()->query("SELECT * FROM posts WHERE status='published' ORDER BY published_at DESC,id DESC LIMIT 3")->fetchAll();
    $seo['title'] = 'Nekrut Wellness & Spa | İstanbul Otel Spa Merkezi';
    $seo['description'] = (string) setting('meta_description', site_default_settings()['meta_description']);
    $seo['canonical'] = url('/');
    $seo['amp'] = amp_url('/');
    render(is_amp_request() ? 'amp/home' : 'home', compact('services','therapists','posts','seo'), is_amp_request() ? 'none' : 'default');
    exit;
}

if ($path === '/hizmetler') {
    $services = db()->query('SELECT * FROM services WHERE is_active=1 ORDER BY category,sort_order,id')->fetchAll();
    $seo['title'] = 'Wellness ve Spa Hizmetleri | Nekrut Hotel';
    $seo['description'] = 'Nekrut Hotel bünyesindeki wellness ritüellerini, hamam deneyimlerini ve kişiye özel bakım seçeneklerini inceleyin.';
    $seo['canonical'] = url('/hizmetler');
    $seo['amp'] = amp_url('/hizmetler');
    $seo['breadcrumbs'] = [['name'=>'Ana Sayfa','url'=>url('/')],['name'=>'Hizmetler','url'=>$seo['canonical']]];
    render(is_amp_request() ? 'amp/list' : 'services', compact('services','seo'), is_amp_request() ? 'none' : 'default');
    exit;
}

if (preg_match('~^/hizmet/([a-z0-9-]+)$~', $path, $m)) {
    $stmt = db()->prepare('SELECT * FROM services WHERE slug=? AND is_active=1 LIMIT 1'); $stmt->execute([$m[1]]); $service=$stmt->fetch();
    if (!$service) render_not_found_page($seo);
    $stmt=db()->prepare('SELECT * FROM service_durations WHERE service_id=? AND is_active=1 ORDER BY sort_order,duration_minutes'); $stmt->execute([$service['id']]); $durations=$stmt->fetchAll();
    $relatedStmt=db()->prepare('SELECT * FROM services WHERE category=? AND id<>? AND is_active=1 ORDER BY is_featured DESC,sort_order LIMIT 3'); $relatedStmt->execute([$service['category'],$service['id']]); $related=$relatedStmt->fetchAll();
    $seo['title']=$service['meta_title'] ?: $service['name'].' | Nekrut Wellness & Spa';
    $seo['description']=$service['meta_description'] ?: $service['short_description'];
    $seo['canonical']=url('/hizmet/'.$service['slug']); $seo['amp']=amp_url('/hizmet/'.$service['slug']);
    $seo['image']=url($service['cover_image'] ?: setting('og_image','/assets/img/og-cover.png'));
    $seo['breadcrumbs']=[['name'=>'Ana Sayfa','url'=>url('/')],['name'=>'Hizmetler','url'=>url('/hizmetler')],['name'=>$service['name'],'url'=>$seo['canonical']]];
    $serviceSchema=['@type'=>'Service','@id'=>$seo['canonical'].'#service','url'=>$seo['canonical'],'name'=>$service['name'],'serviceType'=>$service['category'],'description'=>$service['short_description'],'image'=>$seo['image'],'provider'=>['@id'=>base_url().'/#wellness'],'areaServed'=>['@type'=>'City','name'=>'İstanbul'],'potentialAction'=>reserve_action_schema(url('/rezervasyon?service='.$service['id']))];
    if (!empty($service['price_visible'])) {
        $offers=[];
        foreach($durations as $d){
            if($d['price']===null||$d['price']==='')continue;
            $offers[]=['@type'=>'Offer','name'=>$d['label'],'price'=>(float)$d['price'],'priceCurrency'=>'TRY','availability'=>'https://schema.org/InStock','url'=>url('/rezervasyon?service='.$service['id'].'&duration='.$d['id'])];
        }
        if($offers)$serviceSchema['offers']=$offers;
    }
    $seo['schema'][]=$serviceSchema;
    render(is_amp_request() ? 'amp/service' : 'service', compact('service','durations','related','seo'), is_amp_request() ? 'none' : 'default'); exit;
}


if ($path === '/galeri') {
    $gallery=db()->query('SELECT * FROM gallery_items WHERE is_active=1 ORDER BY sort_order,id')->fetchAll();
    $seo['title']='Spa ve Wellness Galerisi | Nekrut Hotel';
    $seo['description']='Nekrut Wellness & Spa bakım odalarını, hamam ve wellness alanlarını galeride inceleyin.';
    $seo['canonical']=url('/galeri');
    $seo['breadcrumbs']=[['name'=>'Ana Sayfa','url'=>url('/')],['name'=>'Galeri','url'=>$seo['canonical']]];
    $seo['schema'][]=['@type'=>'CollectionPage','@id'=>$seo['canonical'].'#collection','name'=>$seo['title'],'hasPart'=>array_map(fn($g)=>['@type'=>'ImageObject','name'=>$g['title'],'contentUrl'=>url($g['image_path']),'caption'=>$g['alt_text']],$gallery)];
    render('gallery',compact('gallery','seo'));exit;
}

if ($path === '/wellness-rehberi') {
    $posts=db()->query("SELECT * FROM posts WHERE status='published' ORDER BY published_at DESC,id DESC")->fetchAll();
    $seo['title']='Wellness Rehberi | Nekrut Wellness & Spa'; $seo['description']='Spa, wellness, hamam ritüelleri ve hizmet seçimi hakkında kurumsal rehber içerikler.'; $seo['canonical']=url('/wellness-rehberi');$seo['amp']=amp_url('/wellness-rehberi');
    $seo['breadcrumbs']=[['name'=>'Ana Sayfa','url'=>url('/')],['name'=>'Wellness Rehberi','url'=>$seo['canonical']]];
    render(is_amp_request() ? 'amp/posts' : 'posts', compact('posts','seo'), is_amp_request() ? 'none' : 'default'); exit;
}

if (preg_match('~^/makale/([a-z0-9-]+)$~',$path,$m)) {
    $stmt=db()->prepare("SELECT p.*,u.name author_name FROM posts p LEFT JOIN users u ON u.id=p.author_id WHERE p.slug=? AND p.status='published' LIMIT 1"); $stmt->execute([$m[1]]); $post=$stmt->fetch();
    if(!$post) render_not_found_page($seo);
    $post['content'] = normalize_article_heading_links((string) $post['content']);
    $bookingService=null; if($post['booking_service_id']){$s=db()->prepare('SELECT * FROM services WHERE id=? AND is_active=1');$s->execute([$post['booking_service_id']]);$bookingService=$s->fetch();}
    $seo['title']=$post['meta_title']?:$post['title'].' | Nekrut Wellness'; $seo['description']=$post['meta_description']?:content_excerpt($post['content'],155); $seo['canonical']=url('/makale/'.$post['slug']); $seo['amp']=amp_url('/makale/'.$post['slug']);
    $seo['image']=url($post['cover_image']?:setting('og_image','/assets/img/og-cover.png')); $seo['type']='article';
    $seo['breadcrumbs']=[['name'=>'Ana Sayfa','url'=>url('/')],['name'=>'Wellness Rehberi','url'=>url('/wellness-rehberi')],['name'=>$post['title'],'url'=>$seo['canonical']]];
    $seo['schema'][]=['@type'=>'BlogPosting','@id'=>$seo['canonical'].'#article','url'=>$seo['canonical'],'headline'=>$post['title'],'description'=>$seo['description'],'datePublished'=>schema_datetime($post['published_at']),'dateModified'=>schema_datetime($post['updated_at']),'image'=>['@type'=>'ImageObject','url'=>$seo['image'],'contentUrl'=>$seo['image']],'author'=>!empty($post['author_name'])?['@type'=>'Person','name'=>$post['author_name']]:['@id'=>base_url().'/#wellness'],'publisher'=>['@id'=>base_url().'/#wellness'],'mainEntityOfPage'=>['@id'=>$seo['canonical'].'#webpage']];
    render(is_amp_request()?'amp/post':'post',compact('post','bookingService','seo'),is_amp_request()?'none':'default');exit;
}

if (preg_match('~^/kurumsal/([a-z0-9-]+)$~',$path,$m)) {
    $stmt=db()->prepare("SELECT * FROM pages WHERE slug=? AND status='published' LIMIT 1");$stmt->execute([$m[1]]);$page=$stmt->fetch();
    if(!$page) render_not_found_page($seo);
    $bookingService=null;if($page['booking_service_id']){$s=db()->prepare('SELECT * FROM services WHERE id=? AND is_active=1');$s->execute([$page['booking_service_id']]);$bookingService=$s->fetch();}
    $seo['title']=$page['meta_title']?:$page['title'].' | Nekrut Wellness';$seo['description']=$page['meta_description']?:content_excerpt($page['content'],155);$seo['canonical']=url('/kurumsal/'.$page['slug']);$seo['amp']=amp_url('/kurumsal/'.$page['slug']);
    $seo['breadcrumbs']=[['name'=>'Ana Sayfa','url'=>url('/')],['name'=>$page['title'],'url'=>$seo['canonical']]];
    render(is_amp_request()?'amp/page':'page',compact('page','bookingService','seo'),is_amp_request()?'none':'default');exit;
}

if ($path === '/rezervasyon') {
    header('Cache-Control: private, no-store, max-age=0');
    $services=db()->query('SELECT id,name,slug,short_description FROM services WHERE is_active=1 ORDER BY sort_order,id')->fetchAll();
    $selectedService=(int)($_GET['service']??0);$selectedDuration=(int)($_GET['duration']??0);
    $seo['title']='Online Spa Rezervasyonu | Nekrut Wellness';$seo['description']='Hizmet, tarih ve saat seçerek Nekrut Wellness & Spa için online rezervasyon oluşturun. Site üzerinden ödeme alınmaz.';$seo['canonical']=url('/rezervasyon');$seo['robots']='noindex,follow';
    render('booking',compact('services','selectedService','selectedDuration','seo'));exit;
}

if (preg_match('~^/rezervasyon/basarili/([a-zA-Z0-9-]+)$~',$path,$m)) {
    header('Cache-Control: private, no-store, max-age=0');
    $stmt=db()->prepare('SELECT r.*,s.name service_name,sd.label duration_label FROM reservations r JOIN services s ON s.id=r.service_id JOIN service_durations sd ON sd.id=r.duration_id WHERE r.reservation_code=? LIMIT 1');$stmt->execute([$m[1]]);$reservation=$stmt->fetch();
    if(!$reservation) render_not_found_page($seo);
    $seo['title']='Rezervasyon Talebiniz Alındı';$seo['robots']='noindex,nofollow';$seo['canonical']=url('/rezervasyon/basarili/'.$m[1]);render('booking-success',compact('reservation','seo'));exit;
}

if (preg_match('~^/rezervasyon/yonet/([a-f0-9]{64})$~',$path,$m)) {
    header('Cache-Control: private, no-store, max-age=0');
    $stmt=db()->prepare('SELECT r.*,s.name service_name,sd.label duration_label FROM reservations r JOIN services s ON s.id=r.service_id JOIN service_durations sd ON sd.id=r.duration_id WHERE r.manage_token=? LIMIT 1');$stmt->execute([$m[1]]);$reservation=$stmt->fetch();
    if(!$reservation) render_not_found_page($seo);
    if(request_is_post()){verify_csrf();if(($reservation['status']??'')==='pending'||($reservation['status']??'')==='confirmed'){db()->prepare("UPDATE reservations SET status='cancelled',updated_at=NOW() WHERE id=?")->execute([$reservation['id']]);flash('success','Rezervasyon iptal edildi.');redirect('/rezervasyon/yonet/'.$m[1]);}}
    $seo['title']='Rezervasyon Yönetimi';$seo['robots']='noindex,nofollow';$seo['canonical']=url('/rezervasyon/yonet/'.$m[1]);render('booking-manage',compact('reservation','seo'));exit;
}

render_not_found_page($seo);
