<?php
namespace Datacake\Core\Admin\Crud;

require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
use \WP_List_Table;
use Illuminate\Pagination\Paginator;

class BaseCrud extends WP_List_Table {
    public $entity;
    public $model;
    public $parent_page;
    public $columns = [
        'id'=>'id',
        'name'=>'Nome'
    ];
    public $sortableColumns = [
        'id'=>array( 'id', true ),
        'name'=>array('name', true),
    ];
    public $hiddenColumns = array();
    public $extraColumns = array();
    public $bulkActions = array(    
        'bulk-delete' => 'Remover todos'
    );
    public $info = array();
    public function __construct( $args = array()) {
        $this->info['screen'] = isset( $args['screen'] ) ? $args['screen'] : null;
        parent::__construct( $this->info );
    }
    
    public  function get_columns() {
        return $this->columns;
    }
    public function get_hidden_columns(){
        return $this->hiddenColumns;
    }
    public function get_extra_columns(){
        return $this->extraColumns;
    }
    public function get_sortable_columns() {
        return $this->sortableColumns;
    }
    public function get_bulk_actions() {
        return $this->bulkActions;
    }
    public function column_cb( $item ) {
        return sprintf(
          '<input type="checkbox" name="bulk-delete[]" value="%s" />', $item['id']
        );
    }
    public function no_items() {
        'Sem items.';
    }
    

    public function process_bulk_action() {
        if ( 'bulk-delete' === $this->current_action() ) {
            $nonce = esc_attr( $_REQUEST['_wpnonce'] );
            if ( ! wp_verify_nonce( $nonce,  'bulk-' . $this->_args['plural'] ) ) {
                die( 'Go get a life script kiddies' );
            }
            else {
                $ids = $_POST[$this->current_action()];
                foreach ($ids as $index => $id) {
                    $this->entity::destroy(sanitize_text_field($id));    
                }
                $this->redir_with_message('Removidos com sucesso');
            }
        }
        
    }

    public function column_default( $item, $column_name ) {
        global $wpdb;
        return $item[ $column_name ];
    }
    function column_id( $item ) {
        $delete_url = sanitize_text_field($_GET['page']).'_delete';
        $edit_url = sanitize_text_field($_GET['page']).'_edit';
        $delete_nonce = wp_create_nonce( $this->_args['plural'] );
    
        $title = '<strong>' . $item['id'] . '</strong>';
        $actions = array(
            'edit'=> sprintf( 
                '<a href="?page=%s&id=%s">Editar</a>', 
                $edit_url,
                absint( $item['id'] )
            ),
            'delete' => sprintf(
                '<a href="?page=%s&action=%s&id=%s&_wpnonce=%s">Deletar</a>',
                esc_attr( $_REQUEST['page'] ),
                $delete_url,
                absint( $item['id'] ),
                $delete_nonce
            )
        );
        
        return $title . $this->row_actions( $actions );
    }
    public function get_message(){
        if( !empty($_GET['success']) ){
            return "<div class='notice is-dismissible notice-success'><p>".sanitize_textarea_field($_GET['success'])."</p></div>";
        }elseif (!empty($_GET['error'])) {
            return "<div class='notice is-dismissible notice-error'><p>".sanitize_textarea_field($_GET['error'])."</p></div>";
        }
    
    }
    public function redir_with_message($success='',$error='',$page = null){
        if(!$page){
            $page = $this->parent_page;
        }
        //wp_redirect("/wp-admin/admin.php?page=$page&success=$success&error=$error");
        echo '<script> window.location="admin.php?page=' . $page . '&success=' . $success . '&error='.$error.'"; </script> ';
    }
    public function record_count() {
        return $this->entity::all()->count();
    }
    public function list_all($columns,  $per_page = 20, $page_number = 1 ) {
        
        $page = $this->entity::paginate($per_page,$columns,'page',$page_number);
        
        // The data comes not as array
        $arr = [];
        foreach ($page->items() as $key => $value) {
            $arr[] = $value->toArray();
        }
        return $arr;
    }

    public function prepare_items() {
        
        $columns =   $this->get_columns();
        $columns = array_merge(['cb' => '<input type="checkbox" />'],$columns,$this->get_extra_columns());
        $hidden =   $this->get_hidden_columns();
        $sortable =   $this->get_sortable_columns();
        $this->_column_headers = array($columns, $hidden, $sortable, 'nome');
       
        //$this->_column_headers = $this->get_column_info();
        $this->process_bulk_action();
        
        //$this->_column_headers[0] = $this->get_columns();
        
        $per_page = $this->get_items_per_page( 'per_page', 20 );
        $current_page = $this->get_pagenum();
        $total_items = $this->record_count();
    
        $this->set_pagination_args( array(
            'total_items' => $total_items, 
            'per_page'    => $per_page
        ) );
    
        $this->items = $this->list_all( array_keys($this->columns),$per_page ,$current_page );
        
    }
    public function edit_action($data) {
        // Sanitazing data
        foreach ($data as $key => $value) {
            if($key === 'id'){
                $data[$key] = sanitize_key($value);
            } else {
                $data[$key] = sanitize_text_field($value);
            }
            
        }
        
        if($data['id']){
            // Update
            $item = $this->entity::find($data['id']);
            $item->update($data);
            $item->save();
        }else{
            // Create
            $item = $this->entity::create($data);    
        }
        $this->redir_with_message('Salvo com sucesso');
        return $item;
    }
    public function delete_item($id){
        $entity = $this->entity::find($id);
        $entity->delete();
    }
    public function delete() {
       
        if (isset($_GET['id']) && isset($_GET['_wpnonce'])){
            $id = trim(sanitize_key($_GET['id']) );
            $nonce = trim($_GET['_wpnonce']);
            
            if ($id != null && wp_verify_nonce($nonce,$this->_args['plural'])  ){
                $this->delete_item($id);
                $this->redir_with_message('Removido com sucesso');
            }else{
                $this->redir_with_message('','Erro ao remover');
            }

        }
    }
    public function edit(){
        $item = null;
        if ($_SERVER['REQUEST_METHOD'] == 'POST'){
            $data = $_POST;
            $item = $this->edit_action($data);
            
        }
        if (isset($_GET['id'])){
            $item = $this->entity::find(sanitize_key($_GET['id']));
        }
        echo $this->edit_html($item);
    }
    
    public function list(){
        $edit_page = sanitize_text_field($this->parent_page).'_edit';
        $sync_page = sanitize_text_field($this->parent_page).'_sync';
        $delete_page = sanitize_text_field($this->parent_page).'_delete';
        if(isset($_GET['action'])){
            if($_GET['action'] == $delete_page){
                $this->delete();
            }
        }
        if(isset($_GET['action'])){
            if($_GET['action'] == $sync_page){
                $this->sync();
            }
        }
        ?>
        <div class="wrap">
            <?php echo $this->get_message(); ?>
            <h2><?php echo ucfirst($this->_args['plural']); ?></h2>
            <?php if(method_exists($this, 'sync')): ?>
            <a href="admin.php?page=<?php echo $_GET['page']; ?>&action=<?php echo $sync_page; ?>" class="button action pull"><span class="dashicons dashicons-image-rotate"></span>Sincronizar <?php echo ucfirst($this->_args['plural']); ?></a>
            <?php endif; ?>
            <a href="admin.php?page=<?php echo $edit_page; ?>" class="button action"><span class="dashicons dashicons-insert"></span>Novo(a) <?php echo ucfirst($this->_args['singular']); ?></a>
            <div id="poststuff">
                <div id="post-body" class="metabox-holder columns-2">
                    <div id="post-body-content">
                        <div class="meta-box-sortables ui-sortable">
                            <form method="post">
                                <?php
                                $this->prepare_items();
                                $this->display();
                                ?>
                            </form>
                        </div>
                    </div>
                </div>
                <br class="clear">
            </div>
        </div>
        <?php
        
    }
}