<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Slider_install extends \Ciext\Controller\AbstractInstallController
{

    public function __construct()
    {
        parent::__construct();

        // Set acl module name
        $this->module_config['module_acl_name'] = 'slider';

        // Set title in english
        $this->module_config['module_title'] = 'Sliders';

        // Set module image
        $this->module_config['module_image'] = 'fa fa-object-group';

        // Set actions
        $this->module_config['module_actions'] = [
            // 'acl_action' => 'description'
            'view_slider'   => $this->lang->line('View slides'),
            'edit_slider'   => $this->lang->line('Edit slides'),
            'manage_slider' => $this->lang->line('Settings'),
        ];

        // Set menu items
        $this->module_config['module_menu_items'] = [
//            ['method in admin controller', 'title in menu', 'path to the image. empty - default image', 'acl_action']
            ['index', $this->lang->line('Settings'), '', 'manage_slider'],
        ];

        $this->config->load('slider/config');
    }

    public function install($options = [])
    {
        if (empty($options)) {
            $options = [
                'shemaFile' => dirname(__DIR__) . '/data/install.sql',
            ];
        }

        // Create image folder
        mkdir(trim($this->config->item('slider_image_path'), '/'), 0755, true);

        return parent::install($options);
    }

    public function uninstall($options = [])
    {
        if (empty($options)) {
            $options = [
                'dropTables' => [
                    'slider_slide',
                    'slider',
                ],
            ];
        }

        // Remove files if drop tables
        if ($this->input->post('remove_tables') && !empty($options['dropTables'])) {
            self::delTree(trim($this->config->item('slider_image_path'), '/'));
        }

        return parent::uninstall($options);
    }

    public static function delTree($dir)
    {
        $files = array_diff(scandir($dir), array('.', '..'));
        foreach ($files as $file) {
            (is_dir("$dir/$file")) ? self::delTree("$dir/$file") : unlink("$dir/$file");
        }
        return rmdir($dir);
    }
}
