<?php
namespace Skeleton\Pdo;

use Firebase\JWT\JWT;
use Helpers\Log\LogSysteme;
use Helpers\Fichier\Fichier;

class PdoSkeleton extends \PDO
{


    protected $pdo;
    protected $statement;
    // phpcs:ignore
    protected $driver_options;
    // phpcs:ignore
    protected $input_parameters;
    protected $attribute;
    protected $value;
    protected $query;
    protected $lastInsertId;
    private int $countQueryError = 0;
    const FETCH_ASSOC= \PDO::FETCH_ASSOC;


    /**
     * @param string $host
     * @param string $user
     * @param string $pwd
     */
    public function __construct(string $host, string $user, string $pwd)
    {

        

        $this->pdo = new \PDO($host, $user, $pwd);
    }
    
    public function fetch($option = null)
    {
        
        // $last = file_get_contents('E:\\OXALYS\\ENV1\\Oxadata\\tmp\\requete BBA.txt');
        // file_put_contents('E:\\OXALYS\\ENV1\\Oxadata\\tmp\\requete BBA.txt', '
        // ------
        // '.$this->statement.$this->query.' => '.implode($this->input_parameters), FILE_APPEND);
        if ($this->statement != '') {
            $facture = $this->pdo->prepare($this->statement);
            $b = $facture->execute($this->input_parameters);
            if ($b === false) {
                $this->countQueryError++;
            }
            $values = $facture->fetch($option);


            if (is_array($values) && count($values) != 0) {
                foreach ($values as $key => $value) {
                    $values[$key] = rtrim($value);
                }
            }
            $this->reset();
            if ($values) {
                return $values;
            } else {
                return [];
            }
        } elseif ($this->query != '') {
            $values = $this->pdo->query($this->query)->fetch($option);

            if (is_array($values) && count($values) != 0) {
                foreach ($values as $key => $value) {
                    $values[$key] = rtrim($value);
                }
            }
            $this->reset();
            if ($values) {
                return $values;
            } else {
                return [];
            }
        }
    }
    
    public function fetchAll($option = null, $fetch_argument = null, $ctor_arg = array(), $rtrim = true)
    {
        
        // $last = file_get_contents('E:\\OXALYS\\ENV1\\Oxadata\\tmp\\requete BBA.txt');
        // file_put_contents('E:\\OXALYS\\ENV1\\Oxadata\\tmp\\requete BBA.txt', '
        // --------
        
        // '.$this->statement.$this->query.' => '.implode($this->input_parameters), FILE_APPEND);

        if ($this->statement != '') {
            $result = $this->pdo->prepare($this->statement);
            
            $b = $result->execute($this->input_parameters);
            if ($b === false) {
                $this->countQueryError++;
            }
            
            $this->reset();
            $values = $result->fetchAll($option);
        } elseif ($this->query != '') {
            $values = $this->pdo->query($this->query)->fetchAll($option);
        }
        
        if (is_array($values) && count($values) != 0) {
            foreach ($values as $key => $value) {
                if (is_array($value) && count($value) != 0) {
                    foreach ($value as $keyy => $valuee) {
                        if ($rtrim) {
                            $values[$key][$keyy] = rtrim($valuee);
                        } else {
                            $values[$key][$keyy] = $valuee;
                        }
                    }
                }
            }
        }
        
        $this->reset();
        
        if ($values) {
            return $values;
        } else {
            return [];
        }
    }
 
    public function query($query)
    {
        $this->query = $query;
        return $this;
    }


    public function prepare($statement, $driver_options = [])
    {
        $this->statement =$statement;
        $this->driver_options = $driver_options;
        return $this;
    }

    public function execute(array $input_parameters = [])
    {
        $this->input_parameters = $input_parameters;

        if (strpos(strtoupper($this->statement), 'UPDATE') !== false
            || strpos(strtoupper($this->statement), 'INSERT') !== false
            || strpos(strtoupper($this->statement), 'DELETE') !== false
        ) {
            $exec = $this->pdo->prepare($this->statement);
        
            $return = $exec->execute($input_parameters);

            if ($return === false) {
                $this->countQueryError++;
            }

            return $return;
            // $this->reset(); // TODO : what is that ?
        }
    }


    public function setAttribute($attribute, $value)
    {
        $this->attribute = $attribute;
        $this->value = $value;
    }

    public function reset()
    {
        $this->statement =  $this->driver_options= $this->input_parameters= $this->attribute= $this->value = $this->query = '';
    }

    public function lastInserstId()
    {
        return $this->lastInsertId;
    }


//_____________________________________________________________________________
// In order to support silent error for queries, commit is done only if no error occur
// TODO : this system does not work, fix it
    public function beginTransaction() :bool
    {
        $this->countQueryError = 0;
        return $this->beginTransaction();
    }

    public function commit() :bool
    {
        $i = $this->countQueryError;
        $this->countQueryError = 0;
        if ($i !== 0) {
            LogSysteme::prefixErrorLog('Rolling back');
            return $this->rollBack();
        }
        return $this->commit();
    }
}
