<?php
/**
 * Core Admin class for Menu Routing, Enqueues, and Admin-Post Form Handling.
 */

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

class PexEmail_Admin {

    public function init() {
        // Register Sidebar Menus & Assets
        add_action( 'admin_menu', [ $this, 'register_menus' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_assets' ] );
        
        // Handle secure form submissions via admin-post.php
        add_action( 'admin_post_pexemail_save_license', [ $this, 'save_license_key' ] );
        add_action( 'admin_post_pexemail_save_settings', [ $this, 'save_settings' ] );
        
        // Campaign Action Handlers
        add_action( 'admin_post_pexemail_save_campaign', [ $this, 'save_campaign' ] );
        add_action( 'admin_post_pexemail_duplicate_campaign', [ $this, 'duplicate_campaign' ] );
        add_action( 'admin_post_pexemail_delete_campaign', [ $this, 'delete_campaign' ] );

        // Global License Enforcement (Warnings & Lockdowns)
        add_action( 'admin_notices', [ $this, 'global_license_enforcement' ] );
    }

    /**
     * Enqueue CSS and JS securely, only on our plugin's pages.
     */
    public function enqueue_admin_assets( $hook ) {
        // Only load assets if the current page URL contains 'pexemail'
        if ( strpos( $hook, 'pexemail' ) === false ) {
            return;
        }

        // Load Master CSS
        wp_enqueue_style( 
            'pexemail-admin-style', 
            PEXEMAIL_URL . 'assets/css/admin-style.css', 
            [], 
            PEXEMAIL_VERSION 
        );

        // Load Chart.js Locally (Fixes WP.org CDN Offload Rule)
        wp_enqueue_script(
            'pexemail-chart-js',
            PEXEMAIL_URL . 'assets/js/chart.min.js',
            [],
            '3.9.1', 
            true
        );

        // Load Master JS
        wp_enqueue_script( 
            'pexemail-admin-script', 
            PEXEMAIL_URL . 'assets/js/admin-script.js', 
            [ 'jquery', 'pexemail-chart-js' ], 
            PEXEMAIL_VERSION, 
            true 
        );

        // Securely pass PHP variables into our external JS file
        wp_localize_script( 'pexemail-admin-script', 'pexEmailGlobal', [
            'ajax_url'       => admin_url( 'admin-ajax.php' ),
            'nonce_contacts' => wp_create_nonce( 'pexemail_contacts_nonce' ),
            'nonce_admin'    => wp_create_nonce( 'pexemail_admin_nonce' )
        ] );
    }

    public function register_menus() {
        $menu_icon = 'dashicons-email-alt';

        // FIX: Replaced all 16 instances of 'pexally-email-campaign' with 'pexally-email-campaigns'
        add_menu_page( __( 'Pexally Email', 'pexally-email-campaigns' ), __( 'Pexally Email', 'pexally-email-campaigns' ), 'manage_options', 'pexemail-dashboard', [ $this, 'load_view_dashboard' ], $menu_icon, 30 );
        
        add_submenu_page( 'pexemail-dashboard', __( 'Dashboard', 'pexally-email-campaigns' ), __( 'Dashboard', 'pexally-email-campaigns' ), 'manage_options', 'pexemail-dashboard', [ $this, 'load_view_dashboard' ] );
        add_submenu_page( 'pexemail-dashboard', __( 'Campaigns', 'pexally-email-campaigns' ), __( 'Campaigns', 'pexally-email-campaigns' ), 'manage_options', 'pexemail-campaigns', [ $this, 'load_view_campaigns' ] );
        add_submenu_page( 'pexemail-dashboard', __( 'Create Campaign', 'pexally-email-campaigns' ), __( 'Create Campaign', 'pexally-email-campaigns' ), 'manage_options', 'pexemail-campaigns-add', [ $this, 'load_view_campaigns' ] );
        add_submenu_page( 'pexemail-dashboard', __( 'Audience', 'pexally-email-campaigns' ), __( 'Audience', 'pexally-email-campaigns' ), 'manage_options', 'pexemail-contacts', [ $this, 'load_view_contacts' ] );
        add_submenu_page( 'pexemail-dashboard', __( 'Templates', 'pexally-email-campaigns' ), __( 'Templates', 'pexally-email-campaigns' ), 'manage_options', 'pexemail-templates', [ $this, 'load_view_templates' ] );
        add_submenu_page( 'pexemail-dashboard', __( 'Settings', 'pexally-email-campaigns' ), __( 'Settings', 'pexally-email-campaigns' ), 'manage_options', 'pexemail-settings', [ $this, 'load_view_settings' ] );
        add_submenu_page( 'pexemail-dashboard', __( 'Pro License', 'pexally-email-campaigns' ), __( 'Pro License', 'pexally-email-campaigns' ), 'manage_options', 'pexemail-license', [ $this, 'load_view_license' ] );
    }

    public function save_license_key() {
        if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Unauthorized' );
        check_admin_referer( 'pexemail_save_license_action', 'pexemail_license_nonce' );

        $license_key    = isset( $_POST['pexemail_license_key'] ) ? sanitize_text_field( wp_unslash( $_POST['pexemail_license_key'] ) ) : '';
        $licensed_email = isset( $_POST['pexemail_licensed_email'] ) ? sanitize_email( wp_unslash( $_POST['pexemail_licensed_email'] ) ) : '';
        
        update_option( 'pexemail_license_key', $license_key );
        update_option( 'pexemail_input_email', $licensed_email ); 
        
        require_once PEXEMAIL_DIR . 'includes/class-pexemail-license.php';
        PexEmail_License::verify_license_manually( $license_key, $licensed_email );

        wp_safe_redirect( add_query_arg( [ 'page' => 'pexemail-license', 'license_updated' => '1' ], admin_url( 'admin.php' ) ) );
        exit;
    }

    public function save_settings() {
        if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Unauthorized' );
        check_admin_referer( 'pexemail_save_settings_action', 'pexemail_settings_nonce' );

        $raw_pw = isset($_POST['smtp_password']) ? sanitize_text_field( wp_unslash( $_POST['smtp_password'] ) ) : '';
        $clean_pw = str_replace( ' ', '', $raw_pw );

        $settings = [
            'enabled'             => isset($_POST['enabled']) ? 'yes' : 'no',
            'sender_name'         => isset($_POST['sender_name']) ? sanitize_text_field( wp_unslash( $_POST['sender_name'] ) ) : '',
            'sender_email'        => isset($_POST['sender_email']) ? sanitize_email( wp_unslash( $_POST['sender_email'] ) ) : '',
            'logo_url'            => isset($_POST['logo_url']) ? esc_url_raw( wp_unslash( $_POST['logo_url'] ) ) : '',
            'footer_contact_text' => isset($_POST['footer_contact_text']) ? wp_kses_post( wp_unslash( $_POST['footer_contact_text'] ) ) : '',
            
            // Socials
            'facebook_url'        => isset($_POST['facebook_url']) ? esc_url_raw( wp_unslash( $_POST['facebook_url'] ) ) : '',
            'x_url'               => isset($_POST['x_url']) ? esc_url_raw( wp_unslash( $_POST['x_url'] ) ) : '',
            'linkedin_url'        => isset($_POST['linkedin_url']) ? esc_url_raw( wp_unslash( $_POST['linkedin_url'] ) ) : '',
            'instagram_url'       => isset($_POST['instagram_url']) ? esc_url_raw( wp_unslash( $_POST['instagram_url'] ) ) : '',
            'youtube_url'         => isset($_POST['youtube_url']) ? esc_url_raw( wp_unslash( $_POST['youtube_url'] ) ) : '',
            'telegram_url'        => isset($_POST['telegram_url']) ? esc_url_raw( wp_unslash( $_POST['telegram_url'] ) ) : '',
            'whatsapp_url'        => isset($_POST['whatsapp_url']) ? esc_url_raw( wp_unslash( $_POST['whatsapp_url'] ) ) : '',
            'teams_url'           => isset($_POST['teams_url']) ? esc_url_raw( wp_unslash( $_POST['teams_url'] ) ) : '',
            
            // SMTP
            'smtp_enabled'        => isset($_POST['smtp_enabled']) ? sanitize_text_field( wp_unslash( $_POST['smtp_enabled'] ) ) : 'no',
            'smtp_provider'       => isset($_POST['smtp_provider']) ? sanitize_text_field( wp_unslash( $_POST['smtp_provider'] ) ) : 'google',
            'smtp_host'           => isset($_POST['smtp_host']) ? sanitize_text_field( wp_unslash( $_POST['smtp_host'] ) ) : '',
            'smtp_port'           => isset($_POST['smtp_port']) ? intval( $_POST['smtp_port'] ) : 587,
            'smtp_secure'         => isset($_POST['smtp_secure']) ? sanitize_text_field( wp_unslash( $_POST['smtp_secure'] ) ) : 'tls',
            'smtp_username'       => isset($_POST['smtp_username']) ? sanitize_text_field( wp_unslash( $_POST['smtp_username'] ) ) : '',
            'smtp_password'       => $clean_pw,
        ];
        
        update_option( 'pexemail_settings', $settings );
        wp_safe_redirect( add_query_arg( [ 'page' => 'pexemail-settings', 'settings_updated' => '1' ], admin_url( 'admin.php' ) ) );
        exit;
    }

    public function save_campaign() {
        if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Unauthorized' );
        check_admin_referer( 'pexemail_save_campaign_action', 'pexemail_campaign_nonce' );

        global $wpdb;
        $campaign_id = isset( $_POST['campaign_id'] ) ? intval( $_POST['campaign_id'] ) : 0;
        $subject     = isset( $_POST['campaign_subject'] ) ? sanitize_text_field( wp_unslash( $_POST['campaign_subject'] ) ) : '';
        $template    = isset( $_POST['campaign_template'] ) ? wp_kses_post( wp_unslash( $_POST['campaign_template'] ) ) : '';
        $list_id     = isset( $_POST['list_id'] ) ? intval( $_POST['list_id'] ) : 0;

        if ( $campaign_id > 0 ) {
            $wpdb->update( $wpdb->prefix . 'pexemail_campaigns', [
                'subject'  => $subject,
                'template' => $template,
                'list_id'  => $list_id
            ], [ 'id' => $campaign_id ], [ '%s', '%s', '%d' ], [ '%d' ] );
        } else {
            $wpdb->insert( $wpdb->prefix . 'pexemail_campaigns', [
                'subject'  => $subject,
                'template' => $template,
                'list_id'  => $list_id,
                'status'   => 'draft'
            ], [ '%s', '%s', '%d', '%s' ] );
            $campaign_id = $wpdb->insert_id;
        }

        $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}pexemail_recipients WHERE campaign_id = %d AND status = 'pending'", $campaign_id ) );
        
        if ( $list_id > 0 ) {
            $wpdb->query( $wpdb->prepare( "
                INSERT INTO {$wpdb->prefix}pexemail_recipients (campaign_id, contact_id, email, status)
                SELECT %d, id, email, 'pending' 
                FROM {$wpdb->prefix}pexemail_contacts 
                WHERE list_id = %d AND status = 'subscribed'
            ", $campaign_id, $list_id ) );
        }

        wp_safe_redirect( add_query_arg( [ 'page' => 'pexemail-campaigns', 'action' => 'view', 'id' => $campaign_id, 'saved' => '1' ], admin_url( 'admin.php' ) ) );
        exit;
    }

    public function duplicate_campaign() {
        if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Unauthorized' );
        check_admin_referer( 'pexemail_duplicate_campaign_action', 'pexemail_duplicate_nonce' );
        
        global $wpdb;
        $id = isset( $_GET['id'] ) ? intval( $_GET['id'] ) : 0;
        
        $campaign = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}pexemail_campaigns WHERE id = %d", $id ) );
        
        if ( $campaign ) {
            $wpdb->insert( $wpdb->prefix . 'pexemail_campaigns', [
                'subject'  => $campaign->subject . ' (Copy)',
                'template' => $campaign->template,
                'list_id'  => $campaign->list_id,
                'status'   => 'draft'
            ], [ '%s', '%s', '%d', '%s' ] );
            $new_campaign_id = $wpdb->insert_id;

            if ( $campaign->list_id > 0 ) {
                $wpdb->query( $wpdb->prepare( "
                    INSERT INTO {$wpdb->prefix}pexemail_recipients (campaign_id, contact_id, email, status)
                    SELECT %d, id, email, 'pending' 
                    FROM {$wpdb->prefix}pexemail_contacts 
                    WHERE list_id = %d AND status = 'subscribed'
                ", $new_campaign_id, $campaign->list_id ) );
            }
        }
        
        wp_safe_redirect( add_query_arg( [ 'page' => 'pexemail-campaigns', 'duplicated' => '1' ], admin_url( 'admin.php' ) ) );
        exit;
    }

    public function delete_campaign() {
        if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Unauthorized' );
        check_admin_referer( 'pexemail_delete_campaign_action', 'pexemail_delete_nonce' );
        
        global $wpdb;
        $id = isset( $_GET['id'] ) ? intval( $_GET['id'] ) : 0;
        
        $wpdb->delete( $wpdb->prefix . 'pexemail_campaigns', [ 'id' => $id ], [ '%d' ] );
        $wpdb->delete( $wpdb->prefix . 'pexemail_recipients', [ 'campaign_id' => $id ], [ '%d' ] );
        
        wp_safe_redirect( add_query_arg( [ 'page' => 'pexemail-campaigns', 'deleted' => '1' ], admin_url( 'admin.php' ) ) );
        exit;
    }

    /**
     * Executes strict global rules but no longer locks the UI.
     */
    public function global_license_enforcement() {
        $screen = get_current_screen();
        
        if ( ! $screen || strpos( $screen->id, 'pexemail' ) === false ) {
            return;
        }

        $status     = get_option( 'pexemail_license_status', 'invalid' );
        $details    = get_option( 'pexemail_license_details', [] );
        $expires_at = isset($details['expires_at']) ? intval($details['expires_at']) : 0;
        
        // Dynamic check: if time has crossed expiration limit, mark expired.
        if ( $status === 'active' && $expires_at > 0 && time() > $expires_at ) {
            $status = 'expired';
            update_option( 'pexemail_license_status', 'expired' );
        }

        $days_left = $expires_at > 0 ? ceil( ( $expires_at - time() ) / 86400 ) : 0;
        
        // 1. STANDARD EXPIRATION NOTICE (No more UI lockdown! Users just drop to the free tier)
        if ( $status === 'expired' ) {
            echo '<div class="notice notice-warning" style="border-left-color: #ef4444; padding: 12px; display: flex; justify-content: space-between; align-items: center;">';
            echo '<p style="margin:0; font-size:14px;"><strong>Pexally Pro License Expired:</strong> Your account has been reverted to the Free Tier (50 emails/day limit). Renew to restore high-volume sending.</p>';
            echo '<a href="https://payment.pexally.com/pexally-secure-checkout/" target="_blank" class="button" style="border-color:#ef4444; color:#ef4444;">Renew License</a>';
            echo '</div>';
        }

        // 2. 15-DAY WARNING ENGINE (Premium Global Notice)
        if ( $status === 'active' && $expires_at > 0 && $days_left <= 15 ) {
            echo '<div style="max-width: 1400px; margin: 25px 20px 0 0; background: linear-gradient(to right, #fffbeb, #fef3c7); border: 1px solid #fde68a; border-left: 4px solid #d97706; padding: 18px 24px; border-radius: 12px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.02); font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;">';
            echo '<div style="display: flex; align-items: center; gap: 16px;">';
            echo '<div style="background: #fff; width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: #d97706; box-shadow: 0 2px 4px rgba(217, 119, 6, 0.1);"><svg width="24" height="24" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg></div>';
            echo '<div>';
            echo '<strong style="color: #92400e; font-size: 15px; display: block; margin-bottom: 2px;">Pexally Pro License Expiring Soon</strong>';
            echo '<span style="color: #b45309; font-size: 14px; font-weight: 500;">Your license key will expire in <strong>' . intval( $days_left ) . ' days</strong>. Renew now to avoid service interruption.</span>';
            echo '</div></div>';
            echo '<a href="https://payment.pexally.com/pexally-secure-checkout/" target="_blank" style="background: #d97706; color: #fff; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: 700; font-size: 14px; white-space: nowrap; box-shadow: 0 4px 10px -2px rgba(217, 119, 6, 0.3); transition: all 0.2s;">Renew License →</a>';
            echo '</div>';
        }
    }

    // --- View Loaders ---
    public function load_view_dashboard() { 
        $file = PEXEMAIL_DIR . 'views/page-dashboard.php';
        if ( file_exists( $file ) ) { include $file; } else { echo '<div class="wrap"><h2>Error: views/page-dashboard.php not found.</h2></div>'; }
    }
    
    public function load_view_campaigns() { 
        $file = PEXEMAIL_DIR . 'views/page-campaigns.php';
        if ( file_exists( $file ) ) { include $file; } else { echo '<div class="wrap"><h2>Error: views/page-campaigns.php not found.</h2></div>'; }
    }
    
    public function load_view_contacts() { 
        $file = PEXEMAIL_DIR . 'views/page-contacts.php';
        if ( file_exists( $file ) ) { include $file; } else { echo '<div class="wrap"><h2>Error: views/page-contacts.php not found.</h2></div>'; }
    }
    
    public function load_view_templates() { 
        $file = PEXEMAIL_DIR . 'views/page-templates.php';
        if ( file_exists( $file ) ) { include $file; } else { echo '<div class="wrap"><h2>Error: views/page-templates.php not found.</h2></div>'; }
    }
    
    public function load_view_settings() { 
        $file = PEXEMAIL_DIR . 'views/page-settings.php';
        if ( file_exists( $file ) ) { include $file; } else { echo '<div class="wrap"><h2>Error: views/page-settings.php not found.</h2></div>'; }
    }
    
    public function load_view_license() { 
        $file = PEXEMAIL_DIR . 'views/page-license.php';
        if ( file_exists( $file ) ) { include $file; } else { echo '<div class="wrap"><h2>Error: views/page-license.php not found.</h2></div>'; }
    }
}