<?php
class ProductosData extends Extra
{
    public static $tablename = "productos";
    public $extra_fields;
    public $extra_fields_strings;

    public function __construct()
    {
        $this->extra_fields = array();
        $this->extra_fields_strings = array();
        $this->name = "";
        $this->lastname = "";
        $this->username = "";
        $this->email = "";
        $this->password = "";
        $this->created_at = "NOW()";
    }

    public function getBrand()
    {
        if (isset($this->brand_id) && (int)$this->brand_id > 0) {
            $brand = BrandData::getById($this->brand_id);
            if ($brand != null) {
                return $brand;
            }
        }

        $brandName = '';
        if (isset($this->marca) && trim((string)$this->marca) !== '') {
            $brandName = (string)$this->marca;
        } elseif (isset($this->marca_text) && trim((string)$this->marca_text) !== '') {
            $brandName = (string)$this->marca_text;
        }

        return (object) array('name' => $brandName !== '' ? $brandName : 'SIN MARCA');
    }

    public static function getById($id)
    {
        $sql = "select *, nombre as name, marca as marca_text, precio as price, imagen_url as image, producto_descripcion as description from " . self::$tablename . " where id=$id";
        $query = Executor::doit($sql);
        return Model::one($query[0], new ProductosData());
    }

    public static function getBy($k, $v)
    {
        $sql = "select *, nombre as name, marca as marca_text, precio as price, imagen_url as image, producto_descripcion as description from " . self::$tablename . " where $k=\"$v\"";
        $query = Executor::doit($sql);
        return Model::one($query[0], new ProductosData());
    }

    public static function getAll()
    {
        $sql = "select *, nombre as name, marca as marca_text, precio as price, imagen_url as image, producto_descripcion as description from " . self::$tablename;
        $query = Executor::doit($sql);
        return Model::many($query[0], new ProductosData());
    }

    public static function getAllBy($k, $v)
    {
        $sql = "select *, nombre as name, marca as marca_text, precio as price, imagen_url as image, producto_descripcion as description from " . self::$tablename . " where $k=\"$v\"";
        $query = Executor::doit($sql);
        return Model::many($query[0], new ProductosData());
    }

    public static function getLike($q)
    {
        $sql = "select *, nombre as name, marca as marca_text, precio as price, imagen_url as image, producto_descripcion as description from " . self::$tablename . " where nombre like '%$q%'";
        $query = Executor::doit($sql);
        return Model::many($query[0], new ProductosData());
    }

    public static function getAllFiltered(?string $warehouse, ?string $marca, ?string $q, int $min_total_stock, int $limit, int $offset): array
    {
        $sql = "SELECT id, nombre AS name, marca AS marca_text, precio AS price,
                       imagen_url AS image, producto_descripcion AS description,
                       sku_producto, sku_digicorp, url, pdf_url, last_updated,
                       stock_lp_centro, stock_lp_satelite, stock_lp_btl,
                       stock_lp_llojeta, stock_interior
                FROM " . self::$tablename . "
                WHERE 1=1";

        if ($warehouse !== null && $warehouse !== '' && $warehouse !== 'all') {
            $col = '';
            switch ($warehouse) {
                case 'centro':   $col = 'stock_lp_centro'; break;
                case 'satelite': $col = 'stock_lp_satelite'; break;
                case 'btl':      $col = 'stock_lp_btl'; break;
                case 'llojeta':  $col = 'stock_lp_llojeta'; break;
                case 'interior': $col = 'stock_interior'; break;
            }
            if ($col !== '') {
                $sql .= " AND $col > 0";
            }
        }

        if ($marca !== null && $marca !== '') {
            $sql .= " AND marca = '" . addslashes($marca) . "'";
        }

        if ($q !== null && $q !== '') {
            $escaped_q = addslashes($q);
            $sql .= " AND nombre LIKE '%$escaped_q%'";
        }

        $sql .= " ORDER BY nombre ASC LIMIT $limit OFFSET $offset";
        $query = Executor::doit($sql);
        return Model::many($query[0], new ProductosData());
    }

    public static function countFiltered(?string $warehouse, ?string $marca, ?string $q, int $min_total_stock): int
    {
        $sql = "SELECT COUNT(*) AS total FROM " . self::$tablename . " WHERE 1=1";

        if ($warehouse !== null && $warehouse !== '' && $warehouse !== 'all') {
            $col = '';
            switch ($warehouse) {
                case 'centro':   $col = 'stock_lp_centro'; break;
                case 'satelite': $col = 'stock_lp_satelite'; break;
                case 'btl':      $col = 'stock_lp_btl'; break;
                case 'llojeta':  $col = 'stock_lp_llojeta'; break;
                case 'interior': $col = 'stock_interior'; break;
            }
            if ($col !== '') {
                $sql .= " AND $col > 0";
            }
        }

        if ($marca !== null && $marca !== '') {
            $sql .= " AND marca = '" . addslashes($marca) . "'";
        }

        if ($q !== null && $q !== '') {
            $escaped_q = addslashes($q);
            $sql .= " AND nombre LIKE '%$escaped_q%'";
        }

        $query = Executor::doit($sql);
        $result = Model::one($query[0], new ProductosData());
        return $result->total ?? 0;
    }

    public static function getDistinctMarcas(): array
    {
        $sql = "SELECT DISTINCT marca FROM " . self::$tablename . " WHERE marca IS NOT NULL AND marca != '' ORDER BY marca ASC";
        $query = Executor::doit($sql);
        $rows = Model::many($query[0], new ProductosData());
        return array_map(fn($r) => $r->marca, $rows);
    }
}
