<?php

$title = isset($_GET['title']) ? $_GET['title'] : "India";

$title = urldecode($title);
$title = str_replace("+"," ",$title);
$title = str_replace(" ","_",$title);

function fetchWiki($url){

$opts = [
"http"=>[
"method"=>"GET",
"header"=>"User-Agent: Bharatpedia/1.0\r\n"
]
];

$context = stream_context_create($opts);

return file_get_contents($url,false,$context);

}

$api="https://en.wikipedia.org/api/rest_v1/page/mobile-html/".$title;

$html=fetchWiki($api);

if(!$html){
echo "Article not found";
exit;
}

libxml_use_internal_errors(true);

$dom=new DOMDocument();
$dom->loadHTML($html);

$xpath=new DOMXPath($dom);

/* remove infobox */

foreach($xpath->query('//table[contains(@class,"infobox") or contains(@class,"sidebar")]') as $node){
$node->parentNode->removeChild($node);
}


/* remove maintenance boxes */

foreach($xpath->query('//table[contains(@class,"ambox")]') as $node){
$node->parentNode->removeChild($node);
}

/* remove navboxes */

foreach($xpath->query('//table[contains(@class,"navbox")]') as $node){
$node->parentNode->removeChild($node);
}

foreach($xpath->query('//style') as $node){
    $node->parentNode->removeChild($node);
}
/* extract images */

$images=[];

foreach($xpath->query('//img') as $img){

$src=$img->getAttribute("src");

if(strpos($src,"//")===0){
$src="https:".$src;
}

if(!in_array($src,$images)){
$images[]=$src;
}

}

/* build toc */

$toc=[];

foreach($xpath->query('//h2|//h3') as $h){

$text=trim($h->textContent);

$id=strtolower(preg_replace("/[^a-zA-Z0-9]+/","-",$text));

$h->setAttribute("id",$id);

$toc[]=[
"title"=>$text,
"id"=>$id
];

}

$content=$dom->saveHTML();

?>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title><?php echo str_replace("_"," ",$title); ?> - Bharatpedia</title>

<link rel="stylesheet" href="/style.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>

<body>
<div class="site-notice">
Bharatpedia is currently in <strong>read-only mode</strong> due to maintenance.
</div>
<header class="topbar">

<div class="logo">Bharatpedia</div>

<form class="search" id="searchForm">
    <input type="text" id="searchInput" placeholder="Search Bharatpedia" autocomplete="off">
    <div id="searchResults" class="search-results"></div>
</form>

<div class="login">Login</div>

</header>

<nav class="subnav">

<a href="/wiki/Category:Politics_of_India">Politics</a>

<a href="/wiki/Category:Indian_politicians">Politicians</a>

<a href="/wiki/Category:Indian_actors">Actors</a>

<a href="/wiki/Category:Indian_film_actors">Cinema</a>

<a href="/wiki/Category:Indian_biographies">Biographies</a>

<a href="/wiki/Category:History_of_India">History</a>

<a href="/wiki/Category:Culture_of_India">Culture</a>

</nav>

<div class="container">


<main class="article">

<h1>Bharatpedia</h1>

<div class="shortdesc">
Encyclopedia article
</div>



</main>

</div>

<script src="/script.js"></script>

</body>

</html>