<?php
/**
 * Schedule Page
 *
 * @package AIContentGenerator
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Include License Manager
if ( ! class_exists( 'AICG\License_Manager' ) ) {
    require_once ROIDAICO_PLUGIN_DIR . 'includes/class-license-manager.php';
}

// Check Pro status
$is_pro = \AICG\License_Manager::is_pro();
$upgrade_url = \AICG\License_Manager::get_upgrade_url();
$can_add_schedule = \AICG\License_Manager::can_add_schedule();

// Get schedules
global $wpdb;
$table = $wpdb->prefix . 'roidaico_schedules';
$schedules = $wpdb->get_results("SELECT * FROM $table ORDER BY created_at DESC");
$schedule_count = count($schedules);

// Get categories and authors
$categories = get_categories(array('hide_empty' => false));
$authors = get_users(array('capability' => 'edit_posts', 'fields' => array('ID', 'display_name')));
$post_types = get_post_types(array('public' => true), 'objects');

// Days of week
$days = array(
    'mon' => __('Monday', 'roidnet-ai-content-generator'),
    'tue' => __('Tuesday', 'roidnet-ai-content-generator'),
    'wed' => __('Wednesday', 'roidnet-ai-content-generator'),
    'thu' => __('Thursday', 'roidnet-ai-content-generator'),
    'fri' => __('Friday', 'roidnet-ai-content-generator'),
    'sat' => __('Saturday', 'roidnet-ai-content-generator'),
    'sun' => __('Sunday', 'roidnet-ai-content-generator'),
);
?>

<div class="wrap roidaico-wrap">
    <h1>
        <?php esc_html_e('Publishing Schedules', 'roidnet-ai-content-generator'); ?>
        <?php if ( $can_add_schedule ) : ?>
            <button type="button" class="page-title-action" id="roidaico-add-schedule-btn">
                <?php esc_html_e('Add Schedule', 'roidnet-ai-content-generator'); ?>
            </button>
        <?php else : ?>
            <a href="<?php echo esc_url( $upgrade_url ); ?>" class="page-title-action" style="background: linear-gradient(135deg, #667eea, #764ba2); color: #fff; border: none;">
                <?php esc_html_e('Upgrade to Pro for More Schedules', 'roidnet-ai-content-generator'); ?>
            </a>
        <?php endif; ?>
    </h1>

    <?php if ( ! $is_pro && $schedule_count >= 1 ) : ?>
    <div class="roidaico-upgrade-prompt" style="margin: 20px 0;">
        <h3><?php esc_html_e('Want Multiple Schedules?', 'roidnet-ai-content-generator'); ?></h3>
        <p><?php esc_html_e('Free version allows 1 schedule. Upgrade to Pro for unlimited schedules!', 'roidnet-ai-content-generator'); ?></p>
        <a href="<?php echo esc_url( $upgrade_url ); ?>" class="button"><?php esc_html_e('Upgrade Now', 'roidnet-ai-content-generator'); ?></a>
    </div>
    <?php endif; ?>

    <!-- Add/Edit Schedule Modal -->
    <div id="roidaico-schedule-modal" class="roidaico-modal" style="display: none;">
        <div class="roidaico-modal-content roidaico-modal-large">
            <span class="roidaico-modal-close">&times;</span>
            <h2 id="roidaico-schedule-modal-title">
                <?php esc_html_e('Add Schedule', 'roidnet-ai-content-generator'); ?>
            </h2>
            <form id="roidaico-schedule-form">
                <input type="hidden" id="schedule-id" name="id" value="">

                <table class="form-table">
                    <tr>
                        <th><label for="schedule-name">
                                <?php esc_html_e('Schedule Name', 'roidnet-ai-content-generator'); ?>
                            </label></th>
                        <td>
                            <input type="text" id="schedule-name" name="name" class="regular-text" required>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="schedule-category">
                                <?php esc_html_e('Category', 'roidnet-ai-content-generator'); ?>
                            </label></th>
                        <td>
                            <select id="schedule-category" name="category_id">
                                <?php foreach ($categories as $category): ?>
                                    <option value="<?php echo esc_attr($category->term_id); ?>">
                                        <?php echo esc_html($category->name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <p class="description">
                                <?php esc_html_e('Keywords from this category queue will be used.', 'roidnet-ai-content-generator'); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th>
                            <?php esc_html_e('Days', 'roidnet-ai-content-generator'); ?>
                        </th>
                        <td>
                            <div class="roidaico-days-picker">
                                <?php foreach ($days as $day_key => $day_name): ?>
                                    <label class="roidaico-day-checkbox">
                                        <input type="checkbox" name="days[]" value="<?php echo esc_attr($day_key); ?>">
                                        <span>
                                            <?php echo esc_html($day_name); ?>
                                        </span>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <th>
                            <?php esc_html_e('Times', 'roidnet-ai-content-generator'); ?>
                        </th>
                        <td>
                            <div id="roidaico-times-container">
                                <div class="roidaico-time-slot">
                                    <input type="time" name="times[]" value="09:00" required>
                                    <button type="button" class="button roidaico-remove-time" style="display: none;">
                                        <span class="dashicons dashicons-no"></span>
                                    </button>
                                </div>
                            </div>
                            <button type="button" class="button" id="roidaico-add-time">
                                <span class="dashicons dashicons-plus"></span>
                                <?php esc_html_e('Add Time', 'roidnet-ai-content-generator'); ?>
                            </button>
                            <p class="description">
                                <?php esc_html_e('Minimum 15 minutes between times.', 'roidnet-ai-content-generator'); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="schedule-post-type">
                                <?php esc_html_e('Post Type', 'roidnet-ai-content-generator'); ?>
                            </label></th>
                        <td>
                            <select id="schedule-post-type" name="post_type">
                                <?php foreach ($post_types as $pt):
                                    if ($pt->name === 'attachment')
                                        continue;
                                    ?>
                                    <option value="<?php echo esc_attr($pt->name); ?>">
                                        <?php echo esc_html($pt->labels->singular_name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="schedule-author">
                                <?php esc_html_e('Author', 'roidnet-ai-content-generator'); ?>
                            </label></th>
                        <td>
                            <select id="schedule-author" name="author_id">
                                <?php foreach ($authors as $author): ?>
                                    <option value="<?php echo esc_attr($author->ID); ?>">
                                        <?php echo esc_html($author->display_name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>

                    <tr>
                        <th>
                            <?php esc_html_e('Enabled', 'roidnet-ai-content-generator'); ?>
                        </th>
                        <td>
                            <label>
                                <input type="checkbox" name="enabled" value="1" checked>
                                <?php esc_html_e('Enable this schedule', 'roidnet-ai-content-generator'); ?>
                            </label>
                        </td>
                    </tr>
                </table>

                <p class="submit">
                    <button type="submit" class="button button-primary">
                        <?php esc_html_e('Save Schedule', 'roidnet-ai-content-generator'); ?>
                    </button>
                </p>
            </form>
        </div>
    </div>

    <!-- Schedules List -->
    <?php if (!empty($schedules)): ?>
        <div class="roidaico-schedules-grid">
            <?php foreach ($schedules as $schedule):
                $schedule_days = explode(',', $schedule->days);
                $schedule_times = json_decode($schedule->times, true);
                $category = get_category($schedule->category_id);
                $author = get_user_by('id', $schedule->author_id);

                // Calculate next run
                $scheduler = new AICG\Scheduler(new AICG\Keyword_Manager(), new AICG\Content_Generator(
                    new AICG\Ai_Client(),
                    new AICG\Pexels_Api(),
                    new AICG\Quality_Checker()
                ));
                $next_run = $scheduler->get_next_run($schedule->id);
                ?>
                <div class="roidaico-schedule-card <?php echo $schedule->enabled ? '' : 'roidaico-schedule-disabled'; ?>"
                    data-id="<?php echo esc_attr($schedule->id); ?>">
                    <div class="roidaico-schedule-header">
                        <h3>
                            <?php echo esc_html($schedule->name); ?>
                        </h3>
                        <div class="roidaico-schedule-toggle">
                            <label class="roidaico-switch">
                                <input type="checkbox" class="roidaico-toggle-schedule"
                                    data-id="<?php echo esc_attr($schedule->id); ?>" <?php checked($schedule->enabled, 1); ?>>
                                <span class="roidaico-slider"></span>
                            </label>
                        </div>
                    </div>

                    <div class="roidaico-schedule-body">
                        <div class="roidaico-schedule-info">
                            <span class="dashicons dashicons-category"></span>
                            <?php echo esc_html(($category && !is_wp_error($category)) ? $category->name : __('Uncategorized', 'roidnet-ai-content-generator')); ?>
                        </div>

                        <div class="roidaico-schedule-info">
                            <span class="dashicons dashicons-calendar-alt"></span>
                            <?php
                            $day_names = array();
                            foreach ($schedule_days as $d) {
                                if (isset($days[$d])) {
                                    $day_names[] = substr($days[$d], 0, 3);
                                }
                            }
                            echo esc_html(implode(', ', $day_names));
                            ?>
                        </div>

                        <div class="roidaico-schedule-info">
                            <span class="dashicons dashicons-clock"></span>
                            <?php echo esc_html(implode(', ', $schedule_times ?: array())); ?>
                        </div>

                        <div class="roidaico-schedule-info">
                            <span class="dashicons dashicons-admin-users"></span>
                            <?php echo esc_html($author ? $author->display_name : __('Unknown', 'roidnet-ai-content-generator')); ?>
                        </div>

                        <?php if ($next_run && $schedule->enabled): ?>
                            <div class="roidaico-schedule-next-run">
                                <strong>
                                    <?php esc_html_e('Next run:', 'roidnet-ai-content-generator'); ?>
                                </strong>
                                <?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($next_run))); ?>
                            </div>
                        <?php endif; ?>

                        <!-- Last Log Entry -->
                        <?php
                        $last_log = $wpdb->get_row($wpdb->prepare(
                            "SELECT * FROM {$wpdb->prefix}roidaico_logs WHERE schedule_id = %d ORDER BY created_at DESC LIMIT 1",
                            $schedule->id
                        ));
                        if ($last_log):
                            ?>
                            <div class="roidaico-schedule-last-status roidaico-status-<?php echo esc_attr($last_log->status); ?>">
                                <strong><?php esc_html_e('Last Result:', 'roidnet-ai-content-generator'); ?></strong>
                                <span><?php echo esc_html($last_log->message); ?></span>
                                <small>(<?php echo esc_html(mysql2date(get_option('time_format'), $last_log->created_at)); ?>)</small>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="roidaico-schedule-footer">
                        <button type="button" class="button roidaico-edit-schedule" data-id="<?php echo esc_attr($schedule->id); ?>"
                            data-schedule='<?php echo esc_attr(wp_json_encode($schedule)); ?>'>
                            <?php esc_html_e('Edit', 'roidnet-ai-content-generator'); ?>
                        </button>
                        <button type="button" class="button roidaico-delete-schedule"
                            data-id="<?php echo esc_attr($schedule->id); ?>">
                            <?php esc_html_e('Delete', 'roidnet-ai-content-generator'); ?>
                        </button>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <div class="roidaico-empty-state">
            <span class="dashicons dashicons-calendar-alt"></span>
            <h3>
                <?php esc_html_e('No Schedules Yet', 'roidnet-ai-content-generator'); ?>
            </h3>
            <p>
                <?php esc_html_e('Create a schedule to automatically publish content at specific times.', 'roidnet-ai-content-generator'); ?>
            </p>
            <button type="button" class="button button-primary button-hero" id="roidaico-add-first-schedule">
                <?php esc_html_e('Create Your First Schedule', 'roidnet-ai-content-generator'); ?>
            </button>
        </div>
    <?php endif; ?>
</div>