<?php

if (!defined('ABSPATH')) { exit; }

if ( ! class_exists( 'AIEO_Loyalty_Connection', false )
     && ( strpos( __DIR__, 'ai-eshop-optimizer-runtime' ) !== false
          || ! in_array( 'ai-eshop-optimizer-runtime/ai-eshop-optimizer-runtime.php', (array) get_option( 'active_plugins', array() ), true ) ) ) {

class AIEO_Loyalty_Connection {

    const SHORTCODE = 'aieo_loyalty_information';
    const ENDPOINT  = 'aieo-loyalty';

    public function __construct() {
        add_shortcode(self::SHORTCODE, array($this, 'shortcode'));
        add_action('init', array($this, 'add_endpoint'));
        add_filter('query_vars', array($this, 'query_vars'), 0);
        add_filter('woocommerce_account_menu_items', array($this, 'menu_items'));
        add_action('woocommerce_account_' . self::ENDPOINT . '_endpoint', array($this, 'endpoint_content'));
    }

    

    public static function loyalty_role() {
        $r = (string) (class_exists('AIEO_DMM_Settings') ? AIEO_DMM_Settings::get('loyalty_role', '') : '');
        if ($r === '') { $r = (string) get_option('s1erp_prod_woo_loyalty_role', ''); }
        return $r !== '' ? $r : 'customer_loyalty';
    }
    public static function customers_table() {
        $t = (string) (class_exists('AIEO_DMM_Settings') ? AIEO_DMM_Settings::get('loyalty_customers_table', '') : '');
        if ($t === '') { $t = (string) get_option('s1erp_site_customers_table', ''); }
        return $t;
    }
    public static function show_in_my_account() {
        return class_exists('AIEO_DMM_Settings') && (bool) AIEO_DMM_Settings::get('loyalty_my_account', false);
    }
    public static function my_account_label() {
        $l = (string) (class_exists('AIEO_DMM_Settings') ? AIEO_DMM_Settings::get('loyalty_my_account_label', '') : '');
        return $l !== '' ? $l : __('Bonus Card', 'ai-eshop-optimizer');
    }

    

    public function add_endpoint() {
        if (self::show_in_my_account()) { add_rewrite_endpoint(self::ENDPOINT, EP_ROOT | EP_PAGES); }
    }
    public function query_vars($vars) {
        if (self::show_in_my_account()) { $vars[] = self::ENDPOINT; }
        return $vars;
    }
    public function menu_items($items) {
        if (!self::show_in_my_account()) { return $items; }
        $logout = isset($items['customer-logout']) ? $items['customer-logout'] : null;
        if ($logout !== null) { unset($items['customer-logout']); }
        $items[self::ENDPOINT] = self::my_account_label();
        if ($logout !== null) { $items['customer-logout'] = $logout; }
        return $items;
    }
    public function endpoint_content() {
        echo do_shortcode('[' . self::SHORTCODE . ']'); 
    }

    

    public function shortcode() {
        $user = wp_get_current_user();
        if (!$user || 0 === (int) $user->ID) {
            return '<p>' . esc_html__('Συνδεθείτε για να δείτε την κάρτα Bonus σας.', 'ai-eshop-optimizer') . '</p>';
        }
        $role = self::loyalty_role();
        if (in_array($role, (array) $user->roles, true)) {
            return $this->render_card((int) $user->ID);
        }
        
        
        $enrolled = $this->maybe_handle_enroll((int) $user->ID, $role);
        if ($enrolled === 'enrolled') {
            return $this->render_card((int) $user->ID);
        }
        $result = $this->maybe_handle_submit((int) $user->ID, $role);
        if ($result === 'matched') {
            return $this->render_card((int) $user->ID);
        }
        return (is_string($enrolled) ? $enrolled : '')
            . (is_string($result) ? $result : '')
            . $this->render_form()
            . $this->render_enroll_cta();
    }

    private function vitals_field($user_id, $col) {
        global $wpdb;
        $tbl = $wpdb->prefix . 'aieo_user_vitals';
        
        return $wpdb->get_var($wpdb->prepare("SELECT `{$col}` FROM {$tbl} WHERE user_id = %d", (int) $user_id));
    }

    
    private function fresh_points($loyalty_id) {
        $loyalty_id = trim((string) $loyalty_id);
        if ($loyalty_id === '') { return null; }
        global $wpdb;
        $table = self::customers_table();
        if ($table === '' || !$wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table))) { return null; }
        
        return $wpdb->get_row($wpdb->prepare("SELECT BonusPoints, BonusPointsTotal FROM `{$table}` WHERE LoyaltyId = %s LIMIT 1", $loyalty_id));
    }

    private function render_card($user_id) {
        $name   = (string) $this->vitals_field($user_id, 'soft1_customer_name');
        $lid    = (string) $this->vitals_field($user_id, 'soft1_loyalty_id');
        $points = (string) $this->vitals_field($user_id, 'soft1_loyalty_points');
        $total  = (string) $this->vitals_field($user_id, 'soft1_loyalty_points_total');
        $since  = (string) $this->vitals_field($user_id, 'soft1_first_transaction_date');
        
        
        
        $fresh = $this->fresh_points($lid);
        if ($fresh) {
            if (isset($fresh->BonusPoints) && $fresh->BonusPoints !== '')          { $points = (string) $fresh->BonusPoints; }
            if (isset($fresh->BonusPointsTotal) && $fresh->BonusPointsTotal !== '') { $total  = (string) $fresh->BonusPointsTotal; }
        }
        $since_fmt = '';
        if ($since !== '' && $since !== '0000-00-00 00:00:00') {
            $d = date_create($since);
            if ($d) { $since_fmt = $d->format('d-m-Y'); }
        }
        $out  = '<div class="aieo-loyalty-card">';
        $out .= '<h4>' . esc_html__('Ονοματεπώνυμο', 'ai-eshop-optimizer') . ': ' . esc_html($name) . '</h4>';
        $out .= '<h6>' . esc_html__('Αρ. Bonus Card', 'ai-eshop-optimizer') . ': ' . esc_html($lid) . '</h6>';
        $out .= '<h6>' . esc_html__('Μέλος από', 'ai-eshop-optimizer') . ': ' . esc_html($since_fmt) . '</h6>';
        $out .= '<h6>' . esc_html__('Πόντοι', 'ai-eshop-optimizer') . ': ' . esc_html($points) . '</h6>';
        $out .= '<h4>' . esc_html__('Σύνολο Πόντων', 'ai-eshop-optimizer') . ': ' . esc_html($total) . '</h4>';
        $out .= '</div>';
        return $out;
    }

    private function render_form() {
        $out  = '<h4>' . esc_html__('Έχετε ήδη κάρτα Bonus;', 'ai-eshop-optimizer') . '</h4>';
        $out .= esc_html__('Δυστυχώς με τα στοιχεία του λογαριασμού σας στο eshop δεν μπορέσαμε να σας αναγνωρίσουμε.', 'ai-eshop-optimizer') . '<br>';
        $out .= esc_html__('Συμπληρώστε τον αριθμό της κάρτας Bonus και το κινητό (ή το email) που δηλώσατε κατά την εγγραφή σας στο κατάστημα. Αν ταιριάζουν, θα ταυτοποιηθείτε αμέσως!', 'ai-eshop-optimizer') . '<br><br>';
        $out .= '<div class="om-table"><form method="post">';
        $out .= wp_nonce_field('aieo_loyalty_match', 'aieo_loyalty_nonce', true, false);
        $out .= '<div class="om-row account-settings-row"><div class="om-cell">' . esc_html__('Αρ. κάρτας Bonus:', 'ai-eshop-optimizer') . '</div><div class="om-cell"><input type="text" name="aieo_loyalty_id" required></div></div>';
        $out .= '<div class="om-row account-settings-row"><div class="om-cell">' . esc_html__('Κινητό Τηλέφωνο:', 'ai-eshop-optimizer') . '</div><div class="om-cell"><input type="text" name="aieo_loyalty_phone"></div></div>';
        $out .= '<div class="om-row account-settings-row"><div class="om-cell">' . esc_html__('Email:', 'ai-eshop-optimizer') . '</div><div class="om-cell"><input type="text" name="aieo_loyalty_email"></div></div>';
        $out .= '<div class="om-cellsubmit"><input type="submit" class="button button-primary button-setup center-content" value="' . esc_attr__('Αναζήτηση', 'ai-eshop-optimizer') . '"></div>';
        $out .= '</form></div>';
        return $out;
    }

    
    private function maybe_handle_submit($user_id, $role) {
        if (!isset($_POST['aieo_loyalty_id'], $_POST['aieo_loyalty_email'], $_POST['aieo_loyalty_phone'])) { return ''; }
        if (!isset($_POST['aieo_loyalty_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['aieo_loyalty_nonce'])), 'aieo_loyalty_match')) {
            return '<div class="om-alarm">' . esc_html__('Λήξη συνεδρίας — δοκιμάστε ξανά.', 'ai-eshop-optimizer') . '</div>';
        }
        global $wpdb;
        $table = self::customers_table();
        if ($table === '' || !$wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table))) {
            return '<div class="om-alarm">' . esc_html__('Η υπηρεσία δεν είναι διαθέσιμη αυτή τη στιγμή.', 'ai-eshop-optimizer') . '</div>';
        }
        $lid   = sanitize_text_field(wp_unslash($_POST['aieo_loyalty_id']));
        $email = sanitize_email(wp_unslash($_POST['aieo_loyalty_email']));
        $phone = sanitize_text_field(wp_unslash($_POST['aieo_loyalty_phone']));
        
        $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM `{$table}` WHERE LoyaltyId = %s AND (CustomerEmail = %s OR CustomerPhone = %s) LIMIT 1", $lid, $email, $phone));
        if (!$row) {
            return '<div class="om-alarm">' . esc_html__('Δεν βρέθηκε μέλος με τα στοιχεία που δώσατε!', 'ai-eshop-optimizer') . '</div>';
        }
        $this->upsert_vitals($user_id, $row);
        $u = new WP_User($user_id);
        $u->add_role($role);
        return 'matched';
    }

    
    private function maybe_handle_enroll($user_id, $role) {
        if (!isset($_POST['aieo_loyalty_enroll'])) { return ''; }
        if (!isset($_POST['aieo_loyalty_enroll_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['aieo_loyalty_enroll_nonce'])), 'aieo_loyalty_enroll')) {
            return '<div class="om-alarm">' . esc_html__('Λήξη συνεδρίας — δοκιμάστε ξανά.', 'ai-eshop-optimizer') . '</div>';
        }
        $card_id = $this->generate_enroll_card_id($user_id);
        
        
        global $wpdb;
        $tbl  = $wpdb->prefix . 'aieo_user_vitals';
        $sv   = static function ($v) { return ($v !== null && $v !== '') ? (string) $v : null; };
        $u    = new WP_User($user_id);
        $name = trim((string) $u->display_name);
        if ($name === '') { $name = trim(trim((string) $u->first_name) . ' ' . trim((string) $u->last_name)); }
        $data = array(
            'soft1_customer_name'          => $sv($name),
            'soft1_loyalty_id'             => (int) $card_id,
            'soft1_loyalty_points'         => 0,
            'soft1_loyalty_points_total'   => 0,
            'soft1_first_transaction_date' => current_time('mysql', true),
        );
        if ($wpdb->get_var($wpdb->prepare("SELECT 1 FROM {$tbl} WHERE user_id = %d", (int) $user_id))) {
            $wpdb->update($tbl, $data, array('user_id' => (int) $user_id));
        } else {
            $data['user_id'] = (int) $user_id;
            $wpdb->insert($tbl, $data);
        }
        $u->add_role($role);
        
        
        do_action('aieo_loyalty_enrolled', $user_id, $card_id, array('source' => 'self_service'));
        return 'enrolled';
    }

    
    private function generate_enroll_card_id($user_id) {
        return (int) apply_filters('aieo_loyalty_enroll_card_id', (int) $user_id, $user_id);
    }

    
    private function render_enroll_cta() {
        $out  = '<div class="om-table">';
        $out .= '<h4>' . esc_html__('Δεν είστε ακόμη μέλος;', 'ai-eshop-optimizer') . '</h4>';
        $out .= '<p>' . esc_html__('Γίνετε μέλος του προγράμματος Bonus τώρα και αρχίστε να μαζεύετε πόντους με κάθε αγορά σας.', 'ai-eshop-optimizer') . '</p>';
        $out .= '<form method="post">';
        $out .= wp_nonce_field('aieo_loyalty_enroll', 'aieo_loyalty_enroll_nonce', true, false);
        $out .= '<div class="om-cellsubmit"><input type="submit" name="aieo_loyalty_enroll" class="button button-primary button-setup center-content" value="' . esc_attr__('Γίνε μέλος τώρα', 'ai-eshop-optimizer') . '"></div>';
        $out .= '</form></div>';
        return $out;
    }

    private function norm_date($v) {
        $v = trim((string) $v);
        if ($v === '' || strpos($v, '0000-00-00') === 0) { return null; }
        $d = date_create($v);
        return $d ? $d->format('Y-m-d H:i:s') : null;
    }

    private function upsert_vitals($user_id, $row) {
        global $wpdb;
        $tbl  = $wpdb->prefix . 'aieo_user_vitals';
        $iv   = static function ($v) { return ($v !== null && $v !== '') ? (int) $v : null; };
        $sv   = static function ($v) { return ($v !== null && $v !== '') ? (string) $v : null; };
        $data = array(
            'soft1_customer_name'           => $sv($row->CustomerName ?? null),
            'soft1_customer_id'             => $iv($row->CustomerId ?? null),
            'soft1_loyalty_id'              => $iv($row->LoyaltyId ?? null),
            'soft1_loyalty_points'          => $iv($row->BonusPoints ?? null),
            'soft1_loyalty_points_total'    => $iv($row->BonusPointsTotal ?? null),
            'soft1_latest_location'         => $sv($row->CustomerLatestLocation ?? null),
            'soft1_recorded_speciality'     => $sv($row->CustomerRecordedSpeciality ?? null),
            'soft1_latest_transaction_date' => $this->norm_date($row->CustomerLatestTransaction ?? ''),
            'soft1_first_transaction_date'  => $this->norm_date($row->CustomerFirstTransaction ?? ''),
        );
        if ($wpdb->get_var($wpdb->prepare("SELECT 1 FROM {$tbl} WHERE user_id = %d", (int) $user_id))) {
            $wpdb->update($tbl, $data, array('user_id' => (int) $user_id));
        } else {
            $data['user_id'] = (int) $user_id;
            $wpdb->insert($tbl, $data);
        }
    }
}
}
