<?php

namespace GPLoker\Inc;

use CSF;
use function add_action;
use function add_filter;
use function add_query_arg;
use function admin_url;
use function current_time;
use function error_get_last;
use function get_option;
use function get_post_meta;
use function in_array;
use function is_admin;
use function is_array;
use function print_r;
use function register_shutdown_function;
use function sanitize_text_field;
use function sprintf;
use function strtotime;
use function update_option;
use WP_Post;
use function update_post_meta;

class JobMenu extends Base_Post_Type
{
    private $companies;

    public function __construct()
    {
        parent::__construct([
            'id'            => 'lowongan',
            'title'         => 'Lowongan Kerja',
            'supports'      => ['title', 'editor'],
            'menu_position' => 21,
            'menu_icon'     => 'dashicons-portfolio',
            'show_in_rest'  => false,
            'group'         => [
                [
                    'id'                  => 'location',
                    'title'               => 'Lokasi',
                    'hierarchical'        => true,
                    'show_in_editor_page' => true,
                    'show_admin_column'   => true,
                ],
                [
                    'id'                  => 'loker-category',
                    'title'               => 'Loker Kategori',
                    'hierarchical'        => true,
                    'show_in_editor_page' => true,
                    'show_admin_column'   => true,
                ],
                [
                    'id'                  => 'loker-tags',
                    'title'               => 'Loker Tags',
                    'show_in_editor_page' => true,
                    'show_admin_column'   => true,
                ],

            ]
        ]);

        # popup on single
        add_action('generate_after_footer', [$this, 'applyPopUp']);

        add_action('generate_after_footer', [$this, 'jsonLd']);

        add_action('admin_init', [$this, 'registerNewColumns']);
        $this->metabox();
    }

    public function registerNewColumns()
    {

        add_filter('manage_edit-lowongan_columns', [$this, 'columnNames']);
        add_action('manage_lowongan_posts_custom_column', [$this, 'columnContent'], 10, 2);
        add_filter('manage_edit-lowongan_sortable_columns', [$this, 'columSortable']);

        add_filter('views_edit-lowongan', [$this, 'filterExpired']);

        // handler order expired
        add_filter('posts_orderby', function ($orderby_clause, $query) {
            global $wpdb;
            if (is_admin() && $query->get('post_type') === 'lowongan' && 'valid_through' === $query->get('orderby')) {
                //$orderby_clause = "STR_TO_DATE({$wpdb->postmeta}.meta_value, '%m/%d/%Y') " . strtoupper($query->get('order')) . ", {$wpdb->posts}.post_date DESC";
                
                $orderby_clause = "STR_TO_DATE(CONCAT({$wpdb->postmeta}.meta_value, ' 23:59:59'), '%m/%d/%Y %H:%i:%s') " . strtoupper($query->get('order')) . ", {$wpdb->posts}.post_date DESC";

            }

            return $orderby_clause;
        }, 10, 2);

        add_action('pre_get_posts', function ($query) {
            if (is_admin() && $query->get('post_type') === 'lowongan' && 'valid_through' === $query->get('orderby')) {
                $query->set('meta_key', 'valid_through');
            }
        });

        // handler filter expired
        add_filter('posts_clauses', function ($clauses, $query) {
            global $wpdb;
            if (is_admin() && $query->get('post_type') === 'lowongan' && isset($_GET['filter'])) {

                $current_date     = current_time('Y-m-d');
                $clauses['where'] .= " AND STR_TO_DATE($wpdb->postmeta.meta_value, '%m/%d/%Y') < '{$current_date}'";

                // Menambahkan kondisi join dengan postmeta hanya jika belum ada, untuk menghindari join ganda
                if (strpos($clauses['join'], "$wpdb->postmeta ON") === false) {
                    $clauses['join'] .= " LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id AND $wpdb->postmeta.meta_key = 'valid_through')";
                }
            }

            return $clauses;
        }, 10, 2);

        // sticky jobs
        add_action('post_submitbox_misc_actions', function (WP_Post $post) {
            if ($post->post_type !== 'lowongan') {
                return;
            }

            $isSticky   = get_post_meta($post->ID, 'gplokerpro_is_sticky', true);
            $checked    = '';
            if ( $isSticky === 'on' ) {
                $checked = 'checked';
            }
            ?>
            <div class="misc-pub-section misc-sticky-job">
                <label for="sticky-job">
                    <input type="checkbox" name="sticky-jobs" value="on"
                           id="sticky-job" <?php echo $checked; ?>> Sticky Job
                </label>
            </div>
            <?php
        });

        // sticky job save handler
        add_action('save_post', function ($postId, WP_Post $post) {
            if (isset($_POST['action']) && $_POST['action'] === 'inline-save') {
                return;
            }

            if ($post->post_type === 'lowongan') {
                $sticky     = sanitize_text_field($_POST['sticky-jobs'] ?? 'off');
                update_post_meta($postId, 'gplokerpro_is_sticky', $sticky);
                delete_transient('gplokerpro_sticky_jobs_id');
            }
        }, 10, 2);

        // sticky label handler
        add_filter('display_post_states', function ($post_states, $post) {
            if (is_admin() && $post->post_type == 'lowongan') {
                $is_sticky = get_post_meta($post->ID, 'gplokerpro_is_sticky', true);
                if ($is_sticky == 'on') {
                    $post_states['is_sticky_job'] = 'Sticky'; // Sesuaikan styling sesuai keinginan
                }
            }
            return $post_states;
        }, 10, 2);
    }

    public function columnNames($columns)
    {
        $date = $columns['date'];
        unset($columns['date']);
        $columns['expired_status'] = 'Expired Status';
        $columns['date']           = $date;

        return $columns;
    }

    public function columnContent($column, $post_id)
    {
        if ($column === 'expired_status') {
            $expiredDate = get_post_meta($post_id, 'valid_through', true);
            $today       = current_time('timestamp');

            if (strtotime($expiredDate) >= $today) {
                echo '<span style="color: green;">Aktif</span>';
            } else {
                echo '<span style="color: red;">Expired</span>';
            }

        }
    }

    public function columSortable($columns)
    {
        $columns['expired_status'] = 'valid_through';

        return $columns;
    }

    public function filterExpired($views)
    {
        $views['expired'] = sprintf('<a href="%s">%s</a>', add_query_arg([
            'post_type' => 'lowongan',
            'filter'    => 'expired'
        ], admin_url('edit.php')), 'Expired');

        return $views;
    }

    public function orderSorting($clauses, $query)
    {

        global $wpdb;
        if ( ! is_admin() || ! $query->is_main_query() || $query->get('post_type') !== 'lowongan') {
            return $clauses;
        }

        // Pastikan ini hanya berjalan di backend untuk post type 'lowongan' dan ketika orderby 'valid_through'
        if (is_admin() && $query->is_main_query() && 'valid_through' === $query->get('orderby')) {
            // Mengubah format tanggal dari MM/DD/YYYY menjadi YYYY-MM-DD menggunakan fungsi STR_TO_DATE MySQL
            $clauses['orderby'] = "STR_TO_DATE(" . $wpdb->postmeta . ".meta_value, '%m/%d/%Y') " . $query->get('order');
        }

        return $clauses;
    }

    public function jsonLd()
    {
        if (is_singular('lowongan')) :
            global $post;

            $job        = Job::get($post);
            $title_site = get_bloginfo('name');

            $jsonLd                = [];
            $jsonLd['@context']    = "http://schema.org/";
            $jsonLd["@type"]       = "JobPosting";
            $jsonLd["title"]       = $post->post_title;
            $jsonLd["description"] = strip_tags($post->post_content, '<strong><ul><li><em><h2><h3><h4><h5>');
            $jsonLd["identifier"]  = [
                "@type" => "PropertyValue",
                "name"  => $title_site,
                "value" => $title_site
            ];

            $jsonLd["datePosted"]         = $job->getDatePosted();
            $jsonLd["validThrough"]       = $job->getValidThrough();
            $jsonLd["employmentType"]     = $job->getEmploymentType(); //PART_TIME, CONTRACTOR, TEMPORARY, INTERN, VOLUNTEER, PER_DIEM, FULL_TIME
            $jsonLd["hiringOrganization"] = [
                "@type"  => "Organization",
                "name"   => $job->getCompanyName(),
                "sameAs" => ! empty($job->getCompanyWebsite()) ? $job->getCompanyWebsite() : $job->getCompany()->getCompanyUrl(),
                "logo"   => $job->getCompanyLogo()
            ];

            $jsonLd["jobLocation"] = [
                "address" => [
                    "@type"           => "PostalAddress",
                    "streetAddress"   => $job->getAddress() ? : $job->getCity(),
                    "addressLocality" => $job->getCity(),
                    "addressRegion"   => $job->getProvince(),
                    "postalCode"      => $job->getPostalCode(),
                    "addressCountry"  => "Indonesia"
                ]
            ];

            $jsonLd["baseSalary"] = [
                "@type"    => "MonetaryAmount",
                "currency" => "IDR",
                "value"    => [
                    "@type"    => "QuantitativeValue",
                    "value"    => $job->getSalary(),
                    "unitText" => $job->getSalaryUnit()
                ]
            ];

            echo "<script type='application/ld+json'>" . json_encode($jsonLd, 128) . "</script>";
        endif;
    }

    private function getCompanies()
    {
        if (empty($this->companies)) {
            $posts = get_posts([
                'post_type'      => 'companies',
                'posts_per_page' => -1
            ]);

            foreach ($posts as $post) {
                $this->companies[$post->ID] = $post->post_title;
            }
        }

        return $this->companies;
    }

    public static function employmentTypes()
    {
        return [
            'FULL_TIME'  => 'Tetap',
            'PART_TIME'  => 'Paruh Waktu',
            'PER_DIEM'   => 'Harian',
            'CONTRACTOR' => 'Kontrak',
            'TEMPORARY'  => 'Sementara',
            'INTERN'     => 'Magang',
            'VOLUNTEER'  => 'Sukarela',
            'REMOTE'     => 'Remote',
            'ONSITE'     => 'Onsite',
            'OTHER'      => 'Other',
        ];
    }

    private function metabox()
    {
        if (class_exists('CSF')) {

            $prefix = '_lowongan';

            CSF::createMetabox($prefix, [
                'title'     => 'Attribut Lowongan',
                'post_type' => 'lowongan',
                'data_type' => 'unserialize',
                'context'   => 'advanced',
                'priority'  => 'high',
            ]);

            CSF::createSection($prefix, [
                'fields' => [
                    [
                        'id'    => 'featured_jobs',
                        'type'  => 'switcher',
                        'title' => 'Sematkan Lowongan Ini?',
                        'label' => 'Apakah Menampilkan lowongan ini di featured job?',
                    ],
                    [
                        'id'         => 'company',
                        'type'       => 'select',
                        'chosen'     => true,
                        'options'    => $this->getCompanies(),
                        'title'      => 'Perusahaan',
                        'attributes' => [
                            'required' => 'required',
                        ],
                        'placeholder' => 'Pilih Perusahaan',
                        'default' => 0
                    ],
                    [
                        'id'    => 'valid_through',
                        'type'  => 'date',
                        'title' => 'Batas Lamaran',
                    ],
                    [
                        'id'      => 'employment_type',
                        'type'    => 'select',
                        'options' => self::employmentTypes(),
                        'default' => 'FULL_TIME',
                        'title'   => 'Status',
                    ],

                    [
                        'id'    => 'city',
                        'type'  => 'text',
                        'title' => 'Kabupaten/Kota',
                    ],
                    [
                        'id'    => 'province',
                        'type'  => 'text',
                        'title' => 'Provinsi',
                    ],
                    [
                        'id'    => 'postal_code',
                        'type'  => 'text',
                        'title' => 'Kodepos',
                    ],
                    [
                        'id'      => 'monetary_amount',
                        'type'    => 'number',
                        'title'   => 'Gaji',
                        'default' => 0
                    ],
                    [
                        'id'      => 'salary_label',
                        'type'    => 'text',
                        'title'   => 'Salary Label',
                        'default' => 'Negotiable',
                        'desc'    => 'Akan muncul ketika Gaji 0 atau kosong'
                    ],
                    [
                        'id'      => 'monetary_amount_unit',
                        'type'    => 'select',
                        'options' => [
                            'HOUR'  => 'Per Jam',
                            'WEEK'  => 'Mingguan',
                            'MONTH' => 'Bulanan',
                            'YEAR'  => 'Tahunan',
                        ],
                        'default' => 'MONTH',
                        'title'   => 'Mode Gaji',
                    ],
                    [
                        'id'     => 'link_apply',
                        'type'   => 'group',
                        'title'  => 'Link Apply',
                        'fields' => [
                            [
                                'id'    => 'link_title',
                                'type'  => 'text',
                                'title' => 'Title',
                            ],
                            [
                                'id'    => 'link_content',
                                'type'  => 'text',
                                'title' => 'Link',
                            ],
                        ],
                    ],
                ]
            ]);
        }
    }

    public function applyPopUp()
    {
        if (is_single()) :
            $job = GPLokerGetCurrentJob();

            $popup_regular_title         = GPLokerOption('popup_regular_title', 'Kirim Lamaran');
            $popup_regular_message       = GPLokerOption('popup_regular_message',
                "Bagi anda yang sudah memenuhi persyaratan silahkan lamar melalui link :\n{{LINK_APPLY}}");
            $popup_regular_expired_label = GPLokerOption('popup_regular_expired_label', 'Expired Date :');

            $popup_expired_title        = GPLokerOption('popup_expired_title ', 'Lowongan Ini Sudah Ditutup');
            $popup_expired_message      = GPLokerOption('popup_expired_message',
                "Lowongan kerja <strong>{{JOB_POSITION}} {{COMPANY_NAME}}</strong> sudah ditutup pada tanggal {{EXPIRED_DATE}}, \nsilahkan kembali ke halaman utama untuk melihat info lowongan kerja terbaru.");
            $popup_regular_readon_label = GPLokerOption('popup_regular_readon_label', 'Lihat Lowongan Lainnya');

            $popup_regular_message = GPLokerVaribleDynamic($popup_regular_message);
            $popup_expired_message = GPLokerVaribleDynamic($popup_expired_message);

            ?>
            <div class="popup-lamaran-kerja neon-modal" id="neon-modal">
                <div class="popup-lamaran-kerja-content neon-modal-content">
                    <span class="neon-close">&times;</span>
                    <?php if (empty($job->getValidThrough()) || strtotime($job->getValidThrough()) > time()) : ?>
                        <h4><?php echo $popup_regular_title; ?></h4>
                        <div class="popup-content"><?php echo $popup_regular_message; ?></div>
                        <div class="expire_date_job"><?php echo $popup_regular_expired_label; ?><?php echo $job->getValidThrough('d M Y') ? : '--'; ?></div>
                    <?php else : ?>
                        <div class="expired-loker">
                            <h4><?php echo $popup_expired_title; ?></h4>
                            <div class="popup-content"><?php echo $popup_expired_message; ?></div>
                            <div class="readon-wrap"><a class="readon"
                                                        href="<?php echo home_url('/'); ?>"><?php echo $popup_regular_readon_label; ?></a>
                            </div>
                        </div>

                    <?php endif; ?>
                </div>
            </div>
            <script>
                const modal = document.getElementById("neon-modal");
                const btn = document.getElementById("apply-loker");

                const span = document.getElementsByClassName("neon-close")[0];

                btn.onclick = function () {
                    modal.style.display = "block";
                }

                span.onclick = function () {
                    modal.style.display = "none";
                }
                window.onclick = function (event) {
                    if (event.target === modal) {
                        modal.style.display = "none";
                    }
                }
            </script>
        <?php
        endif;
    }
}

new JobMenu();