//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Pastèque.  If not, see <http://www.gnu.org/licenses/>.
namespace ProductCompositions;

$message = NULL;
$error = NULL;
if (isset($_POST['delete-comp'])) {
    if (\Pasteque\CompositionsService::delete($_POST['delete-comp'])) {
        $message = \i18n("Changes saved");
    } else {
        $error = \i18n("Unable to save changes");
    }
}
$compositions = \Pasteque\CompositionsService::getAll();
//Title
echo \Pasteque\row(\Pasteque\mainTitle(\i18n("Compositions", PLUGIN_NAME)));
//Buttons
$buttons = \Pasteque\addButton(\i18n("Add composition", PLUGIN_NAME), \Pasteque\get_module_url_action(PLUGIN_NAME, "composition_edit"));
echo \Pasteque\row(\Pasteque\buttonGroup($buttons));
//Information
\Pasteque\tpl_msg_box($message, $error);
//Counter
echo \Pasteque\row(\Pasteque\counterDiv(\i18n("%d compositions", PLUGIN_NAME, count($compositions))));
if (count($compositions) == 0) {
    echo \Pasteque\errorDiv(\i18n("No category found", PLUGIN_NAME));
} else {
    $content[0][0] = \i18n("Composition.label");
    $i = 1;
    foreach ($compositions as $composition) {
        $discountRate = 0.0;
        if (isset($_POST['discountRate'])) {
            $discountEnabled = isset($_POST['discountEnabled']) ? 1 : 0;
            $discountRate = $_POST['discountRate'];
        }
        $cmp = new \Pasteque\Product($_POST['reference'], $_POST['label'], $_POST['realsell'], $catId, null, $dispOrder, $taxCatId, $visible, $scaled, $_POST['priceBuy'], null, $_POST['barcode'], $img !== null, $discountEnabled, $discountRate);
        $cmp->groups = parseSubgroups($_POST['subgroupData'], $products);
        if (\Pasteque\CompositionsService::create($cmp, $img, null)) {
            $message = \i18n("Changes saved", PLUGIN_NAME);
        } else {
            $error = \i18n("Unable to save changes", PLUGIN_NAME);
        }
    }
}
if (isset($_GET['productId'])) {
    $composition = \Pasteque\CompositionsService::get($_GET['productId']);
    $taxCat = \Pasteque\TaxesService::get($composition->taxCatId);
    $tax = $taxCat->getCurrentTax();
    $vatprice = $composition->priceSell * (1 + $tax->rate);
    $price = sprintf("%.2f", $composition->priceSell);
} else {
    $vatprice = "";
    $price = "";
    $composition = NULL;
}
?>

<h1><?php 
\pi18n('Composition edit', PLUGIN_NAME);
?>
</h1>