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

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

    $fields = [];

    // email
    if(Check::post('email')){

        $email = escapeText($_POST['email']);

        if($email !== $usero->data()->email){

            $fields['email'] = $email;
        }
    }

    // username
    if(Check::post('username')){

        $username = escapeText($_POST['username']);

       if($username != $usero->data()->username){

           // check if username is availaible
           $checkQuery = $dbo->query('SELECT id FROM users WHERE username = ?', [$username]);

           if($checkQuery->count()){
             Session::put('error', 'Username is not availaible');
           }else $fields['username'] = $username;
        }

    }

    //password
    if(Check::post('npassword')){

        if($usero->data()->password){

            // if not original password or no hash
            if(!Check::post('opasssword') || !System\Hash::check($_POST['opasssword'], $usero->data()->password)){
                Session::put('error', 'Old password doesn\'t match & required');
                Response::redirect('user');
            }
        }

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

    }

    //password
    if(Check::post('payment')){

        // if not original password or no hash
        if(!Check::post('payment_value')){
            Session::put('error', 'Payment id is required. please provide one');
            Response::redirect('user');
        }

        $fields['payment_value'] = $_POST['payment_value'];

        $paymentQuery = $dbo->query("SELECT id FROM payment WHERE name = ?", [$_POST['payment']]);

        if($paymentQuery->count()){

            $fields['payment_id'] = $paymentQuery->first()->id;
        }

    }
    
    if($usero->isAdmin())
    {
    
        if(Check::post('search_replace_links') || Check::post('header_code')){
            
            $header_code = $_POST['header_code'];
            
            $search_replace_links = $_POST['search_replace_links'];
            
            set_configs([
                'search_replace_links' => $search_replace_links,
                'header_code' => $header_code
            ]);
        }
        
    }


    $dbo->update('users', $usero->data()->id, $fields);

    if(!Session::exists('error'))
        Session::flash('success', 'Settings saved successfully');

    Response::redirect('user');
}

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

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

$view->paymentArray  = $dbo->query("SELECT * FROM payment")->results();

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

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

echo $data;