<?php

namespace classes\CRUD;

use classes\MysqliVeu;
use Exception;

trait CRUDTrait
{
    protected MysqliVeu $database;

    public function setDatabaseConnection(MysqliVeu $database): void
    {
        $this->database = $database;
    }


    /**
     * Creates a new record in the specified database table with the provided data.
     *
     * @param string $table The name of the table where the new record will be inserted.
     * @param array $data An associative array containing column-value pairs for the new record.
     * @return void
     * @throws Exception
     */
    public function create(string $table, array $data): int
    {
        $columnsString = implode(', ', array_keys($data));

        // Builds placeholder handling values for SQL function
        $placeholdersArray = [];
        $params = [];
        foreach ($data as $key => $value)
        {
            if ($value === 'NOW()')
            {
                $placeholdersArray[] = $value;
            }
            else
            {
                $placeholdersArray[] = '?';
                $params[] = $value;
            }
        }

        $placeholdersString = implode(', ', $placeholdersArray);

        $sql = "INSERT INTO $table ($columnsString) VALUES ($placeholdersString)";

        $this->database->execute($sql, $params);

        return $this->database->getLastInsertedId();
    }


    public function readAll(string $table) {}


    public function read(string $table, $whereConditions) {}


    public function delete(string $table, int $whereConditions) {}


    /**
     * Updates existing records in the specified database table with the provided data and conditions.
     *
     * @param string $table The name of the table where the records will be updated.
     * @param array $data An associative array containing column-value pairs for the fields to be updated.
     * @param array $whereConditions An associative array containing column-value pairs used to build the WHERE clause.
     * @return bool
     * @throws Exception
     */
    public function update(string $table, array $data, array $whereConditions): bool
    {
        $columnsArray = [];
        $values = [];


        // Builds Columns placeholders
        foreach ($data as $column => $value)
        {
            if ($value === 'NOW()')
            {
                $columnsArray[] = "$column = $value";
            }
            else
            {
                $columnsArray[] = "$column = ?";
                $values[] = $value;
            }
        }

        $setString = implode(', ', $columnsArray);
        $whereConditions = $this->buildWhereConditions($whereConditions);
        $params = array_merge($values, $whereConditions['values']);

        $sql = "UPDATE $table SET $setString WHERE {$whereConditions['string']}";

        return $this->database->execute($sql, $params);
    }

    private function buildWhereConditions(array $whereConditions): array
    {
        $whereConditionsArray = [];
        $values = [];

        // Ensures whereConditions is a two-dimensional array for consistent processing
        if (!is_array($whereConditions[0]))
        {
            $whereConditions = [$whereConditions];
        }

        foreach ($whereConditions as $whereCondition)
        {
            [$column, $operator, $value] = $whereCondition;
            $whereConditionsArray[] = "$column $operator ?";
            $values[] = $value;
        }

        return [
            "string" => implode(' AND ', $whereConditionsArray),
            "values" => $values
        ];
    }
}
