<?php
if (!defined('ABSPATH')) exit;
?>

<main class="wrap mtcam-wrap">
    <h1><span class="dashicons dashicons-admin-settings mtcam-icon-lg" aria-hidden="true"></span> <?php esc_html_e('Settings', 'my-trail-camera'); ?></h1>

    <?php
    $mtcam_nonce_valid = isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'mtcam_settings_notice' );
    $mtcam_notices = array(
        'settings_saved'  => array( 'success', __( 'All settings saved successfully!', 'my-trail-camera' ) ),
        'import_success'  => array( 'success', __( 'Backup imported successfully! Cameras and settings restored.', 'my-trail-camera' ) ),
        'import_error'    => array( 'error',   __( 'Error importing backup. Invalid file format.', 'my-trail-camera' ) ),
        'orphans_cleaned' => array( 'success', __( 'Orphaned records cleaned up successfully!', 'my-trail-camera' ) ),
    );
    foreach ( $mtcam_notices as $mtcam_key => $mtcam_notice_item ) {
        if ( $mtcam_nonce_valid && isset( $_GET[ $mtcam_key ] ) ) {
            echo '<div class="notice notice-' . esc_attr( $mtcam_notice_item[0] ) . ' is-dismissible" role="alert"><p><strong>' . esc_html( $mtcam_notice_item[1] ) . '</strong></p></div>';
        }
    }
    if ( ! empty( $this->admin_notice ) ) {
        $mtcam_notice = $this->admin_notice;
        echo '<div class="notice notice-' . esc_attr( $mtcam_notice['type'] ) . ' is-dismissible" role="alert"><p>' . wp_kses_post( $mtcam_notice['message'] ) . '</p></div>';
    }
    ?>

    <!-- TABS -->
    <div class="mtcam-tabs" role="tablist">
        <div class="mtcam-tab active" data-mtcam-tab="security" role="tab" tabindex="0" aria-selected="true"><span aria-hidden="true">🔒</span> <?php esc_html_e('Security', 'my-trail-camera'); ?></div>
        <div class="mtcam-tab" data-mtcam-tab="visibility" role="tab" tabindex="0" aria-selected="false"><span aria-hidden="true">👁️</span> <?php esc_html_e('Public Widget', 'my-trail-camera'); ?></div>
        <div class="mtcam-tab" data-mtcam-tab="advanced" role="tab" tabindex="0" aria-selected="false"><span aria-hidden="true">⚙️</span> <?php esc_html_e('Advanced', 'my-trail-camera'); ?></div>
        <div class="mtcam-tab" data-mtcam-tab="integration" role="tab" tabindex="0" aria-selected="false"><span aria-hidden="true">📡</span> <?php esc_html_e('Integration', 'my-trail-camera'); ?></div>
        <div class="mtcam-tab" data-mtcam-tab="maintenance" role="tab" tabindex="0" aria-selected="false"><span aria-hidden="true">🔧</span> <?php esc_html_e('Maintenance', 'my-trail-camera'); ?></div>
        <div class="mtcam-tab" data-mtcam-tab="about" role="tab" tabindex="0" aria-selected="false"><span aria-hidden="true">ℹ️</span> <?php esc_html_e('About', 'my-trail-camera'); ?></div>
    </div>

	<form method="post" action="<?php echo esc_url( admin_url( 'admin.php?page=mtcam-settings' ) ); ?>">
        <?php wp_nonce_field('mtcam_settings'); ?>

        <?php include dirname(__DIR__) . '/tabs/tab-security.php'; ?>
        <?php include dirname(__DIR__) . '/tabs/tab-visibility.php'; ?>
        <?php include dirname(__DIR__) . '/tabs/tab-advanced.php'; ?>
        <?php include dirname(__DIR__) . '/tabs/tab-integration.php'; ?>
        <?php include dirname(__DIR__) . '/tabs/tab-maintenance.php'; ?>
        <?php include dirname(__DIR__) . '/tabs/tab-about.php'; ?>

    <!-- Single save button for all tabs -->
    <p class="submit mtcam-sticky-save">
        <input type="submit" name="mtcam_settings_submit" class="button button-primary" value="💾 <?php esc_attr_e('Save All Settings', 'my-trail-camera'); ?>" >
    </p>
    </form>

</main>

<?php
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- JSON data is properly encoded
$mtcam_backup_data = wp_json_encode( mtcam_get_cameras(), JSON_UNESCAPED_UNICODE );
$mtcam_backup_settings = wp_json_encode( array(
    'notify_email'           => get_option( 'mtcam_notify_email', '' ),
    'show_ip'                => get_option( 'mtcam_show_ip', 'yes' ),
    'show_photo'             => get_option( 'mtcam_show_photo', 'yes' ),
    'show_battery_stolen'    => get_option( 'mtcam_show_battery_stolen', 'yes' ),
    'public_stolen_show_name' => get_option( 'mtcam_public_stolen_show_name', 'no' ),
    'public_active_show_name' => get_option( 'mtcam_public_active_show_name', 'no' ),
), JSON_UNESCAPED_UNICODE );
$mtcam_backup_reviews  = wp_json_encode(
    function_exists( 'mtcam_location_reviews_get_all' ) ? mtcam_location_reviews_get_all() : array(),
    JSON_UNESCAPED_UNICODE
);
$mtcam_backup_profiles = wp_json_encode( get_option( 'mtcam_custom_profiles', array() ), JSON_UNESCAPED_UNICODE );

wp_add_inline_script( 'mtc-admin-js', 'function thorExportBackup(){' .
    'var data={' .
        'version:"' . esc_js( $system_info['plugin_version'] ) . '",' .
        'exported:new Date().toISOString(),' .
        'cameras:' . $mtcam_backup_data . ',' .
        'settings:' . $mtcam_backup_settings . ',' .
        'location_reviews:' . $mtcam_backup_reviews . ',' .
        'custom_profiles:' . $mtcam_backup_profiles .
    '};' .
    'var blob=new Blob([JSON.stringify(data,null,2)],{type:"application/json"});' .
    'var url=URL.createObjectURL(blob);' .
    'var a=document.createElement("a");a.href=url;' .
    'a.download="mtcam-backup-"+new Date().toISOString().slice(0,10)+".json";' .
    'a.click();URL.revokeObjectURL(url);' .
'}' .
'function thorImportBackup(input){' .
    'var file=input.files[0];if(!file)return;' .
    'var reader=new FileReader();' .
    'reader.onload=function(e){' .
        'try{' .
            'var data=JSON.parse(e.target.result);' .
            'if(!data.cameras||!data.settings){alert("' . esc_js( __( 'Invalid backup file!', 'my-trail-camera' ) ) . '");return;}' .
            'var camCount=Object.keys(data.cameras).length;' .
            'var reviewsCount=data.location_reviews?data.location_reviews.length:0;' .
            'var profilesCount=data.custom_profiles?Object.keys(data.custom_profiles).length:0;' .
            'var preview=document.getElementById("mtcam-import-preview");' .
            'preview.style.display="block";' .
            'preview.innerHTML=' .
                '"<div class=\"mtcam-warning-box\">"' .
                '+"<strong>\ud83d\udccb ' . esc_js( __( 'Import preview:', 'my-trail-camera' ) ) . '</strong><br><br>"' .
                '+"📅 ' . esc_js( __( 'Backup from:', 'my-trail-camera' ) ) . ' "+(data.exported||"?")+"<br>"' .
                '+"📷 ' . esc_js( __( 'Cameras:', 'my-trail-camera' ) ) . ' "+camCount+"<br>"' .
                '+"🗺️ ' . esc_js( __( 'Location reviews:', 'my-trail-camera' ) ) . ' "+reviewsCount+"<br>"' .
                '+"📋 ' . esc_js( __( 'Custom profiles:', 'my-trail-camera' ) ) . ' "+profilesCount+"<br>"' .
                '+"🔧 ' . esc_js( __( 'Version:', 'my-trail-camera' ) ) . ' "+(data.version||"?")+"<br><br>"' .
                '+"<strong>⚠️ ' . esc_js( __( 'Import will REPLACE all current cameras and settings!', 'my-trail-camera' ) ) . '</strong><br><br>"' .
                '+"<button type=\"button\" data-mtcam-action=\"thorConfirmImport\" class=\"mtcam-maint-btn mtcam-maint-btn-orange\">"' .
                '+"✅ ' . esc_js( __( 'Confirm Import', 'my-trail-camera' ) ) . '</button> "' .
                '+"<button type=\"button\" data-mtcam-hide-element=\"mtcam-import-preview\" class=\"mtcam-maint-btn mtcam-maint-btn-red\">"' .
                '+"❌ ' . esc_js( __( 'Cancel', 'my-trail-camera' ) ) . '</button>"' .
                '+"</div>";' .
            'window._thorImportData=data;' .
        '}catch(err){alert("' . esc_js( __( 'Error reading file:', 'my-trail-camera' ) ) . ' "+err.message);}' .
    '};' .
    'reader.readAsText(file);input.value="";' .
'}' .
'function thorConfirmImport(){' .
    'if(!window._thorImportData)return;' .
    'var form=document.createElement("form");form.method="POST";form.action="";' .
    'var nonce=document.querySelector("input[name=\\"_wpnonce\\"]");' .
    'if(nonce){var n=document.createElement("input");n.type="hidden";n.name="_wpnonce";n.value=nonce.value;form.appendChild(n);}' .
    'var d=document.createElement("input");d.type="hidden";d.name="mtcam_import_data";d.value=JSON.stringify(window._thorImportData);form.appendChild(d);' .
    'var s=document.createElement("input");s.type="hidden";s.name="mtcam_import_submit";s.value="1";form.appendChild(s);' .
    'document.body.appendChild(form);form.submit();' .
'}'
);
?>
