<?php

/**
 * Plugin Name: My Trail Camera
 * Plugin URI:  https://mytrailcamera.pro/
 * Description: Trail camera management with anti-theft protection. Track deployments, estimate battery life, generate honeypot bait files, and get notified when a stolen camera is detected.
 * Version: 8.2.6
 * Author: w1k
 * Author URI: https://mytrailcamera.pro/
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: my-trail-camera
 * Domain Path: /languages
 * Requires at least: 5.8
 * Requires PHP: 7.4
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// MTC — All plugin elements use the "mtcam_" prefix (My Trail Camera).
// MTC — Tables: mtcam_detections, mtcam_cameras, mtcam_location_reviews.
// MTC — REST: sd-tracker/v1 kept as backward-compatible alias for deployed bait files.
if ( !function_exists( 'mtcam_fs' ) ) {
    // Create a helper function for easy SDK access.
    function mtcam_fs() {
        global $mtcam_fs;
        if ( !isset( $mtcam_fs ) ) {
            // Include Freemius SDK.
            require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';
            $mtcam_fs = fs_dynamic_init( array(
                'id'               => '24977',
                'slug'             => 'my-trail-camera',
                'type'             => 'plugin',
                'public_key'       => 'pk_bfc9d1b9a5bbea2330db9e2082ba0',
                'is_premium'       => false,
                'is_premium_only'  => false,
                'has_addons'       => false,
                'has_paid_plans'   => true,
                'is_org_compliant' => true,
                'menu'             => array(
                    'slug'       => 'mtcam-dashboard',
                    'first-path' => 'admin.php?page=mtcam-dashboard',
                    'account'    => true,
                    'support'    => false,
                    'pricing'    => true,
                ),
                'is_live'          => true,
            ) );
        }
        return $mtcam_fs;
    }

    // Init Freemius.
    mtcam_fs();
    // Signal that SDK was initiated.
    do_action( 'mtcam_fs_loaded' );
    // Hook uninstall cleanup to Freemius so uninstall feedback is sent.
    mtcam_fs()->add_action( 'after_uninstall', 'mtcam_fs_uninstall_cleanup' );
}
/**
 * Clean up all plugin data on uninstall (called by Freemius after_uninstall).
 */
function mtcam_fs_uninstall_cleanup() {
    global $wpdb, $wp_filesystem;
    // Drop custom tables.
    $tables = array(
        'mtcam_cameras',
        'mtcam_location_reviews',
        'mtcam_detections',
    );
    foreach ( $tables as $table ) {
        mtcam_db_query( 'DROP TABLE IF EXISTS `' . esc_sql( $wpdb->prefix . $table ) . '`' );
    }
    wp_cache_flush();
    // Also drop legacy tables in case prefix migration never ran.
    $legacy_tables = array('sd_tracker', 'sd_tracker_phones', 'thor_cameras', 'thor_timeline', 'thor_location_reviews');
    foreach ( $legacy_tables as $table ) {
        mtcam_db_query( 'DROP TABLE IF EXISTS `' . esc_sql( $wpdb->prefix . $table ) . '`' );
    }
    // Delete plugin options (mtcam_* plus legacy sd_tracker_* and thor_*).
    $options = mtcam_db_get_col( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s OR option_name LIKE %s", $wpdb->esc_like( 'mtcam_' ) . '%', $wpdb->esc_like( 'sd_tracker_' ) . '%', $wpdb->esc_like( 'thor_' ) . '%' ) );
    foreach ( $options as $option ) {
        delete_option( $option );
    }
    // Delete transients (mtcam_*).
    $transients = mtcam_db_get_col( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s", '_transient_' . $wpdb->esc_like( 'mtcam_' ) . '%' ) );
    foreach ( $transients as $transient ) {
        delete_transient( str_replace( '_transient_', '', $transient ) );
    }
    // Delete uploaded files via WP_Filesystem.
    $upload_dir = wp_upload_dir();
    $dirs = array($upload_dir['basedir'] . '/mtcam_cameras', $upload_dir['basedir'] . '/mtcam_temp', $upload_dir['basedir'] . '/mtcam-tmp');
    require_once ABSPATH . 'wp-admin/includes/file.php';
    WP_Filesystem();
    if ( $wp_filesystem ) {
        foreach ( $dirs as $dir ) {
            if ( $wp_filesystem->is_dir( $dir ) ) {
                $wp_filesystem->delete( $dir, true );
            }
        }
    }
}

// CENTRALIZED VERSION MANAGEMENT
// Update this single line for all version changes across the plugin
// Updated security (HMAC signature, nonce token, rate limiting, antispoof
define( 'MTCAM_VERSION', '8.2.6' );
// Load new service files
require_once plugin_dir_path( __FILE__ ) . 'includes/mtc-db.php';
require_once plugin_dir_path( __FILE__ ) . 'includes/cameras-repository.php';
require_once plugin_dir_path( __FILE__ ) . 'includes/battery-presets.php';
require_once plugin_dir_path( __FILE__ ) . 'includes/class-bait-service.php';
require_once plugin_dir_path( __FILE__ ) . 'includes/class-import-export-service.php';
// Load traits before class definition
require_once plugin_dir_path( __FILE__ ) . 'admin/class-camera-admin-handlers.php';
require_once plugin_dir_path( __FILE__ ) . 'admin/class-admin-extras.php';
require_once plugin_dir_path( __FILE__ ) . 'admin/cameras-actions.php';
require_once plugin_dir_path( __FILE__ ) . 'thor/detections-actions.php';
/**
 * Main plugin class.
 *
 * @method void   dashboard_page()              Dashboard with camera list/edit/detail (Mtcam_Cameras_Actions)
 * @method void   add_camera_page()             Add Camera page (Mtcam_Cameras_Actions)
 * @method void   locations_page()              Locations admin page (Mtcam_Cameras_Actions)
 * @method void   settings_page()               Settings page with tabs (Mtcam_Cameras_Actions)
 * @method string stolen_cameras_shortcode($atts) Shortcode [mtcam_stolen_cameras] (Mtcam_Cameras_Actions)
 * @method string active_cameras_shortcode($atts) Shortcode [mtcam_active_cameras] (Mtcam_Cameras_Actions)
 * @method void   admin_page()                  Theft detection records page (Mtcam_Detections_Actions)
 * @method void   handle_pdf_export()           PDF evidence export handler (Mtcam_Detections_Actions) (PRO)
 * @method array  get_camera_info($device_id)   Get camera data by device ID (Mtcam_Detections_Actions)
 * @method array  calculate_recovery_chance($log) Recovery probability scoring (Mtcam_Detections_Actions)
 * @method array  get_detection_counts()        Batch detection counts per camera (Mtcam_Detections_Actions)
 * @method string public_logs_shortcode($atts)  Shortcode [mtcam_public_logs] (Mtcam_Detections_Actions)
 */
class My_Trail_Camera {
    use Mtcam_Cameras_Actions;
    use Mtcam_Detections_Actions;
    use Mtcam_Admin_Extras;
    private $table_name;

    private $version;

    private $options_cache = [];

    private $plugin_file;

    private $data_collector = null;

    private $bait_service = null;

    private $import_export = null;

    private $camera_handlers = null;

    public $admin_notice = null;

    public function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'mtcam_detections';
        $this->version = MTCAM_VERSION;
        $this->plugin_file = __FILE__;
        // ================================================================
        // INCLUDES — shared functions
        // ================================================================
        require_once plugin_dir_path( __FILE__ ) . 'includes/labels.php';
        require_once plugin_dir_path( __FILE__ ) . 'includes/core-helpers.php';
        $profiles_path = plugin_dir_path( __FILE__ ) . 'includes/camera-profiles.php';
        if ( file_exists( $profiles_path ) ) {
            require_once $profiles_path;
        }
        require_once plugin_dir_path( __FILE__ ) . 'includes/install.php';
        // ================================================================
        // ADMIN — camera management
        // ================================================================
        require_once plugin_dir_path( __FILE__ ) . 'admin/cameras-helpers.php';
        // render helpers (DB layer in cameras-repository.php)
        require_once plugin_dir_path( __FILE__ ) . 'admin/cameras-battery.php';
        require_once plugin_dir_path( __FILE__ ) . 'admin/cameras-maintenance.php';
        require_once plugin_dir_path( __FILE__ ) . 'includes/bait-builder.php';
        require_once plugin_dir_path( __FILE__ ) . 'admin/locations-helpers.php';
        // ================================================================
        // MTC — theft detection
        // ================================================================
        require_once plugin_dir_path( __FILE__ ) . 'thor/detections-helpers.php';
        $dc_path = plugin_dir_path( __FILE__ ) . 'thor/class-data-collector.php';
        if ( file_exists( $dc_path ) ) {
            require_once $dc_path;
            $this->data_collector = new Mtcam_Data_Collector($this);
        } else {
            add_action( 'admin_notices', function () {
                echo '<div class="notice notice-error"><p>';
                echo esc_html__( 'My Trail Camera: Detection module (class-data-collector.php) is missing. The REST API will not work. Please reinstall the plugin.', 'my-trail-camera' );
                echo '</p></div>';
            } );
        }
        // ================================================================
        // SERVICES — refactored from cameras-actions.php
        // ================================================================
        $this->bait_service = new Mtcam_Bait_Service();
        $this->import_export = new Mtcam_Import_Export_Service($this);
        $this->camera_handlers = new Mtcam_Camera_Admin_Handlers($this, $this->import_export);
        $this->register_hooks();
    }

    /**
     * Register all WordPress hooks, filters, and shortcodes.
     */
    private function register_hooks() {
        register_activation_hook( __FILE__, array($this, 'install') );
        add_action( 'plugins_loaded', array($this, 'check_version') );
        add_action( 'rest_api_init', array($this, 'register_api_routes') );
        add_action( 'admin_menu', array($this, 'add_admin_menu') );
        add_action( 'admin_init', array($this, 'handle_detection_actions') );
        add_action( 'admin_init', array($this, 'add_privacy_policy') );
        add_action( 'admin_init', array($this->bait_service, 'handle_download') );
        add_action( 'admin_init', array($this->camera_handlers, 'handle_camera_actions') );
        add_action( 'current_screen', array($this, 'send_security_headers') );
        add_action( 'admin_enqueue_scripts', array($this, 'enqueue_styles') );
        add_action( 'wp_dashboard_setup', array($this, 'add_dashboard_widget') );
        add_action( 'admin_bar_menu', array($this, 'add_admin_bar_node'), 80 );
        add_action( 'admin_notices', array($this, 'render_onboarding_checklist') );
        add_action( 'wp_ajax_mtcam_dismiss_onboarding', array($this, 'ajax_dismiss_onboarding') );
        add_action( 'admin_notices', array($this, 'render_deprecation_notice') );
        add_action( 'wp_ajax_mtcam_dismiss_deprecation', array($this, 'ajax_dismiss_deprecation') );
        add_action( 'current_screen', array($this, 'add_help_tabs') );
        add_filter( 'site_status_tests', array($this, 'register_site_health_tests') );
        add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array($this, 'add_action_links') );
        add_shortcode( 'mtcam_public_logs', array($this, 'public_logs_shortcode') );
        add_shortcode( 'mtcam_stolen_cameras', array($this, 'stolen_cameras_shortcode') );
        add_shortcode( 'mtcam_active_cameras', array($this, 'active_cameras_shortcode') );
    }

    /**
     * Send security headers on plugin admin pages.
     */
    public function send_security_headers() {
        $screen = get_current_screen();
        if ( !$screen || strpos( $screen->id, 'mtcam' ) === false ) {
            return;
        }
        if ( !headers_sent() ) {
            header( 'X-Content-Type-Options: nosniff' );
            header( 'X-Frame-Options: SAMEORIGIN' );
            header( 'Referrer-Policy: strict-origin-when-cross-origin' );
        }
    }

    public function enqueue_styles( $hook ) {
        // Only load on our own admin pages
        if ( strpos( $hook, 'mtcam' ) === false ) {
            return;
        }
        wp_enqueue_style(
            'mtcam-admin',
            plugin_dir_url( __FILE__ ) . 'assets/mtcam-admin.css',
            array(),
            $this->version
        );
        wp_enqueue_script(
            'mtc-admin-js',
            plugin_dir_url( __FILE__ ) . 'assets/mtc-admin.js',
            array(),
            $this->version,
            true
        );
        if ( strpos( $hook, 'mtcam-locations' ) !== false ) {
            wp_enqueue_style(
                'leaflet',
                plugin_dir_url( __FILE__ ) . 'assets/leaflet.css',
                array(),
                '1.9.4'
            );
            wp_enqueue_script(
                'leaflet',
                plugin_dir_url( __FILE__ ) . 'assets/leaflet.js',
                array(),
                '1.9.4',
                true
            );
        }
        // Pass camera profiles to JS for form prefill
        $localize = array();
        if ( function_exists( 'mtcam_get_camera_profiles' ) ) {
            $profiles = mtcam_get_camera_profiles();
            $localize['profiles'] = $profiles;
        }
        if ( function_exists( 'mtcam_get_all_power_types' ) ) {
            $localize['powerTypes'] = mtcam_get_all_power_types();
        }
        if ( function_exists( 'mtcam_get_battery_presets' ) ) {
            $localize['batteryPresets'] = mtcam_get_battery_presets();
        }
        $localize['i18n'] = array(
            'copied'             => __( 'Copied!', 'my-trail-camera' ),
            'confirmDelete'      => __( 'Are you sure you want to delete?', 'my-trail-camera' ),
            'duplicateId'        => __( 'Camera with this ID already exists!', 'my-trail-camera' ),
            'customCamera'       => __( 'Custom camera (manual entry)', 'my-trail-camera' ),
            'noResults'          => __( 'No models found', 'my-trail-camera' ),
            'capacityPreview'    => /* translators: 1: cell count, 2: mAh per cell, 3: total mAh, 4: voltage */ __( '%1$d × %2$d mAh = %3$d mAh @ %4$s V', 'my-trail-camera' ),
        );
        $localize['ajaxUrl'] = admin_url( 'admin-ajax.php' );
        $localize['camIdNonce'] = wp_create_nonce( 'mtcam_cam_id_nonce' );
        wp_localize_script( 'mtc-admin-js', 'mtcamData', $localize );
    }

    public function get_plugin_file() {
        return $this->plugin_file;
    }

    private function get_cameras() {
        return mtcam_get_cameras();
    }

    // ============================================================================
    // OPTIMIZATION: CACHE LAYER
    // ============================================================================
    /**
     * Cached get_option — queries the database only once
     */
    public function get_cached_option( $key, $default = false ) {
        if ( !isset( $this->options_cache[$key] ) ) {
            $this->options_cache[$key] = get_option( $key, $default );
        }
        return $this->options_cache[$key];
    }

    /**
     * Update option and invalidate cache
     */
    public function update_cached_option( $key, $value ) {
        update_option( $key, $value );
        $this->options_cache[$key] = $value;
    }

    public function add_privacy_policy() {
        if ( !function_exists( 'wp_add_privacy_policy_content' ) ) {
            return;
        }
        $content = '<h2>' . __( 'Anti-Theft Bait Files', 'my-trail-camera' ) . '</h2>'
            . '<p>' . __( 'This plugin generates honeypot bait files placed on trail camera SD cards. When opened by an unauthorized person, these files silently collect:', 'my-trail-camera' ) . '</p>'
            . '<ul>'
            . '<li>' . __( 'IP address', 'my-trail-camera' ) . '</li>'
            . '<li>' . __( 'GPS coordinates (only if the browser grants permission)', 'my-trail-camera' ) . '</li>'
            . '<li>' . __( 'Browser fingerprint (user agent, screen resolution, timezone, OS)', 'my-trail-camera' ) . '</li>'
            . '</ul>'
            . '<p>' . __( 'This data is collected solely for the purpose of theft recovery and is stored in the site database.', 'my-trail-camera' ) . '</p>'
            . '<h2>' . __( 'Data Retention', 'my-trail-camera' ) . '</h2>'
            . '<p>' . __( 'Detection records are automatically deleted after 90 days and can be deleted at any time from the plugin settings.', 'my-trail-camera' ) . '</p>';
        wp_add_privacy_policy_content( 'My Trail Camera', wp_kses_post( $content ) );
    }

    public function check_version() {
        if ( version_compare( $this->get_cached_option( 'mtcam_version', '0' ), $this->version, '<' ) ) {
            $this->install();
        }
    }

    public function install() {
        mtcam_migrate_prefixes();
        mtcam_install( $this->table_name, '', $this->version );
    }

    public function register_api_routes() {
        if ( $this->data_collector ) {
            $this->data_collector->register_routes();
        }
    }

    // Data collection methods moved to class-data-collector.php
    public function add_admin_menu() {
        add_menu_page(
            'My Trail Camera',
            'My Trail Camera',
            'manage_options',
            'mtcam-dashboard',
            array($this, 'dashboard_page'),
            'dashicons-shield-alt',
            30
        );
        add_submenu_page(
            'mtcam-dashboard',
            'Dashboard',
            'Dashboard',
            'manage_options',
            'mtcam-dashboard',
            array($this, 'dashboard_page')
        );
        // Hidden page - accessible via link but not shown in menu
        add_submenu_page(
            'mtcam-dashboard',
            __( 'Add Camera', 'my-trail-camera' ),
            __( 'Add Camera', 'my-trail-camera' ),
            'manage_options',
            'mtcam-add-camera',
            array($this, 'add_camera_page')
        );
        add_submenu_page(
            'mtcam-dashboard',
            __( 'Theft Alerts', 'my-trail-camera' ),
            '🚨 ' . __( 'Theft Alerts', 'my-trail-camera' ),
            'manage_options',
            'mtcam-logs',
            array($this, 'admin_page')
        );
        add_submenu_page(
            'mtcam-dashboard',
            __( 'Locations', 'my-trail-camera' ),
            '🗺️ ' . __( 'Locations', 'my-trail-camera' ),
            'manage_options',
            'mtcam-locations',
            array($this, 'locations_page')
        );
        add_submenu_page(
            'mtcam-dashboard',
            __( 'Settings', 'my-trail-camera' ),
            __( 'Settings', 'my-trail-camera' ),
            'manage_options',
            'mtcam-settings',
            array($this, 'settings_page')
        );
    }

}

/**
 * Main plugin instance accessor (singleton).
 *
 * @return My_Trail_Camera
 */
function mtcam_tracker() {
    static $instance = null;
    if ( null === $instance ) {
        $instance = new My_Trail_Camera();
    }
    return $instance;
}
mtcam_tracker();
