<?php

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

// Define plugin constants
define('KAVEHBOARD_VERSION', '1.0.0');


// Helper function to get pages for select options
function kavehboard_get_pages_options() {
    $pages = get_pages();
    $options = array('' => __('Select a page', 'kavehTheme'));
    
    foreach ($pages as $page) {
        $options[$page->ID] = $page->post_title;
    }
    
    return $options;
} 

// Helper function to get Elementor templates
function kavehboard_get_elementor_templates() {
    $templates = get_posts(array(
        'post_type' => 'elementor_library',
        'posts_per_page' => -1,
        'meta_query' => array(
            array(
                'key' => '_elementor_template_type',
                'value' => array('page', 'section'),
                'compare' => 'IN'
            )
        )
    ));
    $options = array('' => __('Select a template', 'kavehTheme'));
    foreach ($templates as $template) {
        $options[$template->ID] = $template->post_title;
    }
    return $options;
}

// Function to get user avatar URL with custom avatar support
function kavehboard_get_user_avatar_url($user_id, $size = 96) {
    $custom_avatar_id = get_user_meta($user_id, 'custom_avatar', true);
    if ($custom_avatar_id) {
        $avatar_url = wp_get_attachment_image_url($custom_avatar_id, 'thumbnail');
        if ($avatar_url) {
            return $avatar_url;
        }
    }
    return get_avatar_url($user_id, array('size' => $size));
}



spl_autoload_register(function ($classname) {
  $class = str_replace('\\', DIRECTORY_SEPARATOR, str_replace('_', '-', strtolower($classname)));
  $classes = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . $class . '.php';
  if (file_exists($classes)) {
    require_once ($classes);
  }
});

/**
 * Get notifications for a specific user
 */
function kavehboard_get_user_notifications($user_id, $limit = 10) {
    $args = array(
        'post_type' => 'kaveh_notification',
        'post_status' => 'publish',
        'posts_per_page' => $limit,
        'meta_query' => array(
            'relation' => 'AND',
            array(
                'key' => '_kaveh_notification_active',
                'value' => '1',
                'compare' => '='
            ),
            array(
                'relation' => 'OR',
                array(
                    'key' => '_kaveh_notification_target_type',
                    'value' => 'all',
                    'compare' => '='
                ),
                array(
                    'relation' => 'AND',
                    array(
                        'key' => '_kaveh_notification_target_type',
                        'value' => 'specific',
                        'compare' => '='
                    ),
                    array(
                        'key' => '_kaveh_notification_target_user',
                        'value' => $user_id,
                        'compare' => '='
                    )
                )
            )
        ),
        'orderby' => 'date',
        'order' => 'DESC'
    );
    
    return get_posts($args);
}

/**
 * Get unread notifications count for a user
 */
function kavehboard_get_unread_notifications_count($user_id) {
    $notifications = kavehboard_get_user_notifications($user_id, -1);
    $read_notifications = get_user_meta($user_id, '_kaveh_read_notifications', true) ?: array();
    
    $unread_count = 0;
    foreach ($notifications as $notification) {
        if (!in_array($notification->ID, $read_notifications)) {
            $unread_count++;
        }
    }
    
    return $unread_count;
}

/**
 * Mark notification as read for a user
 */
function kavehboard_mark_notification_read($user_id, $notification_id) {
    $read_notifications = get_user_meta($user_id, '_kaveh_read_notifications', true) ?: array();
    
    if (!in_array($notification_id, $read_notifications)) {
        $read_notifications[] = $notification_id;
        update_user_meta($user_id, '_kaveh_read_notifications', $read_notifications);
    }
}

/**
 * Ensure dashboard page exists
 */
function kavehboard_ensure_dashboard_page_exists() {
    kavehboard_create_dashboard_page();
}

/**
 * Create dashboard page and set it in options if not already configured
 */
function kavehboard_create_dashboard_page() {
    // Get current options
    $options = get_option('kavehboard_options', array());
    
    // Check if dashboard page is already set and valid
    $page_id = isset($options['kavehboard_page']) ? $options['kavehboard_page'] : '';
    if ($page_id && get_post_status($page_id) === 'publish' && get_post_type($page_id) === 'page') {
        return $page_id;
    }
    
    // Check if a page with 'dashboard' slug exists
    $existing_page = get_page_by_path('dashboard');
    if ($existing_page && $existing_page->post_status === 'publish') {
        // Update options to use this existing page
        $options['kavehboard_page'] = $existing_page->ID;
        update_option('kavehboard_options', $options);
        return $existing_page->ID;
    }
    
    // Create new dashboard page
    $page_data = array(
        'post_title' => __('Dashboard', 'kavehTheme'),
        'post_content' => '',
        'post_status' => 'publish',
        'post_type' => 'page',
        'post_name' => 'dashboard',
        'comment_status' => 'closed',
        'ping_status' => 'closed'
    );
    
    $page_id = wp_insert_post($page_data);
    
    if ($page_id && !is_wp_error($page_id)) {
        // Update options to use the new page
        $options['kavehboard_page'] = $page_id;
        update_option('kavehboard_options', $options);
        return $page_id;
    }
    
    return false;
}

/**
 * Get dashboard page ID
 */
function kavehboard_get_dashboard_page_id() {
    $options = get_option('kavehboard_options', array());
    return isset($options['kavehboard_page']) ? $options['kavehboard_page'] : 0;
}

/**
 * Add admin label for dashboard page
 */
add_filter('display_post_states', 'kavehboard_add_dashboard_page_label', 10, 2);
function kavehboard_add_dashboard_page_label($post_states, $post) {
    $dashboard_page_id = kavehboard_get_dashboard_page_id();
    
    if ($post->ID == $dashboard_page_id) {
        $post_states['kavehboard_dashboard_page'] = __('Dashboard Page', 'kavehTheme');
    }
    
    return $post_states;
}

/**
 * Mark all notifications as read for a user
 */
function kavehboard_mark_all_notifications_read($user_id) {
    $notifications = kavehboard_get_user_notifications($user_id, -1);
    $notification_ids = array();
    
    foreach ($notifications as $notification) {
        $notification_ids[] = $notification->ID;
    }
    
    update_user_meta($user_id, '_kaveh_read_notifications', $notification_ids);
}

/**
 * Check if notification is read by user
 */
function kavehboard_is_notification_read($user_id, $notification_id) {
     $read_notifications = get_user_meta($user_id, '_kaveh_read_notifications', true) ?: array();
     return in_array($notification_id, $read_notifications);
 }


$kavehboardassets =  new kavehboardassets();
$kavehboardheaderandfooter =  new kavehboardheaderandfooter();
$kavehboardpages =  new kavehboardpages();
$kavehboardrouting = new kavehboardrouting();
$kavehboardticketsystem = new Kavehboardticketsystem();
new Kavehboardticketadmin();
new Kavehboardticketsubmission();
new Kavehboardticketdashboard();
new Kavehboardticketshortcodes();

// Initialize wallet system
$kavehboardwallet = Kavehboardwallet::get_instance();
new Kavehboardwalletshortcodes();

$kavehboard_options = new kavehboardOptions('kavehboard_options');

// Ensure dashboard page exists on init
add_action('init', 'kavehboard_ensure_dashboard_page_exists');

// Flush rewrite rules on plugin activation
register_activation_hook(__FILE__, 'kavehboard_activate');

// Flush rewrite rules on plugin deactivation
register_deactivation_hook(__FILE__, 'kavehboard_flush_rewrite_rules');

/**
 * Plugin activation hook
 */
function kavehboard_activate() {
    // Create dashboard page
    kavehboard_create_dashboard_page();
    
    // Flush rewrite rules
    kavehboard_flush_rewrite_rules();
}

function kavehboard_flush_rewrite_rules() {
    // Initialize routing to add rewrite rules
    new kavehboardrouting();
    flush_rewrite_rules();
    
    // Set a transient to show admin notice
    set_transient('kavehboard_flush_rewrite_rules', true, 300);
}



// Add function to manually flush rewrite rules
add_action('wp_ajax_kavehboard_flush_rules', 'kavehboard_manual_flush_rules');
function kavehboard_manual_flush_rules() {
    if (current_user_can('manage_options')) {
        new kavehboardrouting();
        flush_rewrite_rules();
        wp_die('Rewrite rules flushed successfully!');
    }
}

// Add admin notice for permalink flush
add_action('admin_notices', 'kavehboard_permalink_notice');
function kavehboard_permalink_notice() {
    if (get_transient('kavehboard_flush_rewrite_rules')) {
        echo '<div class="notice notice-warning is-dismissible">';
        echo '<p>' . __('Kavehboard: Please go to Settings > Permalinks and click "Save Changes" to update URL structure.', 'kavehboard') . '</p>';
        echo '</div>';
        delete_transient('kavehboard_flush_rewrite_rules');
    }
}





// Helper function to get users for select options
function kavehboard_get_users_options() {
    $users = get_users(array(
        'number' => 100, // Limit to 100 users for performance
        'orderby' => 'display_name',
        'order' => 'ASC'
    ));
    
    $options = array();
    foreach ($users as $user) {
        $options[$user->ID] = $user->display_name . ' (' . $user->user_email . ')';
    }
    
    return $options;
}


   

// AJAX handlers for notifications
add_action('wp_ajax_kaveh_mark_notification_read', 'kavehboard_ajax_mark_notification_read');
add_action('wp_ajax_kaveh_mark_all_notifications_read', 'kavehboard_ajax_mark_all_notifications_read');

/**
 * AJAX handler for marking single notification as read
 */
function kavehboard_ajax_mark_notification_read() {
    // Verify nonce for security
    if (!wp_verify_nonce($_POST['nonce'], 'kavehboard_nonce')) {
        wp_die('Security check failed');
    }
    
    $user_id = get_current_user_id();
    $notification_id = intval($_POST['notification_id']);
    
    if ($user_id && $notification_id) {
        kavehboard_mark_notification_read($user_id, $notification_id);
        wp_send_json_success('Notification marked as read');
    } else {
        wp_send_json_error('Invalid request');
    }
}

/**
 * AJAX handler for marking all notifications as read
 */
function kavehboard_ajax_mark_all_notifications_read() {
    // Verify nonce for security
    if (!wp_verify_nonce($_POST['nonce'], 'kavehboard_nonce')) {
        wp_die('Security check failed');
    }
    
    $user_id = get_current_user_id();
    
    if ($user_id) {
        kavehboard_mark_all_notifications_read($user_id);
        wp_send_json_success('All notifications marked as read');
    } else {
        wp_send_json_error('Invalid request');
    }
}

// Hook to register custom post type
add_action('init', 'kavehboard_register_notification_post_type');

/**
 * Register custom post type for notifications
 */
function kavehboard_register_notification_post_type() {
    register_post_type('kaveh_notification', array(
        'labels' => array(
            'name' => __('Notifications', 'kavehTheme'),
            'singular_name' => __('Notification', 'kavehTheme'),
            'menu_name' => __('Notifications', 'kavehTheme'),
            'add_new' => __('Add New Notification', 'kavehTheme'),
            'add_new_item' => __('Add New Notification', 'kavehTheme'),
            'edit_item' => __('Edit Notification', 'kavehTheme'),
            'new_item' => __('New Notification', 'kavehTheme'),
            'view_item' => __('View Notification', 'kavehTheme'),
            'search_items' => __('Search Notifications', 'kavehTheme'),
            'not_found' => __('No notifications found', 'kavehTheme'),
            'not_found_in_trash' => __('No notifications found in trash', 'kavehTheme'),
        ),
        'public' => false,
        'show_ui' => true,
        'show_in_menu' => true,
        'show_in_admin_bar' => true,
        'menu_position' => 25,
        'menu_icon' => 'dashicons-bell',
        'supports' => array('title', 'editor'),
        'has_archive' => false,
        'rewrite' => false,
        'capability_type' => 'post',
        'map_meta_cap' => true,
    ));
    
    // Add meta boxes for notification settings
     add_action('add_meta_boxes', 'kavehboard_add_notification_meta_boxes');
     add_action('save_post', 'kavehboard_save_notification_meta');
}

/**
 * Add meta boxes for notification post type
 */
function kavehboard_add_notification_meta_boxes() {
    add_meta_box(
        'kavehboard_notification_settings',
        __('Notification Settings', 'kavehTheme'),
        'kavehboard_notification_settings_callback',
        'kaveh_notification',
        'normal',
        'high'
    );
}

/**
 * Meta box callback for notification settings
 */
function kavehboard_notification_settings_callback($post) {
    // Add nonce for security
    wp_nonce_field('kavehboard_notification_meta', 'kavehboard_notification_nonce');
    
    // Get current values
    $target_type = get_post_meta($post->ID, '_kaveh_notification_target_type', true) ?: 'all';
    $target_user = get_post_meta($post->ID, '_kaveh_notification_target_user', true);
    $notification_type = get_post_meta($post->ID, '_kaveh_notification_type', true) ?: 'info';
    $action_url = get_post_meta($post->ID, '_kaveh_notification_action_url', true);
    $is_active = get_post_meta($post->ID, '_kaveh_notification_active', true) ?: '1';
    
    ?>
    <table class="form-table">
        <tr>
            <th scope="row">
                <label for="kaveh_notification_target_type"><?php _e('Target Users', 'kavehTheme'); ?></label>
            </th>
            <td>
                <select name="kaveh_notification_target_type" id="kaveh_notification_target_type">
                    <option value="all" <?php selected($target_type, 'all'); ?>><?php _e('All Users', 'kavehTheme'); ?></option>
                    <option value="specific" <?php selected($target_type, 'specific'); ?>><?php _e('Specific User', 'kavehTheme'); ?></option>
                </select>
                <p class="description"><?php _e('Choose who should see this notification.', 'kavehTheme'); ?></p>
            </td>
        </tr>
        <tr id="specific_user_row" style="<?php echo $target_type === 'specific' ? '' : 'display:none;'; ?>">
            <th scope="row">
                <label for="kaveh_notification_target_user"><?php _e('Select User', 'kavehTheme'); ?></label>
            </th>
            <td>
                <?php
                $users = get_users(array('fields' => array('ID', 'display_name')));
                ?>
                <select name="kaveh_notification_target_user" id="kaveh_notification_target_user">
                    <option value=""><?php _e('Select a user...', 'kavehTheme'); ?></option>
                    <?php foreach ($users as $user): ?>
                        <option value="<?php echo esc_attr($user->ID); ?>" <?php selected($target_user, $user->ID); ?>>
                            <?php echo esc_html($user->display_name . ' (ID: ' . $user->ID . ')'); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </td>
        </tr>
        <tr>
            <th scope="row">
                <label for="kaveh_notification_type"><?php _e('Notification Type', 'kavehTheme'); ?></label>
            </th>
            <td>
                <select name="kaveh_notification_type" id="kaveh_notification_type">
                    <option value="info" <?php selected($notification_type, 'info'); ?>><?php _e('Info', 'kavehTheme'); ?></option>
                    <option value="success" <?php selected($notification_type, 'success'); ?>><?php _e('Success', 'kavehTheme'); ?></option>
                    <option value="warning" <?php selected($notification_type, 'warning'); ?>><?php _e('Warning', 'kavehTheme'); ?></option>
                    <option value="error" <?php selected($notification_type, 'error'); ?>><?php _e('Error', 'kavehTheme'); ?></option>
                </select>
            </td>
        </tr>
        <tr>
            <th scope="row">
                <label for="kaveh_notification_action_url"><?php _e('Action URL (Optional)', 'kavehTheme'); ?></label>
            </th>
            <td>
                <input type="url" name="kaveh_notification_action_url" id="kaveh_notification_action_url" value="<?php echo esc_attr($action_url); ?>" class="regular-text" />
                <p class="description"><?php _e('URL to redirect when notification is clicked.', 'kavehTheme'); ?></p>
            </td>
        </tr>
        <tr>
            <th scope="row">
                <label for="kaveh_notification_active"><?php _e('Status', 'kavehTheme'); ?></label>
            </th>
            <td>
                <label>
                    <input type="checkbox" name="kaveh_notification_active" id="kaveh_notification_active" value="1" <?php checked($is_active, '1'); ?> />
                    <?php _e('Active (users can see this notification)', 'kavehTheme'); ?>
                </label>
            </td>
        </tr>
    </table>
    
    <script>
    jQuery(document).ready(function($) {
        $('#kaveh_notification_target_type').change(function() {
            if ($(this).val() === 'specific') {
                $('#specific_user_row').show();
            } else {
                $('#specific_user_row').hide();
            }
        });
    });
    </script>
    <?php
}

/**
 * Save notification meta data
 */
function kavehboard_save_notification_meta($post_id) {
    // Check if this is an autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    
    // Check if this is the correct post type
    if (get_post_type($post_id) !== 'kaveh_notification') {
        return;
    }
    
    // Check nonce
    if (!isset($_POST['kavehboard_notification_nonce']) || !wp_verify_nonce($_POST['kavehboard_notification_nonce'], 'kavehboard_notification_meta')) {
        return;
    }
    
    // Check user permissions
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    
    // Save meta fields
    $fields = array(
        '_kaveh_notification_target_type' => 'kaveh_notification_target_type',
        '_kaveh_notification_target_user' => 'kaveh_notification_target_user',
        '_kaveh_notification_type' => 'kaveh_notification_type',
        '_kaveh_notification_action_url' => 'kaveh_notification_action_url',
        '_kaveh_notification_active' => 'kaveh_notification_active'
    );
    
    foreach ($fields as $meta_key => $post_key) {
        if (isset($_POST[$post_key])) {
            update_post_meta($post_id, $meta_key, sanitize_text_field($_POST[$post_key]));
        } else {
            delete_post_meta($post_id, $meta_key);
        }
    }
}