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

$paramType = $params['type'];
$id = $params['id'];

$paramArray = array('links');

if(!in_array($paramType, $paramArray))
    Response::error(404);

if(!$usero->isAdmin())
    $link_query = $dbo->query("SELECT * FROM links WHERE id = ? AND user_id = ?", [$id, $usero->data()->id]);
else
    $link_query = $dbo->query("SELECT * FROM links WHERE id = ?", [$id]);

if(!$link_query->count())
      Response::error(404);

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

$link_data = $link_query->first();

/**
 * If post data
 */
if(Check::type('post')){

    if(!Check::post('links')){
        System\Session::flash('error', 'Please provide valid links.');
        Response::redirect('edit/links/'.$id);
    }
    
    $is_adsense = 0;
    
    if(isset($_POST['is_adsense']) && $_POST['is_adsense']) $is_adsense = 1;

    $content = $_POST['links'];

    if(!$content = matchUrls($content)){
        System\Session::flash('error', 'Please provide valid links.');
       Response::redirect('edit/links/'.$id);
    }

    $fields = array(
        'content' => serialize($content),
        'is_adsense' => $is_adsense,
    );

    if(isset($_POST['password']))
        $fields['password'] = System\Hash::make($_POST['password']);

    $dbo->update('links', $id, $fields);

    System\Session::flash('success', 'Changes successfully saved.');
    Response::redirect('edit/links/'.$id);
}

$content_array = unserialize($link_data->content);
$content_data = '';

foreach ($content_array as $k) {
    
    $content_data .= $k."\r\n";
}


$view->content_data = $content_data;
$view->isPassword = $link_data->password;
$view->isAdsense = $link_data->is_adsense;

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

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

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

echo $data;