<?php
/**
 * Author: Kıvanç Ağaoğlu
 * Web: https://kivancagaoglu.com
 * Mail: info@kivancagaoglu.com
 * Skype: kivancagaoglu
 * Github: https://github.com/kivancagaogluu/
 *
 */

require_once __DIR__ . '/functions.php';

require_once __DIR__ . '/simple_html_dom.php';

if ($_POST) {

    $url = $_POST['url'];

    $data = html_entity_decode(curl($url));

    $html = str_get_html($data);

    $title = $html->find('h1', 0)->plaintext;

    $content = $html->find('div.entry-content', 0)->innertext;
    
    if(file_exists(__DIR__ . '/files/' . $title . '.html')){
        
        for( $i = 1; $i <= 999; $i++ ){
            
            $fileName = $title . ' (' . $i . ')' . '.html';
            
            if(!file_exists(__DIR__ . '/files/' . $fileName)){
                file_put_contents(__DIR__ . '/files/' . $fileName, $content);
                break;
            }
            
        }
        
    }else{
        
        file_put_contents(__DIR__ . '/files/' . $title . '.html', $content);
        
    }

    

    header('Content-Type: application/application-json');

    echo json_encode([
        'status' => 'success',
    ]);

    exit;

}