<?php
/* Copyright (C) 2026 ZUGFeRD Import Module
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 */

/**
 * \file    class/productmapping.class.php
 * \ingroup importzugferd
 * \brief   Class for product mapping (supplier article numbers to products)
 */

require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';

/**
 * Class ProductMapping
 * Maps supplier article numbers to Dolibarr products
 */
class ProductMapping extends CommonObject
{
    /**
     * @var string ID to identify managed object
     */
    public $element = 'productmapping';

    /**
     * @var string Name of table without prefix
     */
    public $table_element = 'importzugferd_productmapping';

    /**
     * @var int Does object support multicompany
     */
    public $ismultientitymanaged = 1;

    /**
     * @var int Supplier ID
     */
    public $fk_soc;

    /**
     * @var string Supplier article number
     */
    public $supplier_ref;

    /**
     * @var int Product ID
     */
    public $fk_product;

    /**
     * @var string EAN/GTIN
     */
    public $ean;

    /**
     * @var string Manufacturer article number
     */
    public $manufacturer_ref;

    /**
     * @var string Description
     */
    public $description;

    /**
     * @var int Priority
     */
    public $priority = 0;

    /**
     * @var int Active flag
     */
    public $active = 1;

    /**
     * @var string Date creation
     */
    public $date_creation;

    /**
     * @var int User creator
     */
    public $fk_user_creat;

    /**
     * @var int User modifier
     */
    public $fk_user_modif;

    /**
     * Constructor
     *
     * @param DoliDB $db Database handler
     */
    public function __construct($db)
    {
        $this->db = $db;
    }

    /**
     * Create object into database
     *
     * @param User $user User that creates
     * @return int <0 if KO, Id of created object if OK
     */
    public function create($user)
    {
        global $conf;

        $this->entity = $conf->entity;

        if (empty($this->date_creation)) {
            $this->date_creation = dol_now();
        }

        $this->fk_user_creat = $user->id;

        $sql = "INSERT INTO " . MAIN_DB_PREFIX . $this->table_element . " (";
        $sql .= "fk_soc, supplier_ref, fk_product, ean, manufacturer_ref,";
        $sql .= "description, priority, active, date_creation, fk_user_creat, entity";
        $sql .= ") VALUES (";
        $sql .= (int) $this->fk_soc . ",";
        $sql .= "'" . $this->db->escape($this->supplier_ref) . "',";
        $sql .= (int) $this->fk_product . ",";
        $sql .= "'" . $this->db->escape($this->ean) . "',";
        $sql .= "'" . $this->db->escape($this->manufacturer_ref) . "',";
        $sql .= "'" . $this->db->escape($this->description) . "',";
        $sql .= (int) $this->priority . ",";
        $sql .= (int) $this->active . ",";
        $sql .= "'" . $this->db->escape($this->db->idate($this->date_creation)) . "',";
        $sql .= (int) $this->fk_user_creat . ",";
        $sql .= (int) $this->entity;
        $sql .= ")";

        dol_syslog(get_class($this) . "::create", LOG_DEBUG);
        $resql = $this->db->query($sql);

        if (!$resql) {
            $this->error = $this->db->lasterror();
            return -1;
        }

        $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
        return $this->id;
    }

    /**
     * Load object in memory from database
     *
     * @param int $id Id object
     * @return int <0 if KO, 0 if not found, >0 if OK
     */
    public function fetch($id)
    {
        $sql = "SELECT rowid, fk_soc, supplier_ref, fk_product, ean, manufacturer_ref,";
        $sql .= " description, priority, active, date_creation, tms, fk_user_creat, fk_user_modif, entity";
        $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element;
        $sql .= " WHERE rowid = " . (int) $id;

        dol_syslog(get_class($this) . "::fetch", LOG_DEBUG);
        $resql = $this->db->query($sql);

        if ($resql) {
            if ($this->db->num_rows($resql)) {
                $obj = $this->db->fetch_object($resql);

                $this->id = $obj->rowid;
                $this->fk_soc = $obj->fk_soc;
                $this->supplier_ref = $obj->supplier_ref;
                $this->fk_product = $obj->fk_product;
                $this->ean = $obj->ean;
                $this->manufacturer_ref = $obj->manufacturer_ref;
                $this->description = $obj->description;
                $this->priority = $obj->priority;
                $this->active = $obj->active;
                $this->date_creation = $this->db->jdate($obj->date_creation);
                $this->tms = $this->db->jdate($obj->tms);
                $this->fk_user_creat = $obj->fk_user_creat;
                $this->fk_user_modif = $obj->fk_user_modif;
                $this->entity = $obj->entity;

                $this->db->free($resql);
                return 1;
            } else {
                $this->db->free($resql);
                return 0;
            }
        } else {
            $this->error = $this->db->lasterror();
            return -1;
        }
    }

    /**
     * Update object in database
     *
     * @param User $user User that modifies
     * @return int <0 if KO, >0 if OK
     */
    public function update($user)
    {
        $this->fk_user_modif = $user->id;

        $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET";
        $sql .= " fk_soc = " . (int) $this->fk_soc . ",";
        $sql .= " supplier_ref = '" . $this->db->escape($this->supplier_ref) . "',";
        $sql .= " fk_product = " . (int) $this->fk_product . ",";
        $sql .= " ean = '" . $this->db->escape($this->ean) . "',";
        $sql .= " manufacturer_ref = '" . $this->db->escape($this->manufacturer_ref) . "',";
        $sql .= " description = '" . $this->db->escape($this->description) . "',";
        $sql .= " priority = " . (int) $this->priority . ",";
        $sql .= " active = " . (int) $this->active . ",";
        $sql .= " fk_user_modif = " . (int) $this->fk_user_modif;
        $sql .= " WHERE rowid = " . (int) $this->id;

        dol_syslog(get_class($this) . "::update", LOG_DEBUG);
        $resql = $this->db->query($sql);

        if (!$resql) {
            $this->error = $this->db->lasterror();
            return -1;
        }

        return 1;
    }

    /**
     * Delete object from database
     *
     * @param User $user User that deletes
     * @return int <0 if KO, >0 if OK
     */
    public function delete($user)
    {
        $sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element;
        $sql .= " WHERE rowid = " . (int) $this->id;

        dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
        $resql = $this->db->query($sql);

        if (!$resql) {
            $this->error = $this->db->lasterror();
            return -1;
        }

        return 1;
    }

    /**
     * Find product by supplier reference
     *
     * @param int $fk_soc Supplier ID
     * @param string $supplier_ref Supplier article number
     * @return int Product ID or 0 if not found
     */
    public function findProductBySupplierRef($fk_soc, $supplier_ref)
    {
        global $conf;

        // First check our mapping table
        $sql = "SELECT fk_product FROM " . MAIN_DB_PREFIX . $this->table_element;
        $sql .= " WHERE fk_soc = " . (int) $fk_soc;
        $sql .= " AND supplier_ref = '" . $this->db->escape($supplier_ref) . "'";
        $sql .= " AND active = 1";
        $sql .= " AND entity = " . (int) $conf->entity;
        $sql .= " ORDER BY priority DESC";
        $sql .= " LIMIT 1";

        $resql = $this->db->query($sql);
        if ($resql && $this->db->num_rows($resql) > 0) {
            $obj = $this->db->fetch_object($resql);
            return (int) $obj->fk_product;
        }

        return 0;
    }

    /**
     * Find product by EAN
     *
     * @param string $ean EAN/GTIN
     * @return int Product ID or 0 if not found
     */
    public function findProductByEan($ean)
    {
        global $conf;

        if (empty($ean)) {
            return 0;
        }

        // First check our mapping table
        $sql = "SELECT fk_product FROM " . MAIN_DB_PREFIX . $this->table_element;
        $sql .= " WHERE ean = '" . $this->db->escape($ean) . "'";
        $sql .= " AND active = 1";
        $sql .= " AND entity = " . (int) $conf->entity;
        $sql .= " LIMIT 1";

        $resql = $this->db->query($sql);
        if ($resql && $this->db->num_rows($resql) > 0) {
            $obj = $this->db->fetch_object($resql);
            return (int) $obj->fk_product;
        }

        // Check product barcode
        $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "product";
        $sql .= " WHERE barcode = '" . $this->db->escape($ean) . "'";
        $sql .= " AND entity IN (" . getEntity('product') . ")";
        $sql .= " LIMIT 1";

        $resql = $this->db->query($sql);
        if ($resql && $this->db->num_rows($resql) > 0) {
            $obj = $this->db->fetch_object($resql);
            return (int) $obj->rowid;
        }

        return 0;
    }

    /**
     * Find product by supplier price reference
     *
     * @param int $fk_soc Supplier ID
     * @param string $ref_fourn Supplier reference
     * @return int Product ID or 0 if not found
     */
    public function findProductBySupplierPrice($fk_soc, $ref_fourn)
    {
        global $conf;

        $sql = "SELECT fk_product FROM " . MAIN_DB_PREFIX . "product_fournisseur_price";
        $sql .= " WHERE fk_soc = " . (int) $fk_soc;
        $sql .= " AND ref_fourn = '" . $this->db->escape($ref_fourn) . "'";
        $sql .= " AND entity = " . (int) $conf->entity;
        $sql .= " LIMIT 1";

        $resql = $this->db->query($sql);
        if ($resql && $this->db->num_rows($resql) > 0) {
            $obj = $this->db->fetch_object($resql);
            return (int) $obj->fk_product;
        }

        return 0;
    }

    /**
     * Find product using all available methods
     *
     * @param int $fk_soc Supplier ID
     * @param array $product_data Product data from ZUGFeRD (seller_id, buyer_id, global_id, name)
     * @return array Array with 'fk_product' and 'method' used
     */
    public function findProduct($fk_soc, $product_data)
    {
        $result = array('fk_product' => 0, 'method' => '');

        // 1. Check our mapping table with supplier reference
        if (!empty($product_data['seller_id'])) {
            $fk_product = $this->findProductBySupplierRef($fk_soc, $product_data['seller_id']);
            if ($fk_product > 0) {
                return array('fk_product' => $fk_product, 'method' => 'mapping_supplier_ref');
            }
        }

        // 2. Check supplier price table
        if (!empty($product_data['seller_id'])) {
            $fk_product = $this->findProductBySupplierPrice($fk_soc, $product_data['seller_id']);
            if ($fk_product > 0) {
                return array('fk_product' => $fk_product, 'method' => 'supplier_price');
            }
        }

        // 3. Check by EAN/GTIN
        if (!empty($product_data['global_id'])) {
            $fk_product = $this->findProductByEan($product_data['global_id']);
            if ($fk_product > 0) {
                return array('fk_product' => $fk_product, 'method' => 'ean');
            }
        }

        // 4. Check buyer assigned ID (our article number)
        if (!empty($product_data['buyer_id'])) {
            global $conf;
            $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "product";
            $sql .= " WHERE ref = '" . $this->db->escape($product_data['buyer_id']) . "'";
            $sql .= " AND entity IN (" . getEntity('product') . ")";
            $sql .= " LIMIT 1";

            $resql = $this->db->query($sql);
            if ($resql && $this->db->num_rows($resql) > 0) {
                $obj = $this->db->fetch_object($resql);
                return array('fk_product' => (int) $obj->rowid, 'method' => 'buyer_ref');
            }
        }

        return $result;
    }

    /**
     * Get all mappings for a supplier
     *
     * @param int $fk_soc Supplier ID
     * @param int $limit Limit results
     * @param int $offset Offset
     * @return array Array of mappings
     */
    public function fetchAllBySupplier($fk_soc, $limit = 0, $offset = 0)
    {
        global $conf;

        $mappings = array();

        $sql = "SELECT pm.rowid, pm.fk_soc, pm.supplier_ref, pm.fk_product, pm.ean,";
        $sql .= " pm.manufacturer_ref, pm.description, pm.priority, pm.active,";
        $sql .= " p.ref as product_ref, p.label as product_label";
        $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as pm";
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = pm.fk_product";
        $sql .= " WHERE pm.fk_soc = " . (int) $fk_soc;
        $sql .= " AND pm.entity = " . (int) $conf->entity;
        $sql .= " ORDER BY pm.supplier_ref ASC";

        if ($limit > 0) {
            $sql .= " LIMIT " . $limit;
            if ($offset > 0) {
                $sql .= " OFFSET " . $offset;
            }
        }

        $resql = $this->db->query($sql);
        if ($resql) {
            while ($obj = $this->db->fetch_object($resql)) {
                $mappings[] = array(
                    'id' => $obj->rowid,
                    'fk_soc' => $obj->fk_soc,
                    'supplier_ref' => $obj->supplier_ref,
                    'fk_product' => $obj->fk_product,
                    'product_ref' => $obj->product_ref,
                    'product_label' => $obj->product_label,
                    'ean' => $obj->ean,
                    'manufacturer_ref' => $obj->manufacturer_ref,
                    'description' => $obj->description,
                    'priority' => $obj->priority,
                    'active' => $obj->active,
                );
            }
            $this->db->free($resql);
        }

        return $mappings;
    }

    /**
     * Count mappings for a supplier
     *
     * @param int $fk_soc Supplier ID
     * @return int Count
     */
    public function countBySupplier($fk_soc)
    {
        global $conf;

        $sql = "SELECT COUNT(*) as nb FROM " . MAIN_DB_PREFIX . $this->table_element;
        $sql .= " WHERE fk_soc = " . (int) $fk_soc;
        $sql .= " AND entity = " . (int) $conf->entity;

        $resql = $this->db->query($sql);
        if ($resql) {
            $obj = $this->db->fetch_object($resql);
            return (int) $obj->nb;
        }

        return 0;
    }
}
