<?php


if (defined('CAFFITO_CC_LOADED')) return;
define('CAFFITO_CC_LOADED', true);


add_action('wp_enqueue_scripts', function () {
    wp_register_script('caffito-customerclub', false, ['jquery'], null, true);
    wp_enqueue_script('caffito-customerclub');

    $js = <<<JS
jQuery(document).on('submit', '.customer-club-wrapper', function(e){
  e.preventDefault();
  var \$form   = jQuery(this);
  var \$input  = \$form.find('input[name="mobile"]');
  var ajaxUrl  = \$form.data('ajax-url');
  var nonce    = \$form.data('nonce');

  var defaultPH = \$input.attr('data-default-ph') || \$input.attr('placeholder') || '';

  function flashPH(msg) {
    \$input.val('').attr('placeholder', msg);
    \$input.stop(true,true).animate({opacity: 0.6}, 120).animate({opacity: 1}, 180);

    setTimeout(function(){
      \$input.attr('placeholder', defaultPH);
    }, 3000);
  }

  jQuery.ajax({
    url: ajaxUrl,
    type: 'POST',
    dataType: 'json',
    data: {
      action: 'caffito_cc_submit',
      mobile: \$input.val(),
      _ajax_nonce: nonce
    },
    beforeSend: function(){
      \$form.find('button[type="submit"]').prop('disabled', true);
    },
    success: function(res){
      if (res && res.success) {
        flashPH('ثبت شد، ممنون');
      } else {
        var txt = (res && res.data) ? res.data : 'خطا در ثبت. دوباره تلاش کنید.';
        flashPH('' + txt);
      }
    },
    error: function(){
      flashPH('❌ خطای شبکه!');
    },
    complete: function(){

      \$form.find('button[type="submit"]').prop('disabled', false);
    }
  });
});
JS;

    wp_add_inline_script('caffito-customerclub', $js);
});

add_action('wp_ajax_nopriv_caffito_cc_submit', 'caffito_cc_submit');
add_action('wp_ajax_caffito_cc_submit', 'caffito_cc_submit');

if (!function_exists('caffito_cc_submit')) {
    function caffito_cc_submit() {
        check_ajax_referer('caffito_cc_ajax');

        $mobile_raw = isset($_POST['mobile']) ? (string) $_POST['mobile'] : '';
        $mobile     = preg_replace('/[^0-9+]/', '', $mobile_raw);

        if ($mobile === '') {
            wp_send_json_error('از اعداد انگلیسی استفاده کنید');
        }

        $ip = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field($_SERVER['REMOTE_ADDR']) : '0.0.0.0';
        $limit_key = 'caffito_cc_limit_' . md5($mobile . '|' . $ip);
        if (get_transient($limit_key)) {
            wp_send_json_error('لطفاً دیرتر دیگر تلاش کنید');
        }
        set_transient($limit_key, 1, 5 * MINUTE_IN_SECONDS);

        $key     = 'caffito_customerclub_entries';
        $entries = get_option($key);
        if (!is_array($entries)) { $entries = []; }

        $entries[] = [
            'mobile' => $mobile,
            'ip'     => $ip,
            'ua'     => substr(sanitize_text_field($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255),
            'time'   => current_time('mysql'),
        ];

        if (false === get_option($key, false)) {
            add_option($key, $entries, '', 'no');
        } else {
            update_option($key, $entries);
        }

        wp_send_json_success();
    }
}

add_action('admin_init', function () {
    if (!is_admin() || !is_user_logged_in() || !current_user_can('manage_options')) return;
    if (!isset($_GET['page']) || $_GET['page'] !== 'caffito_customerclub') return;
    if (!isset($_GET['export']) || $_GET['export'] != '1') return;

    check_admin_referer('caffito_cc_export');

    $entries = get_option('caffito_customerclub_entries', []);
    if (!is_array($entries)) $entries = [];

    if (ob_get_length()) { @ob_end_clean(); }

    nocache_headers();
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=customerclub-entries-' . date('Ymd-His') . '.csv');

    $out = fopen('php://output', 'w');
    fputcsv($out, ['mobile','ip','user_agent','created_at']);
    foreach ($entries as $row) {
        fputcsv($out, [
            $row['mobile'] ?? '',
            $row['ip']     ?? '',
            $row['ua']     ?? '',
            $row['time']   ?? '',
        ]);
    }
    fclose($out);
    exit;
});


add_action('admin_menu', function () {
    add_menu_page(

        'باشگاه مشتریان',
        'باشگاه مشتریان',
        'manage_options',
        'caffito_customerclub',
        'caffito_customerclub_admin_page',
        'dashicons-groups',
        3.3
    );
});

if (!function_exists('caffito_customerclub_admin_page')) {
    function caffito_customerclub_admin_page() {
        if (!current_user_can('manage_options')) {
            wp_die('دسترسی ندارید.');
        }

        if (isset($_POST['caffito_cc_clear']) && $_POST['caffito_cc_clear'] == '1') {
            check_admin_referer('caffito_cc_clear');
            update_option('caffito_customerclub_entries', []);
            echo '<div class="notice notice-success is-dismissible"><p>لیست پاک شد.</p></div>';
        }

        if (isset($_POST['caffito_cc_delete']) && $_POST['caffito_cc_delete'] == '1' && isset($_POST['delete_key'])) {
            check_admin_referer('caffito_cc_delete');
            $store_key = 'caffito_customerclub_entries';
            $entries_for_delete = get_option($store_key, []);
            if (is_array($entries_for_delete) && array_key_exists($_POST['delete_key'], $entries_for_delete)) {
                unset($entries_for_delete[$_POST['delete_key']]);
                $entries_for_delete = array_values($entries_for_delete);
                update_option($store_key, $entries_for_delete);
                echo '<div class="notice notice-success is-dismissible"><p>ردیف حذف شد.</p></div>';
            } else {
                echo '<div class="notice notice-error is-dismissible"><p>ردیف پیدا نشد.</p></div>';
            }
        }


        $entries = get_option('caffito_customerclub_entries', []);
        if (!is_array($entries)) $entries = [];

        $export_url = wp_nonce_url(
            admin_url('admin.php?page=caffito_customerclub&export=1'),
            'caffito_cc_export'
        );
        ?>
        <div class="wrap">
            <h1>Customer Club</h1>

            <p>
                <a href="<?php echo esc_url($export_url); ?>" class="button button-primary">دانلود CSV</a>
            </p>

            <form method="post" style="margin:12px 0;">
                <?php wp_nonce_field('caffito_cc_clear'); ?>
                <input type="hidden" name="caffito_cc_clear" value="1">
                <button type="submit" class="button button-secondary" onclick="return confirm('لیست پاک شود؟');">پاک‌سازی لیست</button>
            </form>

            <?php if (empty($entries)): ?>
                <p>هنوز شماره‌ای ثبت نشده.</p>
            <?php else: ?>
                <table class="widefat striped">
                    <thead>
                    <tr>
                        <th>موبایل</th>
                        <th>IP</th>
                        <th>User-Agent</th>
                        <th>زمان</th>
                        <th style="width:60px">حذف</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach (array_reverse($entries, true) as $k => $e): ?>
                        <tr>
                            <td><?php echo esc_html($e['mobile'] ?? ''); ?></td>
                            <td><?php echo esc_html($e['ip'] ?? ''); ?></td>
                            <td><?php echo esc_html($e['ua'] ?? ''); ?></td>
                            <td><?php echo esc_html($e['time'] ?? ''); ?></td>
                            <td>
                                <form method="post" onsubmit="return confirm('این ردیف حذف شود؟');" style="display:inline;">
                                    <?php wp_nonce_field('caffito_cc_delete'); ?>
                                    <input type="hidden" name="caffito_cc_delete" value="1">
                                    <input type="hidden" name="delete_key" value="<?php echo esc_attr($k); ?>">
                                    <button type="submit" class="button-link delete" title="حذف این مورد" aria-label="حذف">
                                        <span class="dashicons dashicons-trash"></span>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        <?php
    }
}