<?php
/**
 * The admin-specific functionality of the plugin.
 */
class FixReport_Admin {

	private $plugin_name_slug;
	private $version;
    private $db_handler;

	public function __construct( $plugin_name_slug, $version ) {
		$this->plugin_name_slug = $plugin_name_slug;
		$this->version = $version;
        
        if ( class_exists( 'FixReport_DB' ) ) {
            $this->db_handler = new FixReport_DB();
        } else {
            $this->db_handler = null;
            add_action( 'admin_notices', function() {
                if ( current_user_can( 'manage_options' ) ) {
                    echo '<div class="notice notice-error"><p>';
                    esc_html_e( 'FixReport plugin is missing a critical component (Database Handler). Some functionalities might not work. Please try reinstalling the plugin.', 'fixreport-maintenance-logger' );
                    echo '</p></div>';
                }
            });
        }
	}

    public function add_plugin_admin_menu() {
        // Add the top-level menu page.
        add_menu_page(
            __( 'FixReport Logs', 'fixreport-maintenance-logger' ), 
            __( 'FixReport', 'fixreport-maintenance-logger' ),      
            'manage_options', 
            $this->plugin_name_slug, // This is 'fixreport-maintenance-logger'
            array( $this, 'display_logs_page' ), 
            'dashicons-hammer', 
            76
        );
    }

    /**
     * Register and enqueue the stylesheets for the admin area.
     * @param string $hook_suffix The current admin page.
     */
    public function enqueue_styles( $hook_suffix ) {
        // We currently do not have a separate CSS file for the admin list table page.
        // If we did, we would check the hook and enqueue it here.
        // Example:
        // if ( 'toplevel_page_' . $this->plugin_name_slug !== $hook_suffix ) {
        //     return;
        // }
        // wp_enqueue_style( $this->plugin_name_slug, plugin_dir_url( __FILE__ ) . '../assets/css/fixreport-admin-styles.css', array(), $this->version, 'all' );
    }

    /**
     * Register and enqueue the JavaScript for the admin area.
     * @param string $hook_suffix The current admin page.
     */
    public function enqueue_scripts( $hook_suffix ) {
        // Only load the JS on our plugin's admin page.
        if ( 'toplevel_page_' . $this->plugin_name_slug !== $hook_suffix ) {
            return;
        }

        // Enqueue the script that contains the "View Desc" toggle logic.
        wp_enqueue_script( 
            $this->plugin_name_slug, 
            plugin_dir_url( dirname( __FILE__ ) ) . 'assets/js/fixreport-admin-scripts.js', 
            array(), // No dependencies for this simple script.
            $this->version, 
            true // Load in the footer.
        );
    }

    /**
     * Helper function to get the CSS content for the PDF report template.
     * @return string The CSS content.
     */
    public static function get_pdf_report_styles() {
        if ( ! defined('FIXREPORT_PATH') ) {
            return '';
        }
        $css_file_path = FIXREPORT_PATH . 'assets/css/fixreport-admin-styles.css';
        if ( file_exists( $css_file_path ) ) {
            return file_get_contents( $css_file_path );
        }
        return '';
    }

	public function display_logs_page() {
        $this->display_admin_notices();
        if ( ! $this->db_handler ) {
            echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__( 'Error: FixReport Database handler is not available. Plugin functionality may be limited.', 'fixreport-maintenance-logger' ) . '</p></div>';
            return;
        }
        $is_edit_mode = false; 
        $log_to_edit = null;
        $current_page_slug = $this->plugin_name_slug;

        if ( isset( $_GET['action'] ) && 'edit' === $_GET['action'] && isset( $_GET['log_id'] ) ) {
            $log_id_to_edit = absint( $_GET['log_id'] );
            if ( isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'fixreport_edit_log_view_' . $log_id_to_edit ) ) {
                $log_to_edit = $this->db_handler->get_log_by_id( $log_id_to_edit );
                if ( $log_to_edit ) { 
                    $is_edit_mode = true; 
                } else { 
                    wp_safe_redirect( admin_url( 'admin.php?page=' . $current_page_slug . '&fixreport_notice=log_not_found' ) ); 
                    exit; 
                }
            } else { 
                wp_die( 
                    esc_html__( 'Security check failed for viewing edit form. Invalid or missing nonce.', 'fixreport-maintenance-logger' ), 
                    esc_html__( 'Security Check Failed', 'fixreport-maintenance-logger' ), 
                    array( 'response' => 403, 'back_link' => true ) 
                ); 
            }
        }

        $logs_data = array(); 
        $items_per_page = 20;
        $current_page_num = isset( $_GET['paged'] ) ? absint( $_GET['paged'] ) : 1;
        $current_page_num = max( 1, $current_page_num );
        
        $pagination_args = array(
            'total_items'    => 0,
            'total_pages'    => 0,
            'current_page'   => $current_page_num,
            'items_per_page' => $items_per_page,
        );

        if ( ! $is_edit_mode ) {
            $offset = ( $current_page_num - 1 ) * $items_per_page;
            $total_items = $this->db_handler->count_logs();
            $total_pages = ceil( $total_items / $items_per_page );
            $logs_data = $this->db_handler->get_logs( array( 'number' => $items_per_page, 'offset' => $offset ) );
            $pagination_args['total_items'] = $total_items; 
            $pagination_args['total_pages'] = $total_pages;
        }
		require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/views/logs-display-page.php';
	}

	public function handle_add_log_submission() {
        check_admin_referer( 'fixreport_add_log_action', 'fixreport_add_log_nonce' );
        if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You do not have sufficient permissions to add logs.', 'fixreport-maintenance-logger' ), esc_html__( 'Permissions Error', 'fixreport-maintenance-logger' ), array( 'response' => 403 ) ); }
        if ( ! $this->db_handler ) { wp_die( esc_html__( 'Database handler is not initialized. Cannot add log.', 'fixreport-maintenance-logger' ), esc_html__( 'Database Error', 'fixreport-maintenance-logger' ), array('response' => 500, 'back_link' => true) ); }

        $log_title = isset( $_POST['fixreport_title'] ) ? sanitize_text_field( wp_unslash( $_POST['fixreport_title'] ) ) : '';
        $log_description = isset( $_POST['fixreport_description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['fixreport_description'] ) ) : '';
        $log_type = isset( $_POST['fixreport_type'] ) ? sanitize_text_field( wp_unslash( $_POST['fixreport_type'] ) ) : '';
        $log_priority = isset( $_POST['fixreport_priority'] ) ? sanitize_text_field( wp_unslash( $_POST['fixreport_priority'] ) ) : 'Medium';
        $log_status = isset( $_POST['fixreport_status'] ) ? sanitize_text_field( wp_unslash( $_POST['fixreport_status'] ) ) : 'Resolved';
        
        if ( empty( $log_title ) || empty( $log_description ) || empty( $log_type ) ) {
             wp_safe_redirect( esc_url_raw( admin_url( 'admin.php?page=' . $this->plugin_name_slug . '&fixreport_notice=required_fields_missing' ) ) );
             exit;
        }
        
        $data_to_insert = array(
            'title'       => $log_title, 'description' => $log_description, 'type'        => $log_type,
            'priority'    => $log_priority, 'status'      => $log_status, 'user_id'     => get_current_user_id(),
            'created_at'  => current_time( 'mysql', 1 ), 'updated_at'  => current_time( 'mysql', 1 ),
        ); 
        
        $inserted_id = $this->db_handler->insert_log( $data_to_insert );
        $redirect_url = admin_url( 'admin.php?page=' . $this->plugin_name_slug );
        $notice_code = ($inserted_id !== false) ? 'log_added_success' : 'log_added_error';
        wp_safe_redirect( esc_url_raw( add_query_arg( 'fixreport_notice', $notice_code, $redirect_url ) ) );
        exit;
	}

	public function handle_delete_log_submission() { 
        $log_id = isset( $_GET['log_id'] ) ? absint( $_GET['log_id'] ) : 0;
        check_admin_referer( 'fixreport_delete_log_' . $log_id );
        if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You do not have sufficient permissions to delete logs.', 'fixreport-maintenance-logger' ), esc_html__( 'Permissions Error', 'fixreport-maintenance-logger' ), array( 'response' => 403 ) ); }
        if ( ! $this->db_handler ) { wp_die( esc_html__( 'Database handler is not initialized. Cannot delete log.', 'fixreport-maintenance-logger' ), esc_html__( 'Database Error', 'fixreport-maintenance-logger' ), array('response' => 500, 'back_link' => true) ); }
        if ( $log_id <= 0 ) { wp_die( esc_html__( 'Invalid Log ID for deletion.', 'fixreport-maintenance-logger' ), esc_html__( 'Invalid Input', 'fixreport-maintenance-logger' ), array('response' => 400) ); }
        
        $deleted = $this->db_handler->delete_log( $log_id );
        $redirect_url = admin_url( 'admin.php?page=' . $this->plugin_name_slug );
        $notice_code = ($deleted) ? 'log_deleted_success' : 'log_deleted_error';
        wp_safe_redirect( esc_url_raw( add_query_arg( 'fixreport_notice', $notice_code, $redirect_url ) ) );
        exit;
    }

	public function handle_update_log_submission() { 
        $log_id = isset( $_POST['fixreport_log_id'] ) ? absint( $_POST['fixreport_log_id'] ) : 0;
        check_admin_referer( 'fixreport_update_log_action_' . $log_id, 'fixreport_update_log_nonce' );
        if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You do not have sufficient permissions to update logs.', 'fixreport-maintenance-logger' ), esc_html__( 'Permissions Error', 'fixreport-maintenance-logger' ), array( 'response' => 403 ) ); }
        if ( ! $this->db_handler ) { wp_die( esc_html__( 'Database handler is not initialized. Cannot update log.', 'fixreport-maintenance-logger' ), esc_html__( 'Database Error', 'fixreport-maintenance-logger' ), array('response' => 500, 'back_link' => true) ); }
        if ( $log_id <= 0 ) { wp_die( esc_html__( 'Invalid Log ID for update.', 'fixreport-maintenance-logger' ), esc_html__( 'Invalid Input', 'fixreport-maintenance-logger' ), array('response' => 400) ); }
        
        $data_to_update = array();
        $allowed_fields = array( 'fixreport_title', 'fixreport_description', 'fixreport_type', 'fixreport_priority', 'fixreport_status' );
        $field_map = array(
            'fixreport_title' => 'title', 'fixreport_description' => 'description', 'fixreport_type' => 'type',
            'fixreport_priority' => 'priority', 'fixreport_status' => 'status',
        );
        foreach ( $allowed_fields as $post_field ) {
            if ( isset( $_POST[ $post_field ] ) ) {
                $db_column = $field_map[ $post_field ];
                $data_to_update[ $db_column ] = ( $post_field === 'fixreport_description' ) ?
                    sanitize_textarea_field( wp_unslash( $_POST[ $post_field ] ) ) :
                    sanitize_text_field( wp_unslash( $_POST[ $post_field ] ) );
            }
        }
        $data_to_update['updated_at'] = current_time( 'mysql', 1 );
        if ( empty( $data_to_update['title'] ) || empty( $data_to_update['description'] ) || empty( $data_to_update['type'] ) ) {
            $edit_url_args = array(
                'page' => $this->plugin_name_slug, 'action' => 'edit', 'log_id' => $log_id,
                '_wpnonce' => wp_create_nonce( 'fixreport_edit_log_view_' . $log_id ),
                'fixreport_notice' => 'required_fields_missing_edit'
            );
            wp_safe_redirect( esc_url_raw( add_query_arg( $edit_url_args, admin_url( 'admin.php' ) ) ) );
            exit;
        }
        $updated_rows = $this->db_handler->update_log( $log_id, $data_to_update );
        $redirect_url = admin_url( 'admin.php?page=' . $this->plugin_name_slug );
        $notice_code = 'log_updated_error';
        if ( $updated_rows !== false ) {
            $notice_code = ( $updated_rows > 0 ) ? 'log_updated_success' : 'log_no_changes';
        }
        wp_safe_redirect( esc_url_raw( add_query_arg( 'fixreport_notice', $notice_code, $redirect_url ) ) );
        exit;
    }

    public function handle_export_pdf_submission() { 
        check_admin_referer( 'fixreport_export_pdf_nonce_action' ); 
        if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You do not have sufficient permissions to export logs.', 'fixreport-maintenance-logger' ), esc_html__( 'Permissions Error', 'fixreport-maintenance-logger' ), array( 'response' => 403 ) ); }
        if ( ! $this->db_handler ) { wp_die( esc_html__( 'Database handler is not initialized. Cannot export PDF.', 'fixreport-maintenance-logger' ), esc_html__( 'Database Error', 'fixreport-maintenance-logger' ), array( 'response' => 500, 'back_link' => true ) ); }
        if ( ! class_exists( 'FixReport_Exporter' ) ) {
            wp_die( esc_html__( 'Exporter class (FixReport_Exporter) is not available. PDF export failed. Please ensure all plugin files are correctly installed and loaded.', 'fixreport-maintenance-logger' ), esc_html__( 'Class Load Error', 'fixreport-maintenance-logger' ), array( 'response' => 500 ) );
        }
        $exporter = new FixReport_Exporter( $this->db_handler );
        $exporter->generate_pdf_report();
    }

    private function display_admin_notices() { 
        if ( isset( $_GET['fixreport_notice'] ) ) {
            $notice_code = sanitize_key( $_GET['fixreport_notice'] );
            $message = ''; $type = 'info'; 
            switch ( $notice_code ) {
                case 'log_added_success': $message = __( 'Log entry added successfully.', 'fixreport-maintenance-logger' ); $type = 'success'; break;
                // ... (rest of the cases with the new text domain) ...
                case 'log_not_found': $message = __( 'Error: The requested log entry was not found.', 'fixreport-maintenance-logger' ); $type = 'error'; break;
                default:
                    if ( defined('WP_DEBUG') && WP_DEBUG ) {
                        /* translators: %s: The unknown notice code that was received. */
                        $message = sprintf( esc_html__( 'An unknown notice code was received: %s', 'fixreport-maintenance-logger' ), '<code>' . esc_html( $notice_code ) . '</code>' );
                        $type = 'warning';
                    }
                    break;
            }
            if ( ! empty( $message ) ) {
                printf( '<div class="notice notice-%s is-dismissible"><p>%s</p></div>', esc_attr( $type ), wp_kses_post( $message ) );
            }
        }
    }
}