<?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    mapping.php
 * \ingroup importzugferd
 * \brief   Product mapping management
 */

// Load Dolibarr environment
$res = 0;
if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
    $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
}
$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME'];
$tmp2 = realpath(__FILE__);
$i = strlen($tmp) - 1;
$j = strlen($tmp2) - 1;
while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
    $i--;
    $j--;
}
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
    $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
}
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) {
    $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
}
if (!$res && file_exists("../main.inc.php")) {
    $res = @include "../main.inc.php";
}
if (!$res && file_exists("../../main.inc.php")) {
    $res = @include "../../main.inc.php";
}
if (!$res && file_exists("../../../main.inc.php")) {
    $res = @include "../../../main.inc.php";
}
if (!$res) {
    die("Include of main fails");
}

require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';

dol_include_once('/importzugferd/class/productmapping.class.php');
dol_include_once('/importzugferd/lib/importzugferd.lib.php');

// Load translation files
$langs->loadLangs(array("importzugferd@importzugferd", "products", "companies"));

// Security check
if (!$user->hasRight('importzugferd', 'mapping', 'write')) {
    accessforbidden();
}

// Get parameters
$action = GETPOST('action', 'aZ09');
$confirm = GETPOST('confirm', 'alpha');
$id = GETPOST('id', 'int');
$supplier_id = GETPOST('supplier_id', 'int');

// Form fields
$supplier_ref = GETPOST('supplier_ref', 'alpha');
$product_id = GETPOST('product_id', 'int');
$ean = GETPOST('ean', 'alpha');
$manufacturer_ref = GETPOST('manufacturer_ref', 'alpha');
$description = GETPOST('description', 'alpha');
$priority = GETPOST('priority', 'int');

// Initialize objects
$mapping = new ProductMapping($db);
$form = new Form($db);

$error = 0;

/*
 * Actions
 */

// Add mapping
if ($action == 'add') {
    if (empty($supplier_id) || $supplier_id <= 0) {
        setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors');
        $error++;
    }
    if (empty($supplier_ref)) {
        setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('SupplierRef')), null, 'errors');
        $error++;
    }
    if (empty($product_id) || $product_id <= 0) {
        setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Product')), null, 'errors');
        $error++;
    }

    if (!$error) {
        $mapping->fk_soc = $supplier_id;
        $mapping->supplier_ref = $supplier_ref;
        $mapping->fk_product = $product_id;
        $mapping->ean = $ean;
        $mapping->manufacturer_ref = $manufacturer_ref;
        $mapping->description = $description;
        $mapping->priority = $priority;

        $result = $mapping->create($user);
        if ($result > 0) {
            setEventMessages($langs->trans('MappingCreated'), null, 'mesgs');
            header('Location: '.$_SERVER['PHP_SELF'].'?supplier_id='.$supplier_id);
            exit;
        } else {
            setEventMessages($mapping->error, null, 'errors');
        }
    }
    $action = '';
}

// Delete mapping
if ($action == 'confirm_delete' && $confirm == 'yes') {
    $mapping->fetch($id);
    $save_supplier_id = $mapping->fk_soc;

    $result = $mapping->delete($user);
    if ($result > 0) {
        setEventMessages($langs->trans('MappingDeleted'), null, 'mesgs');
        header('Location: '.$_SERVER['PHP_SELF'].'?supplier_id='.$save_supplier_id);
        exit;
    } else {
        setEventMessages($mapping->error, null, 'errors');
    }
}

/*
 * View
 */

$title = $langs->trans('ProductMapping');
llxHeader('', $title, '', '', 0, 0, '', '', '', 'mod-importzugferd page-mapping');

print load_fiche_titre($title, '', 'fa-exchange-alt');

// Confirm delete
if ($action == 'delete') {
    print $form->formconfirm(
        $_SERVER['PHP_SELF'].'?id='.$id.'&supplier_id='.$supplier_id,
        $langs->trans('DeleteMapping'),
        $langs->trans('ConfirmDeleteMapping'),
        'confirm_delete',
        '',
        0,
        1
    );
}

// Supplier selection
print '<form method="GET" action="'.$_SERVER['PHP_SELF'].'">';
print '<div class="div-table-responsive-no-min">';
print '<table class="noborder centpercent">';
print '<tr class="liste_titre">';
print '<td colspan="2">'.$langs->trans('SelectSupplier').'</td>';
print '</tr>';
print '<tr class="oddeven">';
print '<td class="titlefield">'.$langs->trans('Supplier').'</td>';
print '<td>';
print $form->select_company($supplier_id, 'supplier_id', 's.fournisseur = 1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300');
print ' <input type="submit" class="button smallpaddingimp" value="'.$langs->trans('Select').'">';
print '</td>';
print '</tr>';
print '</table>';
print '</div>';
print '</form>';

// If supplier selected, show mappings and add form
if ($supplier_id > 0) {
    $supplier = new Societe($db);
    $supplier->fetch($supplier_id);

    print '<br>';

    // Add new mapping form
    print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
    print '<input type="hidden" name="token" value="'.newToken().'">';
    print '<input type="hidden" name="action" value="add">';
    print '<input type="hidden" name="supplier_id" value="'.$supplier_id.'">';

    print '<div class="div-table-responsive-no-min">';
    print '<table class="noborder centpercent">';
    print '<tr class="liste_titre">';
    print '<td colspan="6">'.$langs->trans('AddMapping').' - '.$supplier->getNomUrl(1).'</td>';
    print '</tr>';

    print '<tr class="oddeven">';
    print '<td class="titlefield fieldrequired">'.$langs->trans('SupplierRef').'</td>';
    print '<td><input type="text" name="supplier_ref" value="'.dol_escape_htmltag($supplier_ref).'" class="minwidth200" required></td>';
    print '<td class="fieldrequired">'.$langs->trans('Product').'</td>';
    print '<td>'.$form->select_produits($product_id, 'product_id', '', 0, 0, -1, 2, '', 0, array(), 0, '1', 0, 'minwidth300', 0, '', null, 1).'</td>';
    print '<td>'.$langs->trans('EAN').'</td>';
    print '<td><input type="text" name="ean" value="'.dol_escape_htmltag($ean).'" class="minwidth150"></td>';
    print '</tr>';

    print '<tr class="oddeven">';
    print '<td>'.$langs->trans('ManufacturerRef').'</td>';
    print '<td><input type="text" name="manufacturer_ref" value="'.dol_escape_htmltag($manufacturer_ref).'" class="minwidth200"></td>';
    print '<td>'.$langs->trans('Description').'</td>';
    print '<td><input type="text" name="description" value="'.dol_escape_htmltag($description).'" class="minwidth200"></td>';
    print '<td>'.$langs->trans('Priority').'</td>';
    print '<td><input type="number" name="priority" value="'.($priority ?: 0).'" class="width75"></td>';
    print '</tr>';

    print '<tr class="oddeven">';
    print '<td colspan="6" class="center">';
    print '<input type="submit" class="button button-primary" value="'.$langs->trans('Add').'">';
    print '</td>';
    print '</tr>';

    print '</table>';
    print '</div>';
    print '</form>';

    // Existing mappings
    print '<br>';
    print '<div class="div-table-responsive">';
    print '<table class="noborder centpercent">';
    print '<tr class="liste_titre">';
    print '<td>'.$langs->trans('SupplierRef').'</td>';
    print '<td>'.$langs->trans('Product').'</td>';
    print '<td>'.$langs->trans('EAN').'</td>';
    print '<td>'.$langs->trans('ManufacturerRef').'</td>';
    print '<td>'.$langs->trans('Description').'</td>';
    print '<td class="center">'.$langs->trans('Priority').'</td>';
    print '<td class="center">'.$langs->trans('Active').'</td>';
    print '<td class="center">'.$langs->trans('Action').'</td>';
    print '</tr>';

    $mappings = $mapping->fetchAllBySupplier($supplier_id);

    if (count($mappings) > 0) {
        foreach ($mappings as $m) {
            print '<tr class="oddeven">';
            print '<td>'.dol_escape_htmltag($m['supplier_ref']).'</td>';
            print '<td>';
            $product = new Product($db);
            $product->fetch($m['fk_product']);
            print $product->getNomUrl(1);
            print '</td>';
            print '<td>'.dol_escape_htmltag($m['ean']).'</td>';
            print '<td>'.dol_escape_htmltag($m['manufacturer_ref']).'</td>';
            print '<td>'.dol_escape_htmltag($m['description']).'</td>';
            print '<td class="center">'.$m['priority'].'</td>';
            print '<td class="center">';
            print $m['active'] ? img_picto($langs->trans('Active'), 'statut4') : img_picto($langs->trans('Inactive'), 'statut5');
            print '</td>';
            print '<td class="center">';
            print '<a href="'.$_SERVER['PHP_SELF'].'?action=delete&id='.$m['id'].'&supplier_id='.$supplier_id.'&token='.newToken().'">';
            print img_picto($langs->trans('Delete'), 'delete');
            print '</a>';
            print '</td>';
            print '</tr>';
        }
    } else {
        print '<tr class="oddeven"><td colspan="8" class="opacitymedium">'.$langs->trans('NoMappingsFound').'</td></tr>';
    }

    print '</table>';
    print '</div>';
}

llxFooter();
$db->close();
