<?php
/**
 * Toolconfig Controller
 */
class Toolconfig extends Controller
{
    /**
     * Process
     */
    public function process()
    {    
        $AuthUser       = $this->getVariable("AuthUser");
        $Route          = $this->getVariable("Route");
 
        // Config 
        $Config['nav']  = 'tools';

        // Config  
        if(isset($Route->params->self)) { 
            if(file_exists(PATH.'/view/tool/'.$Route->params->self.'/data.json')) {
                $Data       = file_get_contents(PATH.'/view/tool/'.$Route->params->self.'/data.json');
                $Data       = json_decode($Data,true);
                $Categories = $this->db->from('categories')->all();
            }
            if(isset($_POST['_ACTION']) AND $_POST['_ACTION'] == 'save') {
                $Listings['sort'] = $Data['sort'];
                foreach ($_POST['data'] as $Link) {
                    if($Link['name']) {
                        $Listings['category'][] = [
                            'name'      => $Link['name'],
                            'url'       => Input::cleaner($Link['url']),
                            'category'  => $Link['category']
                        ];  
                    }
                }   
                $JsonData = json_encode($Listings,JSON_UNESCAPED_UNICODE);

                $fp = fopen(PATH.'/view/tool/'.$Route->params->self.'/data.json', 'w+');
                fwrite($fp, $JsonData);
                fclose($fp);
                header("location: ".APP.'/admin/config/'.$Route->params->self);
            }
        }

        if(empty($Data)) {
            header("location: ".APP.'/admin/tools');
        }

        $this->setVariable("Config", $Config);  
        $this->setVariable('Categories',$Categories);
        $this->setVariable('Data',$Data['category']);
        $this->view("toolconfig", "admin");
    }
}