<?php
use System\Response;
use System\Check;
use System\Cookie;

// View Class Instance
$view = new System\View('view');

$uid = $params['uid'];

// pre request
$requestType = 'get';

/**
 * check for valid link and get data anyway
 */
$checkQuery = "SELECT links.password, 
       links.uid,
       links.user_id,
       links.content, 
       links.title,
       links.is_adsense,
       links.created, 
       links.views,
       users.username
 FROM links
 LEFT JOIN users
 ON links.user_id = users.id
 WHERE links.status = 'active'
 AND links.uid = ?
 LIMIT 1";

$checkDbo = $dbo->query($checkQuery, [$uid]);

if (!$checkDbo->count()) {
    Response::error(404);
}

$link_data = $checkDbo->first();
$isPassword = ($link_data->password)? true : false;

if (Check::type('post')) {

    // not a valid request
    if(!\Volnix\CSRF\CSRF::validate($_POST)) System\Response::redirect('/');

    /* if(!$usero->isLoggedIn()):
       //validate captcha
        $recaptcha = new \ReCaptcha\ReCaptcha(System\Config::google('secret'));
        $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

        if(!$resp->isSuccess()){
          System\Session::flash('error', 'Captcha verification required');
          System\Response::redirect('view/'.$uid);
        }
     endif;*/

    // if passwor then match the decrypt key
    if ($isPassword) {
        if (!Check::post('password')) {
            System\Session::flash('error', 'Decrypt key required');
            System\Response::redirect('view/'.$uid);
        }

        if (!System\Hash::check($_POST['password'], $link_data->password)) {
            System\Session::flash('error', 'Decrypt key doesn\'t match');
            System\Response::redirect('view/'.$uid);
        }
    }

    /**
     * do page views and stuff here
     */
   
    if ($link_data->username && !$usero->isLoggedIn() 
        && strpos($link_data->content, 'linkshub.me') === false) {
        $revenueObj = new System\Revenue;
        $revenueObj->make($uid);
    }

    // if everything is correct
    $requestType = 'post';
}

// include common
include('common.php');


if (Cookie::exists('links')) {
    $cookies = unserialize(Cookie::get('links'));

    if (isset($cookies[md5($uid)])) {
        $requestType = 'post';
    }
}

if (($usero->isLoggedIn() && $link_data->user_id == $usero->data()->id)
        ||$usero->isAdmin()
          || ($requestType == 'get' && $usero->isLoggedIn() && !$isPassword)
      || $link_data->user_id == 35055) {
    $requestType = 'post';
}

$search_replace_links = $view->options['search_replace_links'];

// links mods on the fly
$link_data_array = unserialize($link_data->content);

$content_mods = explode(',', $search_replace_links);

$search_replace_array = [];

foreach($content_mods as $kel){
    $els = explode('|', $kel, 2);
    $search_replace_array[trim($els[0])] = trim($els[1]);
}

// do the changes here
$link_data_array = array_map(function($el) use($search_replace_array){

    foreach($search_replace_array as $replace_key => $replace_value){

        // lets replace the * with regex
        $replace_key = str_replace('*', '[^\/]+', $replace_key);

        $el = preg_replace('/' . $replace_key . '/', $replace_value, $el);
    }

    return $el;

}, $link_data_array);


// put it back
$link_data->content = serialize($link_data_array);

$view->requestType = $requestType;
$view->isPassword  = $isPassword;
$view->link_data = $link_data;


if ($link_data->title) {
    $view->title = ucwords($link_data->title);
} else {
    $view->title = System\Config::meta('view')['title'];
}

$view->meta_desc = System\Config::meta('view')['desc'];
$view->canonicalUrl = System\Uri::full('/view/'.$uid);
$view->noIndex = true;

$view->pageType = 'view';
$data = $view->render();

echo $data;
