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

if ( ! function_exists( 'newsai_validate_holiday_alert_row' ) ) {
	/**
	 * Validate one holiday row from bundled JSON before DB insert.
	 *
	 * @param mixed $alert Decoded JSON row.
	 * @return bool
	 */
	function newsai_validate_holiday_alert_row( $alert ) {
		if ( ! is_array( $alert ) ) {
			return false;
		}
		if ( empty( $alert['title'] ) || ! is_string( $alert['title'] ) ) {
			return false;
		}
		if ( ! isset( $alert['day'], $alert['month'], $alert['lead'] ) ) {
			return false;
		}
		$day   = (int) $alert['day'];
		$month = (int) $alert['month'];
		$lead  = (int) $alert['lead'];
		if ( $day < 1 || $day > 31 || $month < 1 || $month > 12 ) {
			return false;
		}
		if ( $lead < 0 || $lead > 365 ) {
			return false;
		}
		return trim( $alert['title'] ) !== '';
	}
}

add_action('admin_init', 'newsai_handle_bulk_import');
function newsai_handle_bulk_import() {
    if (isset($_POST['newsai_bulk_import_btn'])) {
        if (!isset($_POST['newsai_import_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['newsai_import_nonce'])), 'newsai_bulk_import')) {
            return;
        }

        global $wpdb;
        $table = $wpdb->prefix . 'newsai_alerts';
        
        $geo = strtolower( sanitize_text_field( function_exists( 'newsai_get_target_geo' ) ? newsai_get_target_geo() : 'US' ) );
        $allowed_geo = [
            'gr', 'cy', 'us', 'gb', 'de', 'fr', 'it', 'es', 'nl', 'be', 'pt', 'ru',
            'in', 'au', 'ca', 'il', 'ch', 'se', 'no', 'dk', 'fi', 'pl', 'at', 'ie',
        ];
        if ( ! in_array( $geo, $allowed_geo, true ) ) {
            $geo = 'gr';
        }
        $json_file = NEWSAI_PATH . "data/holidays-{$geo}.json";

        if (file_exists($json_file)) {
            $json_data = file_get_contents($json_file);
            $alerts = json_decode($json_data, true);

            if ( is_array( $alerts ) && ! empty( $alerts ) ) {
                foreach ( $alerts as $alert ) {
                    if ( ! newsai_validate_holiday_alert_row( $alert ) ) {
                        continue;
                    }
                    $title = sanitize_text_field( $alert['title'] );
                    $day   = (int) $alert['day'];
                    $month = (int) $alert['month'];
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
                    $exists = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$table} WHERE title = %s AND day = %d AND month = %d", $title, $day, $month ) );

                    if (!$exists) {
                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                        $wpdb->insert(
                            $table,
                            [
                                'title'     => $title,
                                'day'       => $day,
                                'month'     => $month,
                                'year'      => 0,
                                'lead_days' => (int) $alert['lead'],
                                'author_id' => 0,
                            ]
                        );
                    }
                }
                if ( function_exists( 'newsai_invalidate_task_due_metrics_cache' ) ) {
                    newsai_invalidate_task_due_metrics_cache();
                }
                wp_safe_redirect(admin_url('admin.php?page=newsai-settings&tab=alerts&msg=imported'));
                exit;
            }
       } else {
            $msg = sprintf(
                /* translators: %s: ISO-2 country code (e.g. GR) */
                __( 'File for country %s not found.', 'newsroom-ai-assistant' ),
                $geo
            );
            wp_die( esc_html( $msg ) );
        }
    }
}
// ΤΕΛΟΣ ΑΡΧΕΙΟΥ

if ( ! function_exists( 'newsai_create_editorial_task' ) ) {
	/**
	 * Insert one row into wp_newsai_alerts (shared by dashboard form, brief v2, decay radar).
	 *
	 * @param array $args {
	 *     @type string $title          Task title (required).
	 *     @type string $notes          Long-form brief / instructions.
	 *     @type string $target_keyword SEO keyword.
	 *     @type string $ref_link       Reference URL.
	 *     @type int    $author_id      Assignee (0 = pool).
	 *     @type int    $lead_days      Lead days before due date.
	 *     @type int    $due_ts         Due date Unix timestamp (site TZ). Default +7 days.
	 * }
	 * @return int|false New alert ID or false.
	 */
	function newsai_create_editorial_task( $args ) {
		global $wpdb;

		$title = isset( $args['title'] ) ? sanitize_text_field( (string) $args['title'] ) : '';
		if ( $title === '' ) {
			return false;
		}

		$table = $wpdb->prefix . 'newsai_alerts';
		$exists = $wpdb->get_var(
			$wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table ) )
		);
		if ( ! $exists ) {
			return false;
		}

		$due_ts = isset( $args['due_ts'] ) ? (int) $args['due_ts'] : 0;
		if ( $due_ts < 1 ) {
			$due_ts = current_time( 'timestamp' ) + ( 7 * DAY_IN_SECONDS );
		}

		$data = [
			'title'          => $title,
			'day'            => (int) gmdate( 'd', $due_ts ),
			'month'          => (int) gmdate( 'm', $due_ts ),
			'year'           => (int) gmdate( 'Y', $due_ts ),
			'lead_days'      => max( 1, min( 90, (int) ( $args['lead_days'] ?? 7 ) ) ),
			'author_id'      => max( 0, (int) ( $args['author_id'] ?? 0 ) ),
			'notes'          => isset( $args['notes'] ) ? sanitize_textarea_field( (string) $args['notes'] ) : '',
			'target_keyword' => isset( $args['target_keyword'] ) ? sanitize_text_field( (string) $args['target_keyword'] ) : '',
			'ref_link'       => isset( $args['ref_link'] ) ? esc_url_raw( (string) $args['ref_link'] ) : '',
			'status'         => 'pending',
		];

		$cols = $wpdb->get_col( "DESC {$table}", 0 );
		if ( is_array( $cols ) ) {
			if ( ! in_array( 'target_keyword', $cols, true ) ) {
				unset( $data['target_keyword'] );
			}
			if ( ! in_array( 'ref_link', $cols, true ) ) {
				unset( $data['ref_link'] );
			}
			if ( ! in_array( 'status', $cols, true ) ) {
				unset( $data['status'] );
			}
		}

		$inserted = $wpdb->insert( $table, $data );
		if ( ! $inserted ) {
			return false;
		}

		$new_id = (int) $wpdb->insert_id;
		if ( $new_id > 0 ) {
			if ( function_exists( 'nros_clear_task_transients' ) ) {
				nros_clear_task_transients();
			}
			if ( function_exists( 'newsai_invalidate_task_due_metrics_cache' ) ) {
				newsai_invalidate_task_due_metrics_cache();
			}
			do_action( 'newsai_task_assigned', $new_id, true, 0 );
		}

		return $new_id > 0 ? $new_id : false;
	}
}

if ( ! function_exists( 'newsai_format_brief_as_task_notes' ) ) {
	/**
	 * Turn structured content-brief payload into task notes text.
	 *
	 * @param array $brief Brief data from newsai_ai_task_content_brief().
	 * @return string
	 */
	function newsai_format_brief_as_task_notes( $brief ) {
		if ( ! is_array( $brief ) ) {
			return '';
		}
		$lines = [];
		if ( ! empty( $brief['angle'] ) ) {
			$lines[] = __( 'Angle:', 'newsroom-ai-assistant' ) . ' ' . sanitize_text_field( (string) $brief['angle'] );
		}
		if ( ! empty( $brief['target_keywords'] ) && is_array( $brief['target_keywords'] ) ) {
			$lines[] = __( 'Keywords:', 'newsroom-ai-assistant' ) . ' ' . implode( ', ', array_map( 'sanitize_text_field', $brief['target_keywords'] ) );
		}
		if ( ! empty( $brief['outline'] ) && is_array( $brief['outline'] ) ) {
			$lines[] = __( 'Outline:', 'newsroom-ai-assistant' );
			foreach ( $brief['outline'] as $item ) {
				$item = sanitize_text_field( (string) $item );
				if ( $item !== '' ) {
					$lines[] = '- ' . $item;
				}
			}
		}
		if ( ! empty( $brief['competing_urls'] ) && is_array( $brief['competing_urls'] ) ) {
			$lines[] = __( 'Competing coverage:', 'newsroom-ai-assistant' );
			foreach ( $brief['competing_urls'] as $row ) {
				if ( ! is_array( $row ) ) {
					continue;
				}
				$t = sanitize_text_field( (string) ( $row['title'] ?? '' ) );
				$u = esc_url_raw( (string) ( $row['url'] ?? '' ) );
				$w = sanitize_text_field( (string) ( $row['why'] ?? '' ) );
				$line = $t !== '' ? $t : $u;
				if ( $u !== '' ) {
					$line .= ' (' . $u . ')';
				}
				if ( $w !== '' ) {
					$line .= ' — ' . $w;
				}
				if ( $line !== '' ) {
					$lines[] = '- ' . $line;
				}
			}
		}
		if ( ! empty( $brief['geo'] ) ) {
			$lines[] = __( 'Target geo:', 'newsroom-ai-assistant' ) . ' ' . sanitize_text_field( (string) $brief['geo'] );
		}
		if ( ! empty( $brief['topic'] ) ) {
			$lines[] = __( 'Topic seed:', 'newsroom-ai-assistant' ) . ' ' . sanitize_text_field( (string) $brief['topic'] );
		}
		$lines[] = __( 'Source: AI content brief', 'newsroom-ai-assistant' );
		return implode( "\n", $lines );
	}
}