<?php
/**
 * @package web-livedraw
 * @since 1.0.0
 */

class Exito_System extends Exito_Post
{
    function __construct()
    {
        //
    }

    function check_page( $slug = null )
    {
        if ( $slug != null ) {
            return get_page_by_path( $slug );
        }
    }

    function list_pasaran()
    {
        $pasaran = get_option( 'pasaran' );

        return ( $pasaran == null ) ? null : (array)$pasaran;
    }

    function get_bukti_jp()
    {
        global $paged;
        
        $list_bukti_jp = new WP_Query([ 'post_type' => 'bukti_jp', 'posts_per_page' => 20, 'nopaging' => false, 'paged' => $paged, 'post_status' => 'publish' ]);

        return $list_bukti_jp;
    }

    function get_bukti_jp_short( $post_id )
    {
        $numb = 0;
        $data = [];
        $list = new WP_Query([ 'post_type' => 'bukti_jp', 'posts_per_page' => -1, 'post_status' => 'publish' ]);

        if ( $list->have_posts() ) {
            while ( $list->have_posts() ) {
                $list->the_post();

                if ( get_the_ID() == intval( $post_id ) ) {
                    //skipped
                } else {
                    $data[$numb] = (object)[ 'ID' => intval( get_the_ID() ) ];

                    $numb++;
                }
            }
        }

        shuffle( $data );

        return [ $data[0], $data[1] ];
    }
    
    function get_pasaran_result()
    {
        $listing = [];
        $outputs = [];
        $halaman = get_pages([ 'post_type' => 'page', 'meta_key' => '_wp_page_template', 'meta_value' => 'page-result.php', 'sort_column' => 'menu_order', 'sort_order' => 'ASC' ]);
        $pasaran = get_terms([ 'taxonomy' => 'pasaran', 'hide_empty' => false ]);
    
        foreach ( $halaman as $data ) {
            $link = get_post_meta( $data->ID, 'link-scrape', true );
            $listing[$link] = $data;
        }

        foreach ( $pasaran as $data ) {
            $keys = get_term_meta( $data->term_id, 'sort-order', true );
            $outputs[$keys] = $listing[$data->slug];
        }
        
        ksort( $outputs );

        return $outputs;
    }

    function get_pasaran_prediksi( $limit = null )
    {
        global $paged;

        $cats_prediksi = get_category_by_slug( 'prediksi-togel' );
        $total_pasaran = ( $limit != null ) ? $limit : count( get_categories([ 'parent' => $cats_prediksi->term_id ]) );
        $list_prediksi = new WP_Query([ 'post_type' => 'post', 'posts_per_page' => $total_pasaran, 'nopaging' => false, 'paged' => $paged, 'tax_query' => [ [ 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => $cats_prediksi->term_id ] ] ]);
        
        return $list_prediksi;
    }

    function get_pasaran_syair( $limit = null )
    {
        global $paged;

        $cats_syair    = get_category_by_slug( 'syair-togel' );
        $total_pasaran = ( $limit != null ) ? $limit : count( get_categories([ 'parent' => $cats_syair->term_id ]) );
        $list_prediksi = new WP_Query([ 'post_type' => 'post', 'posts_per_page' => $total_pasaran, 'nopaging' => false, 'paged' => $paged, 'tax_query' => [ [ 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => $cats_syair->term_id ] ] ]);
        
        return $list_prediksi;
    }

    function get_pasaran_halaman( $type = 'livedraw' )
    {
        $listing = [];
        $outputs = [];
        $halaman = get_pages([ 'post_type' => 'page', 'meta_key' => '_wp_page_template', 'meta_value' => 'page-' . $type . '.php', 'sort_column' => 'menu_order', 'sort_order' => 'ASC' ]);
        $pasaran = get_terms([ 'taxonomy' => 'pasaran', 'hide_empty' => false ]);
    
        foreach ( $halaman as $data ) {
            $link = get_post_meta( $data->ID, 'link-scrape', true );
            $listing[$link] = $data;
        }

        foreach ( $pasaran as $data ) {
            $keys = get_term_meta( $data->term_id, 'sort-order', true );
            $outputs[$keys] = $listing[$data->slug];
        }
        
        asort( $outputs );

        return $outputs;
    }

    function get_livedraw( $pasaran = 'hongkong' )
    {
        $file_path = get_template_directory() . '/functions/page-' . $pasaran . '.php';

        if ( file_exists( $file_path ) ) {
            require_once $file_path;
            return scrape_livedraw();
        } else {
            return [];
        }
    }

    function get_history( $pasaran = 'hongkong' )
    {
        $file_path = get_stylesheet_directory() . '/functions/page-' . $pasaran . '.php';

        if ( file_exists( $file_path ) ) {
            require_once $file_path;

            if ( $code != 'p0000' ) {
                return $this->scrape_history( $code );
            }
        }
        
        $list = [];

        for ( $i = 0; $i <= 5; $i++ ) {
            $list[] = [
                'periode' => '-',
                'tanggal' => date_i18n( 'd M Y', strtotime( '-'.$i.'days' ) ),
                'result'  => '0000',
                'hari'    => date_i18n( 'l', strtotime( '-'.$i.'days' ) ),
            ];
        }

        return $list;
    }

    function scrape_history( $code = 'm17' )
    {
        $list = [];
        $curl = curl_init();
        curl_setopt_array( $curl, [
            CURLOPT_URL            => 'https://www.civictoto.org/load_top10_result.php',
            CURLOPT_COOKIE         => 'PHPSESSID=gv0cpgujm5t809hi64dg1u7pf2;',
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => [ 'sar' => $code ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_SSL_VERIFYPEER => false,
        ] );
        session_write_close();
        $data = curl_exec( $curl );
        curl_close( $curl );

        foreach ( (array)json_decode( $data ) as $item ) {
            $list[] = [
                'periode' => $item->periode,
                'result'  => $item->angka,
                'tanggal' => date_i18n( 'd M Y', strtotime( $item->tanggal ) ),
                'hari'    => date_i18n( 'l', strtotime( $item->tanggal ) ),
                'date'    => date_i18n( 'd/m/Y', strtotime( $item->tanggal ) ),
            ];
        }

        return $list;
    }
    
    function scrape_curl( $url = 'https://app.pool.dev/wp-admin/admin-ajax.php', $fields = 'action=exito_data_api&exito_key=lottery', $use_post = true )
    {
        $list = [];
        $curl = curl_init();
        curl_setopt_array( $curl, [
            CURLOPT_URL            => $url,
            CURLOPT_COOKIE         => 'PHPSESSID=gv0cpgujm5t809hi64dg1u7pf2;',
            CURLOPT_POST           => $use_post,
            CURLOPT_POSTFIELDS     => $fields,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_SSL_VERIFYPEER => false,
        ] );
        session_write_close();
        $json = ($use_post == true) ? json_decode( curl_exec( $curl ), true ) : curl_exec( $curl );
        curl_close( $curl );

        foreach ( (array)$json as $item ) { $list[] = $item; }

        return ( $use_post == true ) ? $list : $json;
    }

    function scrape_formatting( $json = [], $index = 0 )
    {
        $data = [];
        $pool = $json[$index];
        $list = ( $pool['is_live'] == true ) ? $pool['livedraw'] : $pool['lastdraw'];
        $inl1 = intval( count( $list['starter'] ) );
        $inl2 = intval( count( $list['consolation'] ) );
        $time_menit = 0;
        $time_begin = $pool['time_begin'];
        $time_close = $pool['time_close'];
    
        $data['tanggal'] = date_i18n( 'd M Y', strtotime( $list['date'] ) );
        $data['prize_1'] = $this->scrape_timming( $pool['is_live'], $time_begin, $time_close, $time_menit, $list['main'][1]['digits'] );
        $data['prize_2'] = $this->scrape_timming( $pool['is_live'], $time_begin, $time_close, $time_menit, $list['main'][2]['digits'] );
        $data['prize_3'] = $this->scrape_timming( $pool['is_live'], $time_begin, $time_close, $time_menit, $list['main'][3]['digits'] );
    
        $lst1 = 1;
        foreach ( $list['starter'] as $key => $val ) {
            $nKey = ( $lst1 > ( ( $inl1 > 5 ) ? $inl1 / 2 : $inl1 ) ) ? 'prize_5' : 'prize_4';
            $data[$nKey][$key] = $this->scrape_timming( $pool['is_live'], $time_begin, $time_close, $time_menit, $val['digits'] );
            $lst1++;
        }
    
        $lst2 = 1;
        foreach ( $list['consolation'] as $key => $val ) {
            $nKey = ( $lst2 > ( ( $inl2 > 5 ) ? $inl2 / 2 : $inl2 ) ) ? 'prize_7' : 'prize_6';
            $data[$nKey][$key] = $this->scrape_timming( $pool['is_live'], $time_begin, $time_close, $time_menit, $val['digits'] );
            $lst2++;
        }
    
        return $data;
    }

    function scrape_timming( $live = false, $begin = '00:00:00', $close = '00:15:00', &$minutes = 0, $number = '-' )
    {
        $time_today = strtotime( date_i18n( "Y-m-d H:i:s" ) );
        $time_begin = strtotime( date_i18n( "Y-m-d {$begin}" ) );
        $time_close = strtotime( date_i18n( "Y-m-d {$close}" ) . "-{$minutes} minutes" );
        $output     = ( $live == true && $time_today > $time_begin && $time_today < $time_close ) ? '-' : $number;
        $minutes   += ( $minutes <= 4 ) ? 2 : 1;
    
        return $output;
    }

    function generate_page( $type = 'result', $prefix = null, $title = null )
    {
        if ( $prefix != null && $title != null && $this->check_page( sanitize_title( $prefix . ' ' . $title ) ) == null ) {
            $post_txt = $prefix . ' ' . $title;
            $post_new = wp_insert_post([
                'post_type'      => 'page',
                'post_title'     => $post_txt,
                'post_status'    => 'publish',
                'post_date'      => date( 'Y-m-d H:i:s' ),
                'post_name'      => sanitize_title( $post_txt ),
                'post_content'   => '',
                'post_author'    => 1,
                'ping_status'    => 'closed',
                'comment_status' => 'closed',
                'page_template'  => 'page-' . $type . '.php',
            ]);
            
            add_post_meta( $post_new, 'link-scrape', sanitize_title( $title ), true );
            
            $term_objs = get_term_by( 'slug', sanitize_title( $title ), 'pasaran' );
            
            wp_set_object_terms( $post_new, $term_objs->term_id, 'pasaran' );
        }
    }

    function update_page( $title = '', $order = 0 )
    {
        $old_page = get_page_by_path( sanitize_title( $title ) );
        if ( $old_page != null ) {
            wp_update_post( [ 'ID' => $old_page->ID, 'menu_order' => $order ] );
        }
    }

    function generate_category( $title = null )
    {
        if ( $title == null ) { return false; }

        $parent_id = 0;
        $category_parent = get_category_by_slug( 'prediksi-togel' );

        if ( $category_parent == null ) {
            $parent_id = wp_insert_term( 'Prediksi Togel', 'category', 'prediksi-togel' )['term_id'];
        } else {
            $parent_id = $category_parent->term_id;
        }

        $category_name  = 'Prediksi Togel ' . $title;
        $category_data  = [ 'slug' => sanitize_title( $category_name ), 'parent' => $parent_id ];
        if ( category_exists( sanitize_title( $category_name ) ) ) {
            $child_id = get_category_by_slug( sanitize_title( $category_name ) )->term_id;
        } else {
            $child_id = wp_insert_term( $category_name, 'category', $category_data )['term_id'];
        }

        if ( !post_exists( sanitize_title( 'Contoh ' . $category_name ), '', '', '' ) ) {
            wp_insert_post( [
                'post_type'      => 'post',
                'post_title'     => 'Contoh ' . $category_name,
                'post_status'    => 'contoh',
                'post_date'      => '2020-01-01 00:01:00',
                'post_name'      => sanitize_title( 'Contoh ' . $category_name ),
                'post_content'   => '',
                'post_author'    => 1,
                'ping_status'    => 'closed',
                'comment_status' => 'closed',
                'post_category'  => [ $parent_id, $child_id ],
            ] );
        }
    }

    function generate_autopost( $category_name = 'prediksi-togel', $date = '01-01-2020', $is_prediksi = true )
    {
        $data = get_category_by_slug( $category_name );
        $list = get_categories([ 'parent' => $data->term_id, 'hide_empty' => false ]);

        foreach ($list as $item) {
            if ( $item->slug == $category_name . '-singapore' ) {
                if ( date_i18n( 'l', strtotime( $date . '+1days' ) ) != 'Selasa' || date_i18n( 'l', strtotime( $date . '+1days' ) ) != 'Jumat' ) {
                    $this->generate_post( $date, $category_name, $item->slug, $is_prediksi );
                }
            } elseif ( $item->slug == $category_name . '-singapore-night' ) {
                if ( date_i18n( 'l', strtotime( $date . '+1days' ) ) != 'Selasa' || date_i18n( 'l', strtotime( $date . '+1days' ) ) != 'Jumat' ) {
                    $this->generate_post( $date, $category_name, $item->slug, $is_prediksi );
                }
            } elseif ( $item->slug == $category_name . '-singapore-45' ) {
                if ( date_i18n( 'l', strtotime( $date . '+1days' ) ) != 'Senin' || date_i18n( 'l', strtotime( $date . '+1days' ) ) != 'Kamis' ) {
                    $this->generate_post( $date, $category_name, $item->slug, $is_prediksi );
                }
            } elseif ( $item->slug == $category_name . '-dewata-pools' ) {
                if ( date_i18n( 'l', strtotime( $date . '+1days' ) ) != 'Kamis' ) {
                    $this->generate_post( $date, $category_name, $item->slug, $is_prediksi );
                }
            } else {
                $this->generate_post( $date, $category_name, $item->slug, $is_prediksi );
            }
        }
    }

    function generate_page_pasaran( $title = null )
    {
        $this->generate_page( 'livedraw', 'Live Draw',     $title );
        $this->generate_page( 'result',   'Data Keluaran', $title );
        $this->generate_page( 'paito',    'Paito Warna',   $title );
        $this->generate_category( $title );
    }

    function update_page_pasaran( $title = null, $order = 0 )
    {
        $this->update_page( 'Live Draw ' . $title, $order );
        $this->update_page( 'Data Keluaran ' . $title, $order );
        $this->update_page( 'Paito Warna ' . $title, $order );
    }

    function generate_prediksi_all()
    {
        $begin     = new DateTime( date('d-m-Y') );
        $end       = new DateTime( date('d-m-Y') ); $end->modify('+1 day');
        $interval  = new DateInterval( 'P1D' );
        $daterange = new DatePeriod( $begin, $interval, $end );
    
        foreach ( $daterange as $range ) {
            $date = $range->format('d-m-Y');
            $this->generate_autopost( 'prediksi-togel', $date, true );
        }
    }

    function generate_prediksi_slot_all()
    {
        $begin     = new DateTime( date('d-m-Y') );
        $end       = new DateTime( date('d-m-Y') ); $end->modify('+1 day');
        $interval  = new DateInterval( 'P1D' );
        $daterange = new DatePeriod( $begin, $interval, $end );
    
        foreach ( $daterange as $range ) {
            $date = $range->format('d-m-Y');
            $this->generate_autopost( 'prediksi-slot', $date, false );
        }
    }

    function generate_syair_all()
    {
        $begin     = new DateTime( date('d-m-Y') );
        $end       = new DateTime( date('d-m-Y') ); $end->modify('+1 day');
        $interval  = new DateInterval( 'P1D' );
        $daterange = new DatePeriod( $begin, $interval, $end );
    
        foreach ( $daterange as $range ) {
            $date = $range->format('d-m-Y');
            $this->generate_autopost( 'syair-togel', $date, false );
        }
    }

    function generate_rtp_image_all()
    {
        ini_set("user_agent", "Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0");

        if ( !file_exists( ABSPATH . '/assets' ) ) {
            mkdir( ABSPATH . '/assets', 0777, true );
        }

        foreach ( (array)$this->get_rtp_providers() as $provider ) {
            $html = file_get_html( $provider['link'] );

            if ( !file_exists( ABSPATH . '/' . $provider['imgs'] ) ) {
                $provider_img = file_get_contents( 'https://188.166.187.216/' . $provider['imgs'] );
                file_put_contents( ABSPATH . '/' . $provider['imgs'], $provider_img );
            }
            
            foreach ( $html->find( 'div[class="content"]', 0 )->find('div[class="card"]') as $game ) {
                $name = explode( '/', $game->find( 'img', 0 )->src );
                $file = ABSPATH . '/' . $game->find( 'img', 0 )->src;

                if ( !file_exists( ABSPATH . '/assets/' . $name[1] ) ) {
                    mkdir( ABSPATH . '/assets/' . $name[1], 0777, true );
                }

                if ( !file_exists( $file ) ) {
                    $image = file_get_contents( 'https://188.166.187.216/' . $game->find( 'img', 0 )->src );
                    file_put_contents( $file, $image );
                }
            }
        }

        return $data;
    }
}
