<?php
/**
 * Conversation AJAX handlers for MindWebConcierge.
 *
 * @package MindWebConcierge
 */

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

add_action( 'wp_ajax_mindweco_get_conversations_by_date', 'mindweco_get_conversations_by_date_ajax' );

function mindweco_get_conversations_by_date_ajax() {
	check_ajax_referer( 'mindweco_admin_nonce', 'nonce' );

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

	global $wpdb;

	$start_date = sanitize_text_field( wp_unslash( $_POST['start_date'] ?? '' ) );
	$end_date   = sanitize_text_field( wp_unslash( $_POST['end_date'] ?? '' ) );

	if ( empty( $start_date ) || empty( $end_date ) ) {
		wp_send_json_error( 'Please provide both start and end dates' );
		return;
	}

	if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $start_date ) ||
		 ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $end_date ) ) {
		wp_send_json_error( 'Invalid date format. Use YYYY-MM-DD.' );
		return;
	}

	$start_datetime = $start_date . ' 00:00:00';
	$end_datetime   = $end_date . ' 23:59:59';
	$table          = $wpdb->prefix . 'mindweco_conversations';

	$conversations = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT
				c.*,
				COUNT(q.id)       AS total_questions,
				MIN(q.created_at) AS first_question_at
			FROM `{$table}` c
			LEFT JOIN `{$wpdb->prefix}mindweco_questions` q ON q.conversation_id = c.id
			WHERE c.created_at BETWEEN %s AND %s
			GROUP BY c.id
			ORDER BY c.created_at DESC",
			$start_datetime,
			$end_datetime
		)
	);

	if ( empty( $conversations ) ) {
		wp_send_json_success(
			array(
				'conversations' => array(),
				'message'       => 'No conversations found for this date range',
			)
		);
		return;
	}

	wp_send_json_success(
		array(
			'conversations' => $conversations,
			'total'         => count( $conversations ),
		)
	);
}


add_action( 'wp_ajax_mindweco_get_conversations', 'mindweco_get_conversations_ajax' );

function mindweco_get_local_conversation_questions_for_admin( $conv_id ) {
	global $wpdb;

	return $wpdb->get_results(
		$wpdb->prepare(
			"SELECT
				q.id, q.question_text, q.page_id, q.question_page_based, q.created_at,
				r.response_text, r.created_at AS response_at
			FROM `{$wpdb->prefix}mindweco_questions` q
			LEFT JOIN `{$wpdb->prefix}mindweco_responses` r ON r.question_id = q.id
			WHERE q.conversation_id = %s
			ORDER BY q.created_at ASC",
			$conv_id
		)
	);
}

function mindweco_get_admin_conversation_messages( $conv_id ) {
	if ( function_exists( 'mindweco_get_remote_history_for_conversation' ) ) {
		$remote_history = mindweco_get_remote_history_for_conversation( $conv_id );
		if ( is_array( $remote_history ) && ! empty( $remote_history ) ) {
			return $remote_history;
		}
	}

	$questions = mindweco_get_local_conversation_questions_for_admin( $conv_id );
	if ( empty( $questions ) ) {
		return array();
	}

	$messages = array();
	foreach ( $questions as $question ) {
		if ( ! empty( $question->question_text ) ) {
			$messages[] = array(
				'role'      => 'user',
				'kind'      => 'conversation_question',
				'message'   => $question->question_text,
				'timestamp' => $question->created_at,
			);
		}

		if ( ! empty( $question->response_text ) ) {
			$messages[] = array(
				'role'      => 'bot',
				'kind'      => 'conversation_answer',
				'message'   => $question->response_text,
				'timestamp' => $question->response_at ?: $question->created_at,
			);
		}
	}

	return $messages;
}

function mindweco_admin_messages_to_pdf_rows( array $messages ) {
	$rows = array();

	foreach ( $messages as $message ) {
		$role = isset( $message['role'] ) ? (string) $message['role'] : 'bot';
		if ( 'operator' === $role ) {
			$label = 'Operator message';
		} elseif ( 'user' === $role ) {
			$label = 'User message';
		} else {
			$label = 'Assistant message';
		}

		$rows[] = (object) array(
			'question_text' => $label,
			'created_at'    => isset( $message['timestamp'] ) ? $message['timestamp'] : '',
			'response_text' => isset( $message['message'] ) ? $message['message'] : '',
			'response_at'   => isset( $message['timestamp'] ) ? $message['timestamp'] : '',
		);
	}

	return $rows;
}

function mindweco_get_conversations_ajax() {
	check_ajax_referer( 'mindweco_admin_nonce', 'nonce' );

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

	global $wpdb;

	$conv_id = sanitize_text_field( wp_unslash( $_POST['conversation_id'] ?? '' ) );

	if ( empty( $conv_id ) ) {
		wp_send_json_error( 'Invalid ID' );
		return;
	}

	$messages = mindweco_get_admin_conversation_messages( $conv_id );
	if ( ! empty( $messages ) ) {
		wp_send_json_success(
			array(
				'mode'     => 'messages',
				'messages' => $messages,
			)
		);
		return;
	}

	$questions = mindweco_get_local_conversation_questions_for_admin( $conv_id );

	wp_send_json_success( $questions );
}

add_action( 'wp_ajax_mindweco_download_conversation_pdf', 'mindweco_download_conversation_pdf_ajax' );

function mindweco_download_conversation_pdf_ajax() {
	check_ajax_referer( 'mindweco_admin_nonce', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Unauthorized', 'mind-web-concierge' ), '', array( 'response' => 403 ) );
	}

	global $wpdb;

	$conv_id = sanitize_text_field( wp_unslash( $_GET['conversation_id'] ?? '' ) );

	if ( empty( $conv_id ) ) {
		wp_die( esc_html__( 'Invalid conversation ID', 'mind-web-concierge' ), '', array( 'response' => 400 ) );
	}

	$conversation = $wpdb->get_row(
		$wpdb->prepare(
			"SELECT * FROM `{$wpdb->prefix}mindweco_conversations` WHERE id = %s",
			$conv_id
		)
	);

	if ( ! $conversation ) {
		wp_die( esc_html__( 'Conversation not found', 'mind-web-concierge' ), '', array( 'response' => 404 ) );
	}

	$messages = mindweco_get_admin_conversation_messages( $conv_id );
	if ( ! empty( $messages ) ) {
		$questions = mindweco_admin_messages_to_pdf_rows( $messages );
	} else {
		$questions = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT
					q.question_text, q.created_at,
					r.response_text, r.created_at AS response_at
				FROM `{$wpdb->prefix}mindweco_questions` q
				LEFT JOIN `{$wpdb->prefix}mindweco_responses` r ON r.question_id = q.id
				WHERE q.conversation_id = %s
				ORDER BY q.created_at ASC",
				$conv_id
			)
		);
	}

	$pdf = mindweco_generate_formal_pdf(
		$conversation,
		$questions ? $questions : array()
	);

	if ( ob_get_length() ) {
		ob_clean();
	}

	$filename = 'conversation-' . sanitize_file_name( $conv_id ) . '.pdf';

	nocache_headers();
	header( 'Content-Type: application/pdf' );
	header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
	header( 'Content-Length: ' . strlen( $pdf ) );
	echo $pdf; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Binary PDF response.
	exit;
}

function mindweco_generate_formal_pdf( object $conversation, array $questions ): string {

	$PW = 612; $PH = 792;
	$ML = 60;  $MR = 552;
	$MT = 732; $MB = 70;
	$CW = 492;

	$C_BLACK       = '0.087 0.122 0.200'; 
	$C_DARK        = '0.184 0.365 0.384'; 
	$C_TEXT        = '0.133 0.157 0.192'; 
	$C_MID         = '0.322 0.380 0.420'; 
	$C_GREY        = '0.455 0.502 0.541'; 
	$C_RULE        = '0.847 0.871 0.894'; 
	$C_LIGHT       = '0.953 0.969 0.973'; 
	$C_ALITE       = '0.980 0.984 0.988'; 
	$C_HEADER_RULE = '0.545 0.651 0.667'; 
	$C_HEADER_META = '0.788 0.827 0.843'; 
	$C_WHITE       = '1 1 1';

	$objects   = array();
	$next_id   = 1;
	$cat_id    = $next_id++;   
	$pages_id  = $next_id++;   
	$font_r_id = $next_id++;  
	$font_b_id = $next_id++;   
	$font_i_id = $next_id++;  

	$page_ids = array();
	$stream   = '';
	$page_num = 0;
	$y        = 0;

	$site      = get_bloginfo( 'name' ) ?: 'Mind Web Concierge';
	$doc_title = 'Conversation Details';
	$doc_ref   = (string) ( $conversation->id ?? 'Unknown ID' );
	$ref_label = 'Reference No.:';


	$op = static function( string $s ) use ( &$stream ): void {
		$stream .= $s . "\n";
	};

	$enc = static function( string $t ): string {
		$t = str_replace( array( "\r\n", "\r", "\n", "\t" ), ' ', $t );
		if ( function_exists( 'iconv' ) ) {
			$c = @iconv( 'UTF-8', 'Windows-1252//TRANSLIT//IGNORE', $t );
			if ( false !== $c ) { $t = $c; }
		} else {
			$t = preg_replace( '/[^\x20-\x7E]/', '', $t );
		}
		return str_replace( array( '\\', '(', ')' ), array( '\\\\', '\\(', '\\)' ), $t );
	};

	$clean = static function( string $t ): string {
		$t = html_entity_decode( wp_strip_all_tags( $t ), ENT_QUOTES, get_bloginfo( 'charset' ) );
		return trim( preg_replace( '/\s+/u', ' ', $t ) );
	};

	$display_timezone = function_exists( 'wp_timezone' ) ? wp_timezone() : new DateTimeZone( 'UTC' );
	$conversation_timezone = trim( (string) ( $conversation->timezone ?? '' ) );
	if ( '' !== $conversation_timezone && in_array( $conversation_timezone, timezone_identifiers_list(), true ) ) {
		$display_timezone = new DateTimeZone( $conversation_timezone );
	}

	$format_datetime = static function( ?string $datetime ) use ( $display_timezone ): string {
		$datetime = trim( (string) $datetime );
		if ( '' === $datetime ) {
			return 'N/A';
		}

		$utc_timezone = new DateTimeZone( 'UTC' );
		$date         = DateTimeImmutable::createFromFormat( 'Y-m-d H:i:s', $datetime, $utc_timezone );

		if ( false === $date ) {
			try {
				$date = new DateTimeImmutable( $datetime, $utc_timezone );
			} catch ( Exception $e ) {
				return $datetime;
			}
		}

		$date = $date->setTimezone( $display_timezone );

		return function_exists( 'wp_date' )
			? wp_date( 'F j, Y, g:i A', $date->getTimestamp(), $display_timezone )
			: date_i18n( 'F j, Y, g:i A', $date->getTimestamp() );
	};
	
	$word_wrap = static function( string $text, int $max_chars ): array {
		$text  = trim( preg_replace( '/\s+/', ' ', $text ) );
		$words = explode( ' ', $text );
		$lines = array();
		$cur   = '';
		foreach ( $words as $word ) {
			if ( strlen( $word ) > $max_chars ) {
				if ( '' !== $cur ) { $lines[] = $cur; $cur = ''; }
				foreach ( str_split( $word, $max_chars ) as $chunk ) { $lines[] = $chunk; }
				continue;
			}
			if ( '' === $cur ) {
				$cur = $word;
			} elseif ( strlen( $cur ) + 1 + strlen( $word ) > $max_chars ) {
				$lines[] = $cur; $cur = $word;
			} else {
				$cur .= ' ' . $word;
			}
		}
		if ( '' !== $cur ) { $lines[] = $cur; }
		return $lines ?: array( '' );
	};

	$rect = static function( float $x, float $ry, float $w, float $h, string $col ) use ( $op ): void {
		$op( 'q' ); $op( $col . ' rg' );
		$op( sprintf( '%.2f %.2f %.2f %.2f re f', $x, $ry, $w, $h ) );
		$op( 'Q' );
	};

	$hrule = static function( float $x1, float $x2, float $ry, string $col, float $lw = 0.5 ) use ( $op ): void {
		$op( 'q' ); $op( $col . ' RG' ); $op( sprintf( '%.1f w', $lw ) );
		$op( sprintf( '%.2f %.2f m %.2f %.2f l S', $x1, $ry, $x2, $ry ) );
		$op( 'Q' );
	};

	$vrule = static function( float $x, float $y_bot, float $h, string $col, float $lw = 1.0 ) use ( $op ): void {
		$op( 'q' ); $op( $col . ' RG' ); $op( sprintf( '%.1f w', $lw ) );
		$op( sprintf( '%.2f %.2f m %.2f %.2f l S', $x, $y_bot, $x, $y_bot + $h ) );
		$op( 'Q' );
	};

	$txt = static function( string $text, float $x, float $ty, int $size, string $col, string $font = 'F1' ) use ( $op, $enc ): void {
		$op( 'q' ); $op( $col . ' rg' );
		$op( sprintf( 'BT /%s %d Tf %.2f %.2f Td (%s) Tj ET', $font, $size, $x, $ty, $enc( $text ) ) );
		$op( 'Q' );
	};

	$txt_wrap = static function( string $text, float $x, float $ty, int $size, float $max_w, string $col, string $font = 'F1', float $lh = 0 ) use ( $op, $enc, $word_wrap ): void {
		if ( $lh <= 0 ) { $lh = $size * 1.55; }
		$max_chars = max( 1, (int) floor( $max_w / ( $size * 0.50 ) ) );
		$lines     = $word_wrap( $text, $max_chars );
		$op( 'q' ); $op( $col . ' rg' );
		$op( sprintf( 'BT /%s %d Tf', $font, $size ) );
		foreach ( $lines as $i => $line ) {
			$op( sprintf( '%.2f %.2f Td (%s) Tj', ( 0 === $i ? $x : 0 ), ( 0 === $i ? $ty : -$lh ), $enc( $line ) ) );
		}
		$op( 'ET Q' );
	};

	$line_count = static function( string $text, int $max_chars ) use ( $word_wrap ): int {
		return count( $word_wrap( $text, $max_chars ) );
	};


	$new_page = static function() use ( &$stream, &$y, &$page_num, $MT ): void {
		$stream = ''; $y = $MT; $page_num++;
	};

	$finish_page = function() use (
		&$objects, &$page_ids, &$next_id, &$stream, &$page_num,
		$pages_id, $font_r_id, $font_b_id, $font_i_id, $PW, $PH,
		$hrule, $txt, $C_RULE, $C_GREY, $ML, $MR, $MB, &$site, &$doc_title, &$doc_ref
	): void {
		$fy = $MB - 10;
		$hrule( $ML, $MR, $fy + 10, $C_RULE, 0.4 );
		$txt( $site . '  |  ' . $doc_title . '  |  Ref. ' . $doc_ref, $ML, $fy - 2, 7, $C_GREY, 'F1' );
		$label = 'Page ' . $page_num;
		$txt( $label, $MR - strlen( $label ) * 3.8, $fy - 2, 7, $C_GREY, 'F1' );

		$pid = $next_id++; $cid = $next_id++;
		$fr  = '/F1 ' . $font_r_id . ' 0 R /F2 ' . $font_b_id . ' 0 R /F3 ' . $font_i_id . ' 0 R';
		$objects[ $cid ] = '<< /Length ' . strlen( $stream ) . " >>\nstream\n" . $stream . "\nendstream";
		$objects[ $pid ] = '<< /Type /Page /Parent ' . $pages_id . ' 0 R'
			. ' /MediaBox [0 0 ' . $PW . ' ' . $PH . ']'
			. ' /Resources << /Font << ' . $fr . ' >> >>'
			. ' /Contents ' . $cid . ' 0 R >>';
		$page_ids[] = $pid;
	};

	$maybe_break = function( float $needed ) use (
		&$y, $finish_page, $new_page, $MB, $rect, $hrule, $txt,
		$C_BLACK, $C_GREY, $C_RULE, $C_WHITE, $PW, $PH, $ML, $MR, &$site, &$doc_title, &$doc_ref
	): void {
		if ( $y - $needed >= $MB ) { return; }
		$finish_page();
		$new_page();
		$bh = 22; $by = $PH - $bh;
		$rect( 0, $by, $PW, $bh, $C_BLACK );
		$txt( strtoupper( $site ) . ' - ' . $doc_title . ' - Ref. ' . $doc_ref . ' (continued)', $ML, $by + 7, 7, $C_WHITE, 'F2' );
		$hrule( $ML, $MR, $by - 1, $C_RULE, 0.4 );
		$y = $by - 20;
	};

	$new_page();

	$bh = 80; $by = $PH - $bh;
	$rect( 0, $by, $PW, $bh, $C_BLACK );
	$txt( strtoupper( $site ), $ML, $by + 52, 16, $C_WHITE, 'F2' );
	$txt( $doc_title, $ML, $by + 32, 10, $C_WHITE, 'F1' );
	$hrule( $ML, $MR, $by + 24, $C_HEADER_RULE, 0.4 );
	$txt( $ref_label . ' ' . $doc_ref . '   |   Generated: ' . $format_datetime( current_time( 'mysql', true ) ), $ML, $by + 10, 8, $C_HEADER_META, 'F1' );

	$y = $by - 22;

	$hrule( $ML, $MR, $y, $C_RULE, 0.5 );
	$y -= 4;

	$pairs = array(
		array( 'Session ID',   $conversation->cookie_id   ?: 'N/A' ),
		array( 'Date & Time',  $format_datetime( $conversation->created_at ?? '' ) ),
		array( 'IP Address',   $conversation->ip_address  ?: 'N/A' ),
		array( 'Platform',     $conversation->platform    ?: 'N/A' ),
	);

	$col2_x  = $ML + 260;
	$row_h   = 16;
	$label_w = 80;

	foreach ( $pairs as $idx => $pair ) {
		$row_y = $y - ( $idx + 1 ) * $row_h;
		$txt( $pair[0] . ':', $ML, $row_y + 4, 8, $C_MID, 'F2' );
		$txt( $pair[1],       $ML + $label_w, $row_y + 4, 8, $C_TEXT, 'F1' );
	}

	$txt( 'Total questions:', $col2_x, $y - $row_h + 4, 8, $C_MID, 'F2' );
	$txt( (string) count( $questions ), $col2_x + 95, $y - $row_h + 4, 8, $C_TEXT, 'F1' );

	$y -= ( count( $pairs ) + 1 ) * $row_h + 8;
	$hrule( $ML, $MR, $y, $C_RULE, 0.5 );
	$y -= 20;

	$txt( 'QUESTION AND ANSWER DETAILS', $ML, $y, 11, $C_BLACK, 'F2' );
	$y -= 6;
	$hrule( $ML, $MR, $y, $C_BLACK, 1.0 );
	$y -= 18;

	if ( empty( $questions ) ) {
		$txt( 'No question and answer records were found for this session.', $ML, $y, 10, $C_MID, 'F1' );
	} else {
		$FS        = 10;
		$LH        = $FS * 1.55;
		$PAD_T     = 10;  
		$PAD_B     = 10;  
		$PAD_L     = 14;  
		$INNER_W   = $CW - $PAD_L - 6;
		$MAX_CHARS = (int) floor( $INNER_W / ( $FS * 0.50 ) );
		$BAR_W     = 1.5; 

		foreach ( $questions as $i => $qa ) {
			$q_text  = $clean( (string) $qa->question_text );
			$a_text  = $clean( (string) ( $qa->response_text ?: 'No response recorded.' ) );
			$q_lines = $line_count( $q_text, $MAX_CHARS );
			$a_lines = $line_count( $a_text, $MAX_CHARS );
			$q_h     = $PAD_T + $q_lines * $LH + $PAD_B;
			$a_h     = $PAD_T + $a_lines * $LH + $PAD_B;

			$maybe_break( 26 + $q_h + 6 + $a_h + 20 );

			$idx_y = $y - 14;
			$txt( 'Question & Answer ' . ( $i + 1 ), $ML, $idx_y + 2, 8, $C_DARK, 'F2' );
			if ( $qa->created_at ) {
				$ts_str = 'Asked: ' . $format_datetime( $qa->created_at );
				$txt( $ts_str, $MR - strlen( $ts_str ) * 3.8, $idx_y + 2, 8, $C_GREY, 'F3' );
			}
			$y -= 18;

			$q_block_y = $y - $q_h;
			$rect( $ML, $q_block_y, $CW, $q_h, $C_LIGHT );
			$vrule( $ML + 1, $q_block_y, $q_h, $C_DARK, $BAR_W );

			$q_label_y = $q_block_y + $q_h - $PAD_T;
			$txt( 'Question', $ML + $PAD_L, $q_label_y - 1, 7, $C_MID, 'F2' );
			$txt_wrap( $q_text, $ML + $PAD_L, $q_label_y - 10, $FS, $INNER_W, $C_TEXT, 'F1', $LH );
			$y -= $q_h + 6;

			$a_block_y = $y - $a_h;
			$rect( $ML, $a_block_y, $CW, $a_h, $C_ALITE );
			$vrule( $ML + 1, $a_block_y, $a_h, $C_GREY, $BAR_W );

			$a_label_y = $a_block_y + $a_h - $PAD_T;
			$txt( 'Answer', $ML + $PAD_L, $a_label_y - 1, 7, $C_GREY, 'F2' );
			if ( $qa->response_at ) {
				$rs_str = 'Answered: ' . $format_datetime( $qa->response_at );
				$txt( $rs_str, $MR - strlen( $rs_str ) * 3.8, $a_label_y - 1, 7, $C_GREY, 'F3' );
			}
			$txt_wrap( $a_text, $ML + $PAD_L, $a_label_y - 10, $FS, $INNER_W, $C_TEXT, 'F1', $LH );
			$y -= $a_h + 20;
		}
	}

	if ( $y > $MB + 30 ) {
		$hrule( $ML, $MR, $y, $C_RULE, 0.5 );
		$y -= 12;
		$txt( 'End of conversation details', $ML, $y, 8, $C_GREY, 'F3' );
	}

	$finish_page();

	$refs                  = implode( ' ', array_map( static fn( $id ) => $id . ' 0 R', $page_ids ) );
	$objects[ $cat_id ]    = '<< /Type /Catalog /Pages ' . $pages_id . ' 0 R >>';
	$objects[ $pages_id ]  = '<< /Type /Pages /Kids [' . $refs . '] /Count ' . count( $page_ids ) . ' >>';
	$objects[ $font_r_id ] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>';
	$objects[ $font_b_id ] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>';
	$objects[ $font_i_id ] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Oblique /Encoding /WinAnsiEncoding >>';

	ksort( $objects );
	$pdf     = "%PDF-1.4\n%\xe2\xe3\xcf\xd3\n";
	$offsets = array();
	foreach ( $objects as $id => $body ) {
		$offsets[ $id ] = strlen( $pdf );
		$pdf           .= $id . " 0 obj\n" . $body . "\nendobj\n";
	}
	$xref = strlen( $pdf );
	$cnt  = count( $objects ) + 1;
	$pdf .= "xref\n0 $cnt\n0000000000 65535 f \n";
	for ( $i = 1; $i < $cnt; $i++ ) {
		$pdf .= isset( $offsets[ $i ] )
			? sprintf( "%010d 00000 n \n", $offsets[ $i ] )
			: "0000000000 65535 f \n";
	}
	$pdf .= "trailer\n<< /Size $cnt /Root 1 0 R >>\nstartxref\n$xref\n%%EOF";

	return $pdf;
}


add_action( 'wp_ajax_mindweco_get_unanswered_questions', 'mindweco_get_unanswered_questions_ajax' );

function mindweco_get_unanswered_questions_ajax() {
	check_ajax_referer( 'mindweco_admin_nonce', 'nonce' );

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

	global $wpdb;

	$start_date = sanitize_text_field( wp_unslash( $_POST['start_date'] ?? '' ) );
	$end_date   = sanitize_text_field( wp_unslash( $_POST['end_date'] ?? '' ) );
	$date_where = '';

	if ( ! empty( $start_date ) || ! empty( $end_date ) ) {
		if ( empty( $start_date ) || empty( $end_date ) ) {
			wp_send_json_error( 'Please provide both start and end dates' );
			return;
		}

		if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $start_date ) ||
			! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $end_date ) ) {
			wp_send_json_error( 'Invalid date format. Use YYYY-MM-DD.' );
			return;
		}

		$date_where = $wpdb->prepare(
			'AND q.created_at BETWEEN %s AND %s',
			$start_date . ' 00:00:00',
			$end_date . ' 23:59:59'
		);
	} else {
		$today      = current_time( 'Y-m-d' );
		$date_where = $wpdb->prepare(
			'AND q.created_at BETWEEN %s AND %s',
			$today . ' 00:00:00',
			$today . ' 23:59:59'
		);
	}

	$unanswered_where = "(
		r.id IS NULL
		OR TRIM(r.response_text) = ''
		OR r.answer_status IN (1, 2)
	)";

	$questions = $wpdb->get_results(
		"SELECT
			q.id,
			q.conversation_id,
			q.question_text,
			q.page_id,
			q.question_page_based,
			q.created_at,
			c.cookie_id,
			c.ip_address,
			c.platform
		FROM `{$wpdb->prefix}mindweco_questions` q
		LEFT JOIN `{$wpdb->prefix}mindweco_responses` r ON r.question_id = q.id
		LEFT JOIN `{$wpdb->prefix}mindweco_conversations` c ON c.id = q.conversation_id
		WHERE {$unanswered_where}
		{$date_where}
		ORDER BY q.created_at DESC"
	);
		

	wp_send_json_success(
		array(
			'questions' => $questions ? $questions : array(),
			'total'     => $questions ? count( $questions ) : 0,
		)
	);
}


add_action( 'wp_ajax_mindweco_get_today_conversations', 'mindweco_get_today_conversations_ajax' );

function mindweco_get_today_conversations_ajax() {
	check_ajax_referer( 'mindweco_admin_nonce', 'nonce' );

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

	global $wpdb;

	$today        = current_time( 'Y-m-d' );
	$start_of_day = $today . ' 00:00:00';
	$end_of_day   = $today . ' 23:59:59';
	$table        = $wpdb->prefix . 'mindweco_conversations';

	$conversations = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT
				c.*,
				COUNT(q.id)       AS total_questions,
				MIN(q.created_at) AS first_question_at
			FROM `{$table}` c
			LEFT JOIN `{$wpdb->prefix}mindweco_questions` q ON q.conversation_id = c.id
			WHERE c.created_at BETWEEN %s AND %s
			GROUP BY c.id
			ORDER BY c.created_at DESC",
			$start_of_day,
			$end_of_day
		)
	);

	wp_send_json_success(
		array(
			'conversations' => $conversations ? $conversations : array(),
			'total'         => $conversations ? count( $conversations ) : 0,
		)
	);
}

add_action( 'wp_ajax_mindweco_delete_conversation', 'mindweco_delete_conversation_ajax' );

function mindweco_delete_conversation_ajax() {
	check_ajax_referer( 'mindweco_admin_nonce', 'nonce' );

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

	global $wpdb;

	$conv_id = sanitize_text_field( wp_unslash( $_POST['conversation_id'] ?? '' ) );
	if ( empty( $conv_id ) ) {
		wp_send_json_error( array( 'message' => 'Invalid conversation ID' ) );
		return;
	}

	$conversations_table = $wpdb->prefix . 'mindweco_conversations';
	$questions_table     = $wpdb->prefix . 'mindweco_questions';
	$responses_table     = $wpdb->prefix . 'mindweco_responses';

	$question_ids = $wpdb->get_col(
		$wpdb->prepare(
			"SELECT id FROM `{$questions_table}` WHERE conversation_id = %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name from $wpdb->prefix, not user input.
			$conv_id
		)
	);

	if ( ! empty( $question_ids ) ) {
		$placeholders = implode( ',', array_fill( 0, count( $question_ids ), '%d' ) );
		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM `{$responses_table}` WHERE question_id IN ({$placeholders})", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name from $wpdb->prefix, not user input.
				...$question_ids
			)
		);
	}

	$wpdb->delete( $questions_table, array( 'conversation_id' => $conv_id ), array( '%s' ) );
	$deleted = $wpdb->delete( $conversations_table, array( 'id' => $conv_id ), array( '%s' ) );

	if ( false === $deleted ) {
		wp_send_json_error( array( 'message' => 'Failed to delete conversation' ) );
		return;
	}

	wp_send_json_success( array( 'message' => 'Conversation deleted successfully' ) );
}
