<?php
/**
 * Plugin Name: Simple Stopwatch Easy to Use
 * Plugin URI:  https://wordpress.org/plugins/simple-stopwatch-easy-to-use/
 * Description: Add a simple, easy-to-use stopwatch or countdown timer to any page or post using a shortcode or block.
 * Version:     1.1.0
 * Author:      itsmeakay
 * Author URI:  https://profiles.wordpress.org/itsmeakay
 * License:     GPL-2.0+
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: simple-stopwatch-easy-to-use
 * Requires PHP: 7.2
 * Requires at least: 5.0
 */

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

define( 'SSETU_VERSION', '1.1.0' );
define( 'SSETU_URL', plugin_dir_url( __FILE__ ) );
define( 'SSETU_DIR', plugin_dir_path( __FILE__ ) );

add_action( 'init', 'ssetu_register_block' );
add_shortcode( 'simple_stopwatch', 'ssetu_render' );
add_action( 'admin_menu', 'ssetu_register_admin_page' );
add_filter( 'plugins_api', 'ssetu_local_plugin_info', 20, 3 );
add_filter( 'plugin_row_meta', 'ssetu_row_meta', 10, 2 );

/**
 * Local-preview only: lets "View Details" show updated readme content
 * immediately on this dev site, without waiting for an SVN release.
 * Has no effect once this runs against the live wordpress.org API.
 */
function ssetu_local_plugin_info( $res, $action, $args ) {
    if ( $action !== 'plugin_information' ) return $res;
    if ( $args->slug !== 'simple-stopwatch-easy-to-use' ) return $res;

    $res = new stdClass();
    $res->name              = 'Simple Stopwatch Easy to Use';
    $res->slug              = 'simple-stopwatch-easy-to-use';
    $res->version           = SSETU_VERSION;
    $res->author            = '<a href="https://profiles.wordpress.org/itsmeakay/">itsmeakay</a>';
    $res->author_profile    = 'https://profiles.wordpress.org/itsmeakay/';
    $res->requires          = '5.0';
    $res->tested            = '7.0';
    $res->requires_php      = '7.2';
    $res->last_updated      = gmdate( 'Y-m-d' );
    $res->short_description = 'Add a simple, easy-to-use stopwatch or countdown timer to any page or post using a shortcode or block.';

    $res->sections = array(
        'description' => '
<p>Simple Stopwatch Easy to Use lets you embed a fully functional stopwatch or countdown timer anywhere on your WordPress site, using either a shortcode or a block.</p>
<h4>Features</h4>
<ul>
    <li>Stopwatch (count up) and countdown timer modes</li>
    <li>Start, Stop, Reset controls</li>
    <li>Lap time recording, with export to a text file</li>
    <li>Optional millisecond display</li>
    <li>Optional sound on start/stop and when a countdown reaches zero</li>
    <li>Optional "remember time after page reload"</li>
    <li>Works as a Gutenberg block or a shortcode</li>
    <li>Multiple stopwatches on the same page work independently</li>
    <li>Customizable color and size</li>
</ul>
<h4>Usage</h4>
<p>Add the "Simple Stopwatch" block, or use the shortcode <code>[simple_stopwatch]</code>.</p>
<p>Example: <code>[simple_stopwatch mode="countdown" from="00:10:00" color="#25D366" sound="yes"]</code></p>
        ',
        'installation' => '
<ol>
    <li>Upload the plugin files to <code>/wp-content/plugins/simple-stopwatch-easy-to-use/</code></li>
    <li>Activate the plugin through the Plugins menu in WordPress</li>
    <li>Add the "Simple Stopwatch" block, or add <code>[simple_stopwatch]</code> to any page or post</li>
</ol>
        ',
        'faq' => '
<p><strong>How do I add the stopwatch to my page?</strong><br>
Use the block inserter and search for "Simple Stopwatch", or add the shortcode <code>[simple_stopwatch]</code> to any page, post, or widget.</p>
<p><strong>Can I use a countdown timer instead of a stopwatch?</strong><br>
Yes — set <code>mode="countdown"</code> and <code>from="00:10:00"</code> in the shortcode, or choose "Countdown timer" in the block settings.</p>
<p><strong>Can I add more than one stopwatch on the same page?</strong><br>
Yes, each one runs independently.</p>
<p><strong>Does it remember the time if I refresh the page?</strong><br>
Only if you enable that option (<code>persist="yes"</code>).</p>
        ',
        'changelog' => '
<h4>1.1.0</h4>
<ul>
    <li>Added countdown timer mode</li>
    <li>Added Gutenberg block (in addition to the shortcode)</li>
    <li>Fixed: multiple stopwatches on the same page now work independently</li>
    <li>Added optional millisecond display, sound, and "remember time after reload"</li>
    <li>Added lap export to a text file</li>
    <li>Added accessibility labels to controls</li>
</ul>
<h4>1.0.0</h4>
<ul><li>Initial release</li></ul>
        ',
        'screenshots' => '
<ol>
    <li><img src="' . SSETU_URL . 'assets/images/screenshot-1.png" alt="Stopwatch running" /><p>The stopwatch running on a page, with lap times and export</p></li>
    <li><img src="' . SSETU_URL . 'assets/images/screenshot-2.png" alt="Shortcode builder" /><p>The shortcode builder under Tools — pick your options and copy the shortcode</p></li>
</ol>
        ',
    );

    $res->screenshots = array(
        array( 'src' => SSETU_URL . 'assets/images/screenshot-1.png', 'caption' => 'The stopwatch running on a page' ),
        array( 'src' => SSETU_URL . 'assets/images/screenshot-2.png', 'caption' => 'The shortcode builder under Tools' ),
    );

    $res->banners = array(
        'low'  => SSETU_URL . 'assets/banner-772x250.png',
        'high' => SSETU_URL . 'assets/banner-1544x500.png',
    );

    $res->icons = array(
        '1x' => SSETU_URL . 'assets/icon-128x128.png',
        '2x' => SSETU_URL . 'assets/icon-256x256.png',
    );

    return $res;
}

function ssetu_row_meta( $links, $file ) {
    if ( $file !== plugin_basename( __FILE__ ) ) return $links;
    $url = admin_url( 'plugin-install.php?tab=plugin-information&plugin=simple-stopwatch-easy-to-use&TB_iframe=true&width=772&height=550' );
    $links[] = '<a href="' . esc_url( $url ) . '" class="thickbox open-plugin-details-modal">' . esc_html__( 'View details', 'simple-stopwatch-easy-to-use' ) . '</a>';
    return $links;
}

function ssetu_register_admin_page() {
    $hook = add_management_page(
        __( 'Simple Stopwatch', 'simple-stopwatch-easy-to-use' ),
        __( 'Simple Stopwatch', 'simple-stopwatch-easy-to-use' ),
        'edit_posts',
        'simple-stopwatch-easy-to-use',
        'ssetu_render_admin_page'
    );
    add_action( 'load-' . $hook, function() {
        add_action( 'admin_enqueue_scripts', function() {
            wp_enqueue_script( 'ssetu-admin', SSETU_URL . 'assets/admin.js', array(), SSETU_VERSION, true );
        } );
    } );
}

function ssetu_render_admin_page() {
    if ( ! current_user_can( 'edit_posts' ) ) return;
    ?>
    <div class="wrap">
        <h1><?php esc_html_e( 'Simple Stopwatch — Easy to Use', 'simple-stopwatch-easy-to-use' ); ?></h1>
        <p><?php esc_html_e( 'Add a stopwatch or countdown timer to any page or post using the block editor or a shortcode.', 'simple-stopwatch-easy-to-use' ); ?></p>

        <h2><?php esc_html_e( 'Using the block', 'simple-stopwatch-easy-to-use' ); ?></h2>
        <p><?php esc_html_e( 'In the block editor, click the + icon and search for "Simple Stopwatch". All options (mode, color, size, sound, etc.) are available in the block settings panel on the right.', 'simple-stopwatch-easy-to-use' ); ?></p>

        <h2><?php esc_html_e( 'Shortcode builder', 'simple-stopwatch-easy-to-use' ); ?></h2>
        <p><?php esc_html_e( 'Choose your options below, then copy the generated shortcode into any page or post.', 'simple-stopwatch-easy-to-use' ); ?></p>

        <table class="form-table" role="presentation" style="max-width:560px">
            <tr>
                <th><label for="ssetu-gen-mode"><?php esc_html_e( 'Mode', 'simple-stopwatch-easy-to-use' ); ?></label></th>
                <td>
                    <select id="ssetu-gen-mode">
                        <option value="stopwatch"><?php esc_html_e( 'Stopwatch (count up)', 'simple-stopwatch-easy-to-use' ); ?></option>
                        <option value="countdown"><?php esc_html_e( 'Countdown timer', 'simple-stopwatch-easy-to-use' ); ?></option>
                    </select>
                </td>
            </tr>
            <tr id="ssetu-gen-from-row" style="display:none">
                <th><label for="ssetu-gen-from"><?php esc_html_e( 'Countdown from', 'simple-stopwatch-easy-to-use' ); ?></label></th>
                <td><input type="text" id="ssetu-gen-from" value="00:10:00" placeholder="HH:MM:SS" class="regular-text"></td>
            </tr>
            <tr>
                <th><label for="ssetu-gen-color"><?php esc_html_e( 'Button color', 'simple-stopwatch-easy-to-use' ); ?></label></th>
                <td><input type="color" id="ssetu-gen-color" value="#2271b1"></td>
            </tr>
            <tr>
                <th><label for="ssetu-gen-size"><?php esc_html_e( 'Size', 'simple-stopwatch-easy-to-use' ); ?></label></th>
                <td>
                    <select id="ssetu-gen-size">
                        <option value="large"><?php esc_html_e( 'Large', 'simple-stopwatch-easy-to-use' ); ?></option>
                        <option value="small"><?php esc_html_e( 'Small', 'simple-stopwatch-easy-to-use' ); ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e( 'Show milliseconds', 'simple-stopwatch-easy-to-use' ); ?></th>
                <td><label><input type="checkbox" id="ssetu-gen-ms"> <?php esc_html_e( 'Yes', 'simple-stopwatch-easy-to-use' ); ?></label></td>
            </tr>
            <tr>
                <th><?php esc_html_e( 'Play sound', 'simple-stopwatch-easy-to-use' ); ?></th>
                <td><label><input type="checkbox" id="ssetu-gen-sound"> <?php esc_html_e( 'Yes', 'simple-stopwatch-easy-to-use' ); ?></label></td>
            </tr>
            <tr>
                <th><?php esc_html_e( 'Remember time after reload', 'simple-stopwatch-easy-to-use' ); ?></th>
                <td><label><input type="checkbox" id="ssetu-gen-persist"> <?php esc_html_e( 'Yes', 'simple-stopwatch-easy-to-use' ); ?></label></td>
            </tr>
        </table>

        <p>
            <input type="text" id="ssetu-gen-output" readonly class="large-text code" style="max-width:560px" value="[simple_stopwatch]">
        </p>
        <p>
            <button type="button" class="button button-primary" id="ssetu-gen-copy"><?php esc_html_e( 'Copy shortcode', 'simple-stopwatch-easy-to-use' ); ?></button>
            <span id="ssetu-gen-copied" style="display:none;color:#15803d;margin-left:8px"><?php esc_html_e( 'Copied!', 'simple-stopwatch-easy-to-use' ); ?></span>
        </p>

        <p style="margin-top:24px;color:#666"><?php esc_html_e( 'Prefer the block editor? Search for "Simple Stopwatch" in the block inserter — all the same options are available there too.', 'simple-stopwatch-easy-to-use' ); ?></p>
    </div>

    <?php
}

function ssetu_register_block() {
    register_block_type( 'ssetu/stopwatch', array(
        'attributes'      => array(
            'mode'     => array( 'type' => 'string', 'default' => 'stopwatch' ),
            'from'     => array( 'type' => 'string', 'default' => '00:05:00' ),
            'color'    => array( 'type' => 'string', 'default' => '#2271b1' ),
            'size'     => array( 'type' => 'string', 'default' => 'large' ),
            'ms'       => array( 'type' => 'boolean', 'default' => false ),
            'sound'    => array( 'type' => 'boolean', 'default' => false ),
            'persist'  => array( 'type' => 'boolean', 'default' => false ),
        ),
        'render_callback' => 'ssetu_render',
        'editor_script'   => 'ssetu-block-editor',
    ) );

    wp_register_script(
        'ssetu-block-editor',
        SSETU_URL . 'assets/block.js',
        array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n' ),
        SSETU_VERSION,
        true
    );
    wp_set_script_translations( 'ssetu-block-editor', 'simple-stopwatch-easy-to-use' );
}

function ssetu_render( $atts ) {
    $atts = shortcode_atts( array(
        'mode'    => 'stopwatch', // stopwatch | countdown
        'from'    => '00:05:00',  // countdown starting point HH:MM:SS
        'color'   => '#2271b1',
        'size'    => 'large',
        'ms'      => 'no',
        'sound'   => 'no',
        'persist' => 'no',
    ), $atts, 'simple_stopwatch' );

    wp_enqueue_style( 'ssetu-style', SSETU_URL . 'assets/stopwatch.css', array(), SSETU_VERSION );
    wp_enqueue_script( 'ssetu-script', SSETU_URL . 'assets/stopwatch.js', array(), SSETU_VERSION, true );

    static $instance = 0;
    $instance++;
    $uid = 'ssetu-' . $instance . '-' . substr( md5( wp_rand() ), 0, 6 );

    $mode       = $atts['mode'] === 'countdown' ? 'countdown' : 'stopwatch';
    $size_class = sanitize_html_class( $atts['size'] );
    $color      = sanitize_hex_color( $atts['color'] ) ?: '#2271b1';
    $show_ms    = in_array( strtolower( $atts['ms'] ), array( 'yes', '1', 'true' ), true );
    $use_sound  = in_array( strtolower( $atts['sound'] ), array( 'yes', '1', 'true' ), true );
    $persist    = in_array( strtolower( $atts['persist'] ), array( 'yes', '1', 'true' ), true );
    $from_secs  = ssetu_time_to_seconds( $atts['from'] );

    ob_start();
    ?>
    <div class="ssetu-wrap ssetu-<?php echo esc_attr( $size_class ); ?>"
         id="<?php echo esc_attr( $uid ); ?>"
         data-mode="<?php echo esc_attr( $mode ); ?>"
         data-from="<?php echo esc_attr( $from_secs ); ?>"
         data-ms="<?php echo $show_ms ? '1' : '0'; ?>"
         data-sound="<?php echo $use_sound ? '1' : '0'; ?>"
         data-persist="<?php echo $persist ? '1' : '0'; ?>">
        <div class="ssetu-display" role="timer" aria-live="polite"><?php echo esc_html( $mode === 'countdown' ? gmdate( 'H:i:s', $from_secs ) : '00:00:00' ); ?></div>
        <div class="ssetu-laps"></div>
        <div class="ssetu-controls">
            <button type="button" class="ssetu-btn ssetu-start" style="background:<?php echo esc_attr( $color ); ?>" aria-label="<?php esc_attr_e( 'Start', 'simple-stopwatch-easy-to-use' ); ?>"><?php esc_html_e( 'Start', 'simple-stopwatch-easy-to-use' ); ?></button>
            <button type="button" class="ssetu-btn ssetu-stop" disabled aria-label="<?php esc_attr_e( 'Stop', 'simple-stopwatch-easy-to-use' ); ?>"><?php esc_html_e( 'Stop', 'simple-stopwatch-easy-to-use' ); ?></button>
            <button type="button" class="ssetu-btn ssetu-reset" aria-label="<?php esc_attr_e( 'Reset', 'simple-stopwatch-easy-to-use' ); ?>"><?php esc_html_e( 'Reset', 'simple-stopwatch-easy-to-use' ); ?></button>
            <button type="button" class="ssetu-btn ssetu-lap" disabled style="background:<?php echo esc_attr( $color ); ?>" aria-label="<?php esc_attr_e( 'Lap', 'simple-stopwatch-easy-to-use' ); ?>"><?php esc_html_e( 'Lap', 'simple-stopwatch-easy-to-use' ); ?></button>
            <button type="button" class="ssetu-btn ssetu-export" style="display:none" aria-label="<?php esc_attr_e( 'Export laps', 'simple-stopwatch-easy-to-use' ); ?>"><?php esc_html_e( 'Export', 'simple-stopwatch-easy-to-use' ); ?></button>
        </div>
    </div>
    <?php
    return ob_get_clean();
}

/** Convert "HH:MM:SS" or "MM:SS" to total seconds */
function ssetu_time_to_seconds( $time_str ) {
    $parts = array_map( 'absint', explode( ':', $time_str ) );
    $parts = array_reverse( $parts );
    $secs  = ( $parts[0] ?? 0 ) + ( ( $parts[1] ?? 0 ) * 60 ) + ( ( $parts[2] ?? 0 ) * 3600 );
    return max( 0, $secs );
}
