<?php
/**
 * Database helpers for translation strings.
 *
 * @package WPR_Translate
 */

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

/**
 * Check if the strings table exists, caching the result per request.
 *
 * @return bool
 */
function wpr_translate_admin_strings_table_exists() {
    static $table_exists = null;

    // Reuse cached status within the same request.
    if ( null !== $table_exists ) {
        return $table_exists;
    }

    global $wpdb;

    // Check the database for the strings table.
    $table         = $wpdb->prefix . 'wpestate_translation_strings';
    $table_exists  = ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) === $table );

    return $table_exists;
}

/**
 * Ensure the processed flag exists on the strings table.
 *
 * @return bool
 */
function wpr_translate_admin_ensure_processed_column() {
    static $checked  = false;
    static $available = false;

    // Return cached status when already checked in this request.
    if ( $checked ) {
        return $available;
    }

    // Confirm the table exists before altering it.
    $has_table = wpr_translate_admin_strings_table_exists();

    if ( ! $has_table ) {
        $checked   = true;
        $available = false;

        return false;
    }

    global $wpdb;

    // Inspect the schema for the processed column.
    $table  = $wpdb->prefix . 'wpestate_translation_strings';

    $column = $wpdb->get_row(
        $wpdb->prepare( "SHOW COLUMNS FROM {$table} LIKE %s", 'processed' ),
        ARRAY_A
    );

    if ( empty( $column ) ) {
        // Add the processed column for export tracking when missing.
        $altered = $wpdb->query( "ALTER TABLE {$table} ADD processed TINYINT(1) UNSIGNED NOT NULL DEFAULT 0 AFTER status" );

        if ( false === $altered ) {
            $checked   = true;
            $available = false;

            return false;
        }
    }

    // Cache the availability status for later calls.
    $checked   = true;
    $available = true;

    return true;
}
