<?php
if (!defined('ABSPATH')) exit;

class HK_Setting {

    public function __construct() {
        add_action('admin_menu', [$this, 'add_menu']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_scripts']);
    }

    public function add_menu() {
        add_menu_page(
            'Hallo Ketua Settings',
            'Hallo Ketua',
            'manage_options',
            'hallo-ketua-settings',
            [$this, 'settings_page'],
            'dashicons-businessman',
            30
        );
    }

    public function register_settings() {
        register_setting('hk_settings', 'hk_nama_ketua');
        register_setting('hk_settings', 'hk_ketua_whatsapp');
        register_setting('hk_settings', 'hk_bio');
        register_setting('hk_settings', 'hk_color_primary');
        register_setting('hk_settings', 'hk_color_icon');
        register_setting('hk_settings', 'hk_color_font');
        register_setting('hk_settings', 'hk_color_section_bg');
        register_setting('hk_settings', 'hk_color_button');
        register_setting('hk_settings', 'hk_logo_utama');
        register_setting('hk_settings', 'hk_slide_photos');
        register_setting('hk_settings', 'hk_logos');
        register_setting('hk_settings', 'hk_pengalaman');
        register_setting('hk_settings', 'hk_instagram_url');
        register_setting('hk_settings', 'hk_tiktok_url');
        register_setting('hk_settings', 'hk_home_url');
        register_setting('hk_settings', 'hk_proposal_url');
        register_setting('hk_settings', 'hk_appointment_url');
    }

    public function enqueue_admin_scripts($hook) {
        if ($hook !== 'toplevel_page_hallo-ketua-settings') return;
        wp_enqueue_media();
    }

    public function settings_page() {
        if (isset($_POST['hk_save_settings']) && check_admin_referer('hk_settings_nonce')) {
            update_option('hk_nama_ketua', sanitize_text_field($_POST['hk_nama_ketua'] ?? ''));
            update_option('hk_ketua_whatsapp', sanitize_text_field($_POST['hk_ketua_whatsapp'] ?? ''));
            update_option('hk_bio', sanitize_textarea_field($_POST['hk_bio'] ?? ''));
            update_option('hk_color_primary', sanitize_hex_color($_POST['hk_color_primary'] ?? '#05293c'));
            update_option('hk_color_icon', sanitize_hex_color($_POST['hk_color_icon'] ?? '#80a5b4'));
            update_option('hk_color_font', sanitize_hex_color($_POST['hk_color_font'] ?? '#05293c'));
            update_option('hk_color_section_bg', sanitize_hex_color($_POST['hk_color_section_bg'] ?? '#f8f6f0'));
            update_option('hk_color_button', sanitize_hex_color($_POST['hk_color_button'] ?? '#eaee25'));
            update_option('hk_logo_utama', esc_url_raw($_POST['hk_logo_utama'] ?? ''));
            update_option('hk_slide_photos', array_map('esc_url_raw', $_POST['hk_slide_photos'] ?? []));
            update_option('hk_logos', array_map('esc_url_raw', $_POST['hk_logos'] ?? []));
            update_option('hk_pengalaman', array_map(function($item) {
                return [
                    'tahun' => sanitize_text_field($item['tahun'] ?? ''),
                    'judul' => sanitize_text_field($item['judul'] ?? ''),
                    'lembaga' => sanitize_text_field($item['lembaga'] ?? ''),
                    'deskripsi' => sanitize_textarea_field($item['deskripsi'] ?? '')
                ];
            }, $_POST['hk_pengalaman'] ?? []));
            update_option('hk_instagram_url', esc_url_raw($_POST['hk_instagram_url'] ?? ''));
            update_option('hk_tiktok_url', esc_url_raw($_POST['hk_tiktok_url'] ?? ''));
            update_option('hk_home_url', esc_url_raw($_POST['hk_home_url'] ?? ''));
            update_option('hk_proposal_url', esc_url_raw($_POST['hk_proposal_url'] ?? ''));
            update_option('hk_appointment_url', esc_url_raw($_POST['hk_appointment_url'] ?? ''));

            echo '<div class="notice notice-success"><p>Settings saved!</p></div>';
        }

        $nama = get_option('hk_nama_ketua', '');
        $whatsapp = get_option('hk_ketua_whatsapp', '');
        $bio = get_option('hk_bio', '');
        $color_primary = get_option('hk_color_primary', '#05293c');
        $color_icon = get_option('hk_color_icon', '#80a5b4');
        $color_font = get_option('hk_color_font', '#05293c');
        $color_section_bg = get_option('hk_color_section_bg', '#f8f6f0');
        $color_button = get_option('hk_color_button', '#eaee25');
        $logo_utama = get_option('hk_logo_utama', '');
        $slide_photos = get_option('hk_slide_photos', []);
        $logos = get_option('hk_logos', []);
        $pengalaman = get_option('hk_pengalaman', []);
        $instagram_url = get_option('hk_instagram_url', '');
        $tiktok_url = get_option('hk_tiktok_url', '');
        $home_url = get_option('hk_home_url', home_url('/'));
        $proposal_url = get_option('hk_proposal_url', home_url('/proposal'));
        $appointment_url = get_option('hk_appointment_url', home_url('/janji-temu'));

        ?>
        <div class="wrap">
            <h1>Hallo Ketua Settings</h1>
            <form method="post">
                <?php wp_nonce_field('hk_settings_nonce'); ?>

                <h2>Profil Ketua</h2>
                <table class="form-table">
                    <tr>
                        <th>Nama Ketua</th>
                        <td><input type="text" name="hk_nama_ketua" value="<?php echo esc_attr($nama); ?>" class="regular-text" required></td>
                    </tr>
                    <tr>
                        <th>WhatsApp Ketua</th>
                        <td><input type="text" name="hk_ketua_whatsapp" value="<?php echo esc_attr($whatsapp); ?>" class="regular-text" placeholder="08123456789" required></td>
                    </tr>
                    <tr>
                        <th>Bio Singkat</th>
                        <td><textarea name="hk_bio" rows="5" class="large-text"><?php echo esc_textarea($bio); ?></textarea></td>
                    </tr>
                </table>

                <h2>Warna</h2>
                <table class="form-table">
                    <tr>
                        <th>Primary (Dark Blue)</th>
                        <td><input type="color" name="hk_color_primary" value="<?php echo esc_attr($color_primary); ?>"> <small>#05293c</small></td>
                    </tr>
                    <tr>
                        <th>Icon (Biru Muda)</th>
                        <td><input type="color" name="hk_color_icon" value="<?php echo esc_attr($color_icon); ?>"> <small>#80a5b4</small></td>
                    </tr>
                    <tr>
                        <th>Font Color (Dark Blue)</th>
                        <td><input type="color" name="hk_color_font" value="<?php echo esc_attr($color_font); ?>"> <small>#05293c</small></td>
                    </tr>
                    <tr>
                        <th>Section Background (White Broken)</th>
                        <td><input type="color" name="hk_color_section_bg" value="<?php echo esc_attr($color_section_bg); ?>"> <small>#f8f6f0</small></td>
                    </tr>
                    <tr>
                        <th>Button (Yellow)</th>
                        <td><input type="color" name="hk_color_button" value="<?php echo esc_attr($color_button); ?>"> <small>#eaee25</small></td>
                    </tr>
                </table>

                <h2>Logo & Foto</h2>
                <table class="form-table">
                    <tr>
                        <th>Logo Utama</th>
                        <td>
                            <input type="text" name="hk_logo_utama" id="logo_utama" value="<?php echo esc_attr($logo_utama); ?>" class="regular-text">
                            <button type="button" class="button hk-upload-btn" data-target="logo_utama">Upload</button>
                        </td>
                    </tr>
                    <tr>
                        <th>Slide Foto (Max 15)</th>
                        <td>
                            <div id="slide-photos-container">
                                <?php foreach ($slide_photos as $i => $photo): ?>
                                <div style="margin-bottom:10px;">
                                    <input type="text" name="hk_slide_photos[]" value="<?php echo esc_attr($photo); ?>" class="regular-text">
                                    <button type="button" class="button hk-upload-btn" data-target-array="true">Upload</button>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <button type="button" id="add-slide-photo" class="button">Add Photo</button>
                        </td>
                    </tr>
                    <tr>
                        <th>Logo Perusahaan/Organisasi</th>
                        <td>
                            <div id="logos-container">
                                <?php foreach ($logos as $i => $logo): ?>
                                <div style="margin-bottom:10px;">
                                    <input type="text" name="hk_logos[]" value="<?php echo esc_attr($logo); ?>" class="regular-text">
                                    <button type="button" class="button hk-upload-btn" data-target-array="true">Upload</button>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <button type="button" id="add-logo" class="button">Add Logo</button>
                        </td>
                    </tr>
                </table>

                <h2>Pengalaman</h2>
                <div id="pengalaman-container">
                    <?php foreach ($pengalaman as $i => $exp): ?>
                    <div class="pengalaman-item" style="border:1px solid #ccc; padding:15px; margin-bottom:15px;">
                        <p>
                            <label>Tahun:</label><br>
                            <input type="text" name="hk_pengalaman[<?php echo $i; ?>][tahun]" value="<?php echo esc_attr($exp['tahun']); ?>" class="regular-text">
                        </p>
                        <p>
                            <label>Judul:</label><br>
                            <input type="text" name="hk_pengalaman[<?php echo $i; ?>][judul]" value="<?php echo esc_attr($exp['judul']); ?>" class="regular-text">
                        </p>
                        <p>
                            <label>Lembaga:</label><br>
                            <input type="text" name="hk_pengalaman[<?php echo $i; ?>][lembaga]" value="<?php echo esc_attr($exp['lembaga']); ?>" class="regular-text">
                        </p>
                        <p>
                            <label>Deskripsi:</label><br>
                            <textarea name="hk_pengalaman[<?php echo $i; ?>][deskripsi]" rows="3" class="large-text"><?php echo esc_textarea($exp['deskripsi']); ?></textarea>
                        </p>
                        <button type="button" class="button remove-pengalaman">Remove</button>
                    </div>
                    <?php endforeach; ?>
                </div>
                <button type="button" id="add-pengalaman" class="button">Add Pengalaman</button>

                <h2>Social Media</h2>
                <table class="form-table">
                    <tr>
                        <th>Instagram URL</th>
                        <td><input type="url" name="hk_instagram_url" value="<?php echo esc_attr($instagram_url); ?>" class="regular-text" placeholder="https://instagram.com/username"></td>
                    </tr>
                    <tr>
                        <th>TikTok URL</th>
                        <td><input type="url" name="hk_tiktok_url" value="<?php echo esc_attr($tiktok_url); ?>" class="regular-text" placeholder="https://tiktok.com/@username"></td>
                    </tr>
                </table>

                <h2>Bottom Navigation URLs</h2>
                <table class="form-table">
                    <tr>
                        <th>Beranda URL</th>
                        <td><input type="url" name="hk_home_url" value="<?php echo esc_attr($home_url); ?>" class="regular-text" placeholder="<?php echo home_url('/'); ?>"></td>
                    </tr>
                    <tr>
                        <th>Kirim Proposal URL</th>
                        <td><input type="url" name="hk_proposal_url" value="<?php echo esc_attr($proposal_url); ?>" class="regular-text" placeholder="<?php echo home_url('/proposal'); ?>"></td>
                    </tr>
                    <tr>
                        <th>Janji Temu URL</th>
                        <td><input type="url" name="hk_appointment_url" value="<?php echo esc_attr($appointment_url); ?>" class="regular-text" placeholder="<?php echo home_url('/janji-temu'); ?>"></td>
                    </tr>
                </table>

                <p style="margin-top:30px;">
                    <button type="submit" name="hk_save_settings" class="button button-primary">Save Settings</button>
                </p>
            </form>
        </div>

        <script>
        jQuery(document).ready(function($) {
            var mediaUploader;
            var currentInput;

            $('.hk-upload-btn').on('click', function(e) {
                e.preventDefault();
                var btn = $(this);
                var isArray = btn.data('target-array');

                if (!isArray) {
                    currentInput = $('#' + btn.data('target'));
                } else {
                    currentInput = btn.prev('input');
                }

                if (mediaUploader) {
                    mediaUploader.open();
                    return;
                }

                mediaUploader = wp.media({
                    title: 'Choose Image',
                    button: { text: 'Choose Image' },
                    multiple: false
                });

                mediaUploader.on('select', function() {
                    var attachment = mediaUploader.state().get('selection').first().toJSON();
                    currentInput.val(attachment.url);
                });

                mediaUploader.open();
            });

            $('#add-slide-photo').on('click', function() {
                if ($('#slide-photos-container > div').length >= 15) {
                    alert('Maximum 15 photos');
                    return;
                }
                $('#slide-photos-container').append('<div style="margin-bottom:10px;"><input type="text" name="hk_slide_photos[]" class="regular-text"><button type="button" class="button hk-upload-btn" data-target-array="true">Upload</button></div>');
            });

            $('#add-logo').on('click', function() {
                $('#logos-container').append('<div style="margin-bottom:10px;"><input type="text" name="hk_logos[]" class="regular-text"><button type="button" class="button hk-upload-btn" data-target-array="true">Upload</button></div>');
            });

            var pengalamanIndex = <?php echo count($pengalaman); ?>;
            $('#add-pengalaman').on('click', function() {
                var html = '<div class="pengalaman-item" style="border:1px solid #ccc; padding:15px; margin-bottom:15px;">';
                html += '<p><label>Tahun:</label><br><input type="text" name="hk_pengalaman['+pengalamanIndex+'][tahun]" class="regular-text"></p>';
                html += '<p><label>Judul:</label><br><input type="text" name="hk_pengalaman['+pengalamanIndex+'][judul]" class="regular-text"></p>';
                html += '<p><label>Lembaga:</label><br><input type="text" name="hk_pengalaman['+pengalamanIndex+'][lembaga]" class="regular-text"></p>';
                html += '<p><label>Deskripsi:</label><br><textarea name="hk_pengalaman['+pengalamanIndex+'][deskripsi]" rows="3" class="large-text"></textarea></p>';
                html += '<button type="button" class="button remove-pengalaman">Remove</button></div>';
                $('#pengalaman-container').append(html);
                pengalamanIndex++;
            });

            $(document).on('click', '.remove-pengalaman', function() {
                $(this).closest('.pengalaman-item').remove();
            });
        });
        </script>
        <?php
    }
}
