<?php
/**
 * MediaFiles handlers for MindWebConcierge.
 *
 * @package MindWebConcierge
 */

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

add_action( 'wp_ajax_mindweco_index_all_media_files', 'mindweco_plugin_index_media_files' );

function mindweco_plugin_index_media_files() {
    check_ajax_referer( 'mindweco_files_nonce', 'nonce' );

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( 'Unauthorized' );
        return;
    }

    global $wpdb;

    $options       = get_option( 'mindweco_plugin_options', array() );
    $options       = is_array( $options ) ? $options : array();
    $base_url      = sanitize_text_field( $options['base_url'] ?? '' );
    $token         = mindweco_decrypt_api_key( get_option( 'mindweco_plugin_access_token', '' ) );
    $chunk_size    = get_option( 'mindweco_chunk_size' );
    $chunk_overlap = get_option( 'mindweco_chunk_overlap' );

    $category = get_option( 'mindweco_plugin_category', null );
    if ( ! $category || empty( $category['id'] ) ) {
        wp_send_json_error( 'Category not set. Please login first.' );
        return;
    }

    $category_id = absint( $category['id'] );

    if ( empty( $base_url ) || empty( $token ) || ! $category_id ) {
        wp_send_json_error( 'Missing required configuration: Base URL, Token, or Category ID' );
        return;
    }

    $fresh_token = mindweco_plugin_refresh_token();
    if ( $fresh_token ) {
        $token = $fresh_token;
    }

    $attachments = get_posts( array(
        'post_type'      => 'attachment',
        'post_status'    => 'inherit',
        'posts_per_page' => -1,
        'orderby'        => 'date',
        'order'          => 'DESC',
        'post_mime_type' => array(
            'application/pdf',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        ),
    ) );

    if ( empty( $attachments ) ) {
        wp_send_json_error( 'No supported media files found (PDF or DOCX).' );
        return;
    }

    $results = array();
    $table   = $wpdb->prefix . 'mindweco_indexed_media_files';

    foreach ( $attachments as $attachment ) {
        $file_path = get_attached_file( $attachment->ID );

        $media_item = array(
            'id'        => $attachment->ID,
            'title'     => $attachment->post_title,
            'url'       => wp_get_attachment_url( $attachment->ID ),
            'mime_type' => $attachment->post_mime_type,
            'date'      => $attachment->post_date,
            'filesize'  => $file_path && file_exists( $file_path ) ? filesize( $file_path ) : 0,
        );

        $existing = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT item_id FROM `{$table}` WHERE file_id = %d LIMIT 1",
                $attachment->ID
            )
        );

        if ( $existing ) {
            $results[] = array(
                'file_id' => $attachment->ID,
                'item_id' => $existing,
                'status'  => 'already_indexed',
                'url'     => $media_item['url'],
                'title'   => $attachment->post_title,
            );
            continue;
        }

        $api_response = mindweco_plugin_api_index_media_files(
            $base_url,
            $token,
            $category_id,
            $chunk_size,
            $chunk_overlap,
            $media_item['url'],
            0,
            $media_item,
            0
        );

        if ( empty( $api_response['success'] ) ) {
            $results[] = array(
                'file_id' => $attachment->ID,
                'item_id' => null,
                'status'  => 'failed',
                'error'   => sanitize_text_field( $api_response['message'] ?? 'Unknown error' ),
                'url'     => $media_item['url'],
                'title'   => $attachment->post_title,
            );
            continue;
        }

        $new_item_id = $api_response['body']['item_id'] ?? null;

        if ( empty( $new_item_id ) ) {
            $results[] = array(
                'file_id' => $attachment->ID,
                'item_id' => null,
                'status'  => 'failed',
                'error'   => 'No item_id returned from API',
                'url'     => $media_item['url'],
                'title'   => $attachment->post_title,
            );
            continue;
        }

        $wpdb->query(
            $wpdb->prepare(
                "INSERT INTO `{$table}` (file_id, item_id, category_id)
                VALUES (%d, %s, %d)
                ON DUPLICATE KEY UPDATE item_id = VALUES(item_id), category_id = VALUES(category_id)",
                $attachment->ID,
                $new_item_id,
                $category_id
            )
        );

        $results[] = array(
            'file_id' => $attachment->ID,
            'item_id' => $new_item_id,
            'status'  => 'success',
            'url'     => $media_item['url'],
            'title'   => $attachment->post_title,
        );
    }

    wp_send_json_success( $results );
}


add_action( 'wp_ajax_mindweco_get_stats_files', 'mindweco_plugin_get_stats_files' );

function mindweco_plugin_get_stats_files() {
    check_ajax_referer( 'mindweco_files_nonce', 'nonce' );

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array( 'message' => 'Unauthorized' ) );
        return;
    }

    global $wpdb;
    $table_name = $wpdb->prefix . 'mindweco_indexed_media_files';

    $row = $wpdb->get_row(
        "SELECT 
            COUNT(p.ID) AS total,
            COUNT(i.file_id) AS indexed
        FROM {$wpdb->prefix}posts p
        LEFT JOIN {$table_name} i ON p.ID = i.file_id
        WHERE p.post_type = 'attachment'
          AND p.post_status = 'inherit'
          AND p.post_mime_type IN (
              'application/pdf',
              'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
          )"
    );

    $total    = (int) ( $row->total ?? 0 );
    $indexed  = (int) ( $row->indexed ?? 0 );
    $to_index = max( 0, $total - $indexed );
    $progress = $total > 0 ? min( 100, round( ( $indexed / $total ) * 100 ) ) : 0;

    wp_send_json_success( array(
        'total'    => $total,
        'indexed'  => $indexed,
        'to_index' => $to_index,
        'progress' => $progress,
    ) );
}

add_action( 'wp_ajax_mindweco_fetch_media_files', 'mindweco_fetch_media_files' );

function mindweco_fetch_media_files() {
    check_ajax_referer( 'mindweco_files_nonce', 'nonce' );

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'mind-web-concierge' ) ) );
        return;
    }

    $attachments = get_posts( array(
        'post_type'      => 'attachment',
        'post_status'    => 'inherit',
        'posts_per_page' => -1,
        'orderby'        => 'date',
        'order'          => 'DESC',
        'post_mime_type' => array(
            'application/pdf',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        ),
    ) );

    global $wpdb;
    $table = $wpdb->prefix . 'mindweco_indexed_media_files';

    $file_data = array();
    foreach ( $attachments as $attachment ) {
        $indexed_row = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM `{$table}` WHERE file_id = %d LIMIT 1",
                $attachment->ID
            )
        );

        $file_path  = get_attached_file( $attachment->ID );
        $is_indexed = ! empty( $indexed_row );
        $item_id    = $indexed_row ? $indexed_row->item_id : null;

        $file_data[] = array(
            'id'        => $attachment->ID,
            'title'     => $attachment->post_title,
            'url'       => wp_get_attachment_url( $attachment->ID ),
            'mime_type' => $attachment->post_mime_type,
            'date'      => $attachment->post_date,
            'filesize'  => $file_path && file_exists( $file_path ) ? filesize( $file_path ) : 0,
            'indexed'   => $is_indexed,
            'item_id'   => $item_id,
        );
    }

    $total_files   = count( $file_data );
    $total_indexed = intval( $wpdb->get_var( "SELECT COUNT(*) FROM `{$table}`" ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

    wp_send_json_success( array(
        'files'  => $file_data,
        'totals' => array(
            'total_files'   => $total_files,
            'total_indexed' => $total_indexed,
        ),
    ) );
}

add_action( 'wp_ajax_mindweco_get_indexed_table_files', 'mindweco_get_indexed_table_files' );

function mindweco_get_indexed_table_files() {

    check_ajax_referer( 'mindweco_files_nonce', 'nonce' );

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized.', 'mind-web-concierge' ) ) );
        return;
    }

    global $wpdb;
    $table_name = $wpdb->prefix . 'mindweco_indexed_media_files';

    $results = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT i.id AS index_id, i.item_id, i.file_id, i.category_id,
                p.post_title, p.post_name, p.post_status, p.post_author, p.post_type, p.post_mime_type,
                u.display_name AS author_name
            FROM `{$table_name}` i
            LEFT JOIN `{$wpdb->prefix}posts` p ON i.file_id = p.ID
            LEFT JOIN `{$wpdb->prefix}users` u ON p.post_author = u.ID
            WHERE p.post_type = %s
            ORDER BY i.id ASC",
            'attachment'
        )
    );

    function mindweco_format_size( $bytes ) {
        if ( $bytes >= 1048576 ) {
            return round( $bytes / 1048576, 2 ) . ' MB';
        } elseif ( $bytes >= 1024 ) {
            return round( $bytes / 1024, 2 ) . ' KB';
        }
        return $bytes . ' B';
    }

    $html = '';

    if ( $results ) {
        foreach ( $results as $r ) {
            $file_size = '—';

            $meta = wp_get_attachment_metadata( $r->file_id );
            if ( isset( $meta['filesize'] ) ) {
                $file_size = mindweco_format_size( $meta['filesize'] );
            } else {
                // fallback
                $file_path = get_attached_file( $r->file_id );
                if ( $file_path && file_exists( $file_path ) ) {
                    $file_size = mindweco_format_size( filesize( $file_path ) );
                }
            }

            $html .= '<tr>';
            $html .= '<td>' . esc_html( $r->index_id ) . '</td>';
            $html .= '<td>' . esc_html( $r->item_id ) . '</td>';
            $html .= '<td>' . esc_html( $r->file_id ) . '</td>';
            $html .= '<td>' . esc_html( $r->post_type ) . '</td>';
            $html .= '<td>' . esc_html( $r->category_id ) . '</td>';
            $html .= '<td>' . esc_html( $r->post_title ) . '</td>';
            $html .= '<td>' . esc_html( $file_size ) . '</td>';
            $html .= '<td>' . esc_html( $r->author_name ) . '</td>';
            $html .= '<td>' . esc_html( $r->post_mime_type ) . '</td>';
            $html .= '<td>';
            $html .= '<button class="button button-small button-link-delete unindex-file p-1"';
            $html .= ' data-item-id="' . esc_attr( $r->item_id ) . '"';
            $html .= ' data-category-id="' . esc_attr( $r->category_id ) . '">';
            $html .= '<span class="dashicons dashicons-trash"></span> ' . esc_html__( 'UnIndex', 'mind-web-concierge' );
            $html .= '</button>';
            $html .= '</td>';
            $html .= '</tr>';
        }
    }

    wp_send_json_success( $html );
}


add_action( 'wp_ajax_mindweco_delete_indexed_file', 'mindweco_plugin_delete_indexed_file' );

function mindweco_plugin_delete_indexed_file() {

    check_ajax_referer( 'mindweco_files_nonce', 'nonce' );

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( 'Unauthorized' );
        return;
    }

    global $wpdb;

    $item_id     = sanitize_text_field( wp_unslash( $_POST['item_id'] ?? '' ) );
    $category_id = absint( $_POST['category_id'] ?? 0 );


    if ( empty( $item_id ) || ! $category_id ) {
        wp_send_json_error( array( 'message' => 'Invalid item_id or category_id' ) );
        return;
    }

    $table = $wpdb->prefix . 'mindweco_indexed_media_files';

    $count_before = (int) $wpdb->get_var(
        "SELECT COUNT(*) FROM `{$table}`"
    );

    $options  = get_option( 'mindweco_plugin_options', array() );
    $options  = is_array( $options ) ? $options : array();

    $base_url = sanitize_text_field( $options['base_url'] ?? '' );
    $token    = mindweco_decrypt_api_key( get_option( 'mindweco_plugin_access_token', '' ) );

    if ( empty( $base_url ) || empty( $token ) ) {
        wp_send_json_error( array( 'message' => 'Missing Base URL or Access Token' ) );
        return;
    }

    $api_response = mindweco_plugin_api_delete_indexed_items(
        $base_url,
        $token,
        $category_id,
        $item_id
    );

    if ( isset( $api_response['http_code'] ) && 401 === (int) $api_response['http_code'] ) {
        $new_token = mindweco_plugin_refresh_token();

        if ( $new_token ) {
            $api_response = mindweco_plugin_api_delete_indexed_items(
                $base_url,
                $new_token,
                $category_id,
                $item_id
            );
        }
    }

    $deleted = $wpdb->delete(
        $table,
        array(
            'item_id'     => $item_id,
            'category_id' => $category_id,
        ),
        array( '%s', '%d' )
    );

    $count_after = (int) $wpdb->get_var(
        "SELECT COUNT(*) FROM `{$table}`"
    );

    if ( false === $deleted ) {
        wp_send_json_error( array( 'message' => 'Database delete failed' ) );
        return;
    }

    wp_send_json_success(
        array(
            'message'      => $deleted > 0 ? 'File unindexed successfully' : 'File removed from API but was not in local database',
            'deleted_rows' => $deleted,
            'count_before' => $count_before,
            'count_after'  => $count_after,
        )
    );
}


add_action( 'wp_ajax_mindweco_unindex_all_files', 'mindweco_plugin_unindex_all_files' );

function mindweco_plugin_unindex_all_files() {

    check_ajax_referer( 'mindweco_files_nonce', 'nonce' );

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( 'Unauthorized' );
        return;
    }

    global $wpdb;

    $table    = $wpdb->prefix . 'mindweco_indexed_media_files';
	$options  = get_option( 'mindweco_plugin_options', array() );
	$base_url = isset( $options['base_url'] ) ? $options['base_url'] : '';
	$token = mindweco_decrypt_api_key( get_option( 'mindweco_plugin_access_token', '' ) );

    $all_files = $wpdb->get_results( "SELECT item_id, category_id FROM `{$table}`" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

    if($base_url && $token) {
        $fresh_token = mindweco_plugin_refresh_token();
		if ( $fresh_token ) {
			$token = $fresh_token;
		}
        foreach($all_files as $file ){
            mindweco_plugin_api_delete_indexed_items( $base_url , $token, $file->category_id, $file->item_id);
        }
    }

    $deleted = $wpdb->query( "TRUNCATE TABLE `{$table}`" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

	if ( false !== $deleted ) {
		wp_send_json_success( array( 'message' => esc_html__( 'All indexed items have been deleted.', 'mind-web-concierge' ) ) );
	} else {
		wp_send_json_error( array( 'message' => esc_html__( 'Failed to delete items.', 'mind-web-concierge' ) ) );
	}

}


add_action( 'add_attachment', 'mindweco_on_file_uploaded' );

function mindweco_on_file_uploaded( $attachment_id ) {
    $mime = get_post_mime_type( $attachment_id );
    $supported = array(
        'application/pdf',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    );

     if ( ! in_array( $mime, $supported, true ) ) {
        return;
    }

    global $wpdb;
    $table = $wpdb->prefix . 'mindweco_indexed_media_files';

    $existing = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT item_id FROM `{$table}` WHERE file_id = %d LIMIT 1",
            $attachment_id
        )
    );

    if ( $existing ) {
        return;
    }

    $options     = get_option( 'mindweco_plugin_options', array() );
    $base_url    = sanitize_text_field( $options['base_url'] ?? '' );
    $token       = mindweco_decrypt_api_key( get_option( 'mindweco_plugin_access_token', '' ) );
    $category    = get_option( 'mindweco_plugin_category', null );
    $category_id = absint( $category['id'] ?? 0 );

    if ( empty( $base_url ) || empty( $token ) || ! $category_id ) {
        return;
    }

    $fresh_token = mindweco_plugin_refresh_token();
    if ( $fresh_token ) {
        $token = $fresh_token;
    }

    if ( empty( $base_url ) || empty( $token ) || ! $category_id ) {
        return;
    }

    $attachment = get_post( $attachment_id );
    $file_path  = get_attached_file( $attachment_id );

    $media_item = array(
        'id'        => $attachment_id,
        'title'     => $attachment->post_title,
        'url'       => wp_get_attachment_url( $attachment_id ),
        'mime_type' => $mime,
        'date'      => $attachment->post_date,
        'filesize'  => $file_path && file_exists( $file_path ) ? filesize( $file_path ) : 0,
    );

    $api_response = mindweco_plugin_api_index_media_files(
        $base_url,
        $token,
        $category_id,
        get_option( 'mindweco_chunk_size' ),
        get_option( 'mindweco_chunk_overlap' ),
        $media_item['url'],
        0,
        $media_item,
        0
    );

    if ( empty( $api_response['success'] ) ) {
        return;
    }

    $new_item_id = $api_response['body']['item_id'] ?? null;

    if ( empty( $new_item_id ) ) {
        return;
    }

    $wpdb->query(
        $wpdb->prepare(
            "INSERT INTO `{$table}` (file_id, item_id, category_id)
            VALUES (%d, %s, %d)
            ON DUPLICATE KEY UPDATE item_id = VALUES(item_id), category_id = VALUES(category_id)",
            $attachment_id,
            $new_item_id,
            $category_id
        )
    );
}

add_action( 'wp_ajax_mindweco_check_file_indexed', 'mindweco_check_file_indexed' );

function mindweco_check_file_indexed() {
    check_ajax_referer( 'mindweco_files_nonce', 'nonce' );

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( 'Unauthorized' );
        return;
    }

    global $wpdb;
    $file_id = absint( $_POST['file_id'] ?? 0 );
    $table   = $wpdb->prefix . 'mindweco_indexed_media_files';

    $item_id = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT item_id FROM `{$table}` WHERE file_id = %d LIMIT 1",
            $file_id
        )
    );

    wp_send_json_success( array(
        'indexed' => ! empty( $item_id ),
        'item_id' => $item_id,
    ) );
}

add_action( 'delete_attachment', 'mindweco_on_file_deleted' );

function mindweco_on_file_deleted( $attachment_id ) {
    global $wpdb;
    $table = $wpdb->prefix . 'mindweco_indexed_media_files';

    $row = $wpdb->get_row(
        $wpdb->prepare(
            "SELECT item_id, category_id FROM `{$table}` WHERE file_id = %d LIMIT 1",
            $attachment_id
        )
    );

    if ( ! $row ) {
        return;
    }

    $options  = get_option( 'mindweco_plugin_options', array() );
    $base_url = sanitize_text_field( $options['base_url'] ?? '' );
    $token    = mindweco_decrypt_api_key( get_option( 'mindweco_plugin_access_token', '' ) );

    if ( $base_url && $token ) {
        $fresh_token = mindweco_plugin_refresh_token();
        if ( $fresh_token ) {
            $token = $fresh_token;
        }

        $api_response = mindweco_plugin_api_delete_indexed_items(
            $base_url,
            $token,
            $row->category_id,
            $row->item_id
        );

        if ( isset( $api_response['http_code'] ) && 401 === (int) $api_response['http_code'] ) {
            $new_token = mindweco_plugin_refresh_token();
            if ( $new_token ) {
                mindweco_plugin_api_delete_indexed_items(
                    $base_url,
                    $new_token,
                    $row->category_id,
                    $row->item_id
                );
            }
        }
    }

    $wpdb->delete(
        $table,
        array( 'file_id' => $attachment_id ),
        array( '%d' )
    );
}

add_action( 'wp_ajax_delete-post', 'mindweco_intercept_media_delete', 1 );

function mindweco_intercept_media_delete() {
    $post_id = absint( $_POST['id'] ?? 0 );
    if ( ! $post_id ) return;

    $post = get_post( $post_id );
    if ( ! $post || $post->post_type !== 'attachment' ) return;

    $supported = array(
        'application/pdf',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    );

    if ( ! in_array( $post->post_mime_type, $supported, true ) ) return;

    global $wpdb;
    $table = $wpdb->prefix . 'mindweco_indexed_media_files';

    $row = $wpdb->get_row(
        $wpdb->prepare(
            "SELECT item_id, category_id FROM `{$table}` WHERE file_id = %d LIMIT 1",
            $post_id
        )
    );

    if ( ! $row ) return;

    $options  = get_option( 'mindweco_plugin_options', array() );
    $base_url = sanitize_text_field( $options['base_url'] ?? '' );
    $token    = mindweco_decrypt_api_key( get_option( 'mindweco_plugin_access_token', '' ) );

    if ( empty( $base_url ) || empty( $token ) ) return;

    $fresh_token = mindweco_plugin_refresh_token();
    if ( $fresh_token ) {
        $token = $fresh_token;
    }

    mindweco_plugin_api_delete_indexed_items(
        $base_url,
        $token,
        $row->category_id,
        $row->item_id
    );

    $wpdb->delete(
        $table,
        array( 'file_id' => $post_id ),
        array( '%d' )
    );
}