<?php

namespace Plainwork\DatabaseWordPress;

use Plainwork\Database\DatabaseAdapterInterface;
use Plainwork\Database\Exception\DatabaseException;

class WordPressDatabaseAdapter implements DatabaseAdapterInterface
{
    public function prepareQuery(string $sqlTemplate, array $vars): string
    {
        global $wpdb;

    /* replace core wpdb prefix */
        if (false !== strpos($sqlTemplate, '`wp_')) {
            $sqlTemplate = str_replace('`wp_', '`' . $wpdb->prefix, $sqlTemplate);
        }

        if (false === strpos($sqlTemplate, '%')) {
            return $sqlTemplate;
        }

    // check vars for LIKE starting/ending with %: '%admin%'
        foreach (array_keys($vars) as $ii) {
            $v = $vars[$ii];
            if (!is_string($v)) {
                continue;
            }
            if (('%' !== substr($v, 0, 1)) || ('%' !== substr($v, -1)) ) {
                continue;
            }

            $v = '%' . $wpdb->esc_like(substr($v, 1, -1)) . '%';
            $vars[$ii] = $v;
        }

// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
        return $wpdb->prepare($sqlTemplate, $vars);
    }

    public function query($sql)
    {
        global $wpdb;

        $ret = true;

        $isSelect = false;
        $isInsert = false;
        if (preg_match('/^\s*insert\s/i', $sql)) {
            $isInsert = true;
        } elseif (preg_match('/^\s*(select|show)\s/i', $sql)) {
            $isSelect = true;
        }

        if ($isSelect) {
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
            $ret = $wpdb->get_results($sql, ARRAY_A);
        } else {
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
            $ret = $wpdb->query($sql);
            if ($isInsert && (1 == $ret)) {
                $ret = $wpdb->insert_id;
            }
        }

        if ($wpdb->last_error) {
            throw new DatabaseException('WordPress database error: ' . $wpdb->last_error);
            // exit( $wpdb->last_error . '<br/>' . $sql );
            $ret = false;
            return $ret;
        }

        return $ret;
    }

    public function addIndexSql(string $table, array $cols): array
    {
        $indexName = $table . '_';
        $indexName .= join('_', $cols);
        $indexName .= '_index';
        $colString = join(', ', array_fill(0, count($cols), '%i'));

        $sql = 'ALTER TABLE %i ADD INDEX %i (' . $colString . ')';
        $args = array_merge([$table, $indexName], $cols);

        return [$sql, $args];
    }
}
