<?php
/**
 * Cron Settings Display
 */

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

$cron = new CCSPLLMS_Cron();

// Handle form submission
if ( isset( $_POST['update_cron'] ) ) {
    // Verify nonce.
    $nonce = isset( $_POST['ccspllms_cron_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['ccspllms_cron_nonce'] ) ) : '';
    if ( ! wp_verify_nonce( $nonce, 'ccspllms_cron' ) ) {
        return;
    }

    // Sanitize inputs.
    $frequency = isset( $_POST['cron_frequency'] ) ? sanitize_text_field( wp_unslash( $_POST['cron_frequency'] ) ) : '';
    $time      = isset( $_POST['cron_time'] ) ? sanitize_text_field( wp_unslash( $_POST['cron_time'] ) ) : '';

    // Update schedule.
    $result = $cron->update_schedule( $frequency, $time );

    // Feedback messages (safe HTML).
    if ( $result ) {
        echo wp_kses_post(
            '<div class="ccspllms_alert success">Cron schedule updated successfully!</div>'
        );
    } else {
        echo wp_kses_post(
            '<div class="ccspllms_alert error">Failed to update cron schedule.</div>'
        );
    }
}


// Handle force run form submission
if ( isset( $_POST['force_run_cron'] ) ) {
    // Verify nonce.
    $nonce = isset( $_POST['ccspllms_cron_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['ccspllms_cron_nonce'] ) ) : '';
    if ( ! wp_verify_nonce( $nonce, 'ccspllms_cron' ) ) {
        return;
    }

    // Run force regeneration.
    $result = $cron->force_regeneration();

    // Output safe messages.
    if ( $result ) {
        echo wp_kses_post(
            '<div class="ccspllms_alert success">Generation scheduled to run in a few seconds!</div>'
        );
    } else {
        echo wp_kses_post(
            '<div class="ccspllms_alert error">Failed to schedule generation.</div>'
        );
    }
}


$current_frequency = get_option('ccspllms_cron_frequency', 'daily');
$current_time = get_option('ccspllms_cron_time', '02:00');
$next_scheduled = $cron->get_next_scheduled();
?>

<div class="ccspllms_container">
    
    <div class="ccspllms_header">
        <div class="ccspllmshead_left">
            <div class="ccspllmshead_logo">
            <img src="<?php echo esc_html(CCSPLLMS_PLUGIN_URL . 'assets/cloudcusplogo.svg'); ?>" alt="Logo" class="ccspllms_logo">
            </div>
            <div class="ccspllmshead_text"><h1>LLMS.txt  Generator</h1></div>
        </div>
        <div class="ccspllmshead_right">
             <h1><i class="fas fa-clock"></i> Cron Settings</h1>
        <p>Configure automatic file generation schedule</p>
        </div>
        
    </div>

    <div class="ccspllms_content">
        <div class="ccspllms_card">
            <h3>Current Schedule</h3>
            <table class="ccspllms_table">
                <tr>
                    <td>Status</td>
                    <td><?php echo $current_frequency !== 'disabled' ? '<span class="status-active">Active</span>' : '<span class="status-inactive">Disabled</span>'; ?></td>
                </tr>
                <tr>
                    <td>Frequency</td>
                    <td>
                        <?php echo esc_html(ucwords(str_replace('_', ' ', str_replace('ccspllms', '', $current_frequency)))); ?>
                    </td>

                </tr>
                <tr>
                    <td>Time</td>
                    <td><?php echo esc_html($current_time); ?></td>
                </tr>
                <tr>
                    <td>Next Run</td>
                    <td><?php echo esc_html($next_scheduled ? gmdate('M j, Y H:i:s', strtotime($next_scheduled)) : 'Not scheduled'); ?></td>
                </tr>
            </table>
        </div>

        <form method="post">
            <?php wp_nonce_field('ccspllms_cron', 'ccspllms_cron_nonce'); ?>
            
            <div class="ccspllms_card">
                <h3>Schedule Settings</h3>
                
                <table class="form-table">
                    <tr>
                        <th scope="row">Frequency</th>
                        <td>
                            <select name="cron_frequency">
                                <option value="disabled" <?php selected($current_frequency, 'disabled'); ?>>Disabled</option>
                                <option value="ccspllms_hourly" <?php selected($current_frequency, 'ccspllms_hourly'); ?>>Every Hour</option>
                                <option value="ccspllms_twice_daily" <?php selected($current_frequency, 'ccspllms_twice_daily'); ?>>Twice Daily</option>
                                <option value="daily" <?php selected($current_frequency, 'daily'); ?>>Daily</option>
                                <option value="ccspllms_weekly" <?php selected($current_frequency, 'ccspllms_weekly'); ?>>Weekly</option>
                            </select>
                            <p class="description">How often to automatically regenerate the LLMS.txt file</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">Time</th>
                        <td>
                            <input type="time" name="cron_time" value="<?php echo esc_attr($current_time); ?>">
                            <p class="description">What time to run the generation (24-hour format)</p>
                        </td>
                    </tr>
                </table>
            </div>

            <p class="submit">
                <input type="submit" name="update_cron" class="ccspllms_button" value="Update Schedule">
                <button type="submit" name="force_run_cron" id="force_run" class="ccspllms_button">Force Run Now</button> <i class="fas fa-exclamation-triangle" style="color: #ff1807; font-size: 1rem;"> This will Clear any existing scheduled generation and run it immediately.</i>
            </p>
        </form>

        

        <div class="ccspllms_card">
            <h3>Generation History</h3>
            <?php
            $history = $cron->get_generation_history(20);
            if ($history) {
                ?>
                <form id="ccspllms-history-form">
                    <?php wp_nonce_field('ccspllms_delete_history', 'ccspllms_delete_history_nonce'); ?>
                    <button type="button" id="ccspllms-delete-selected" class="ccspllms_button" style="margin-bottom:10px;">Delete Selected</button>
                    <table class="ccspllms_table" id="ccspllms-history-table">
                        <thead>
                            <tr>
                                <th><input type="checkbox" id="ccspllms-select-all"></th>
                                <th>Date</th>
                                <th>Trigger</th>
                                <th>Status</th>
                                <th>Posts Count</th>
                                <th>File Size</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php
                        foreach ( $history as $entry ) {
                            $status   = $entry->success
                                ? '<span class="status-success">Success</span>'
                                : '<span class="status-error">Failed</span>';

                            $file_size = $entry->file_size ? size_format( $entry->file_size ) : 'N/A';
                            $row_id    = esc_attr( $entry->id ); 

                            echo '<tr data-row-id="' . esc_html( $row_id ) . '">';
                            echo '<td><input type="checkbox" class="ccspllms-row-checkbox" value="' . esc_html( $row_id ) . '"></td>';
                            echo '<td>' . esc_html( gmdate( 'M j, Y H:i:s', strtotime( $entry->generated_at ) ) ) . '</td>';
                            echo '<td>' . esc_html( ucfirst( $entry->trigger_type ) ) . '</td>';
                            echo '<td>' . wp_kses_post( $status ) . '</td>';
                            echo '<td>' . esc_html( $entry->posts_count ?? 'N/A' ) . '</td>';
                            echo '<td>' . esc_html( $file_size ) . '</td>';
                            echo '<td><button type="button" class="ccspllms-delete-single ccspllms_button" data-row-id="' . esc_html( $row_id ) . '">Delete</button></td>';
                            echo '</tr>';
                        }

                        ?>
                        </tbody>
                    </table>
                </form>
                <?php
            } else {
                echo '<p>No generation history available.</p>';
            }
            ?>
        </div>


    </div>
</div>