<?php

class PolarisPrestaThemeAjaxWishlistModuleFrontController extends ModuleFrontController
{
    public $ajax = true;

    public function initContent()
    {
        parent::initContent();

        $idCustomer = (int)$this->context->customer->id;
        $idProduct = (int)Tools::getValue('id_product');

        if (!$idCustomer) {
            // Page d'origine pour revenir après connexion (validée same-origin → pas d'open redirect)
            $back = trim((string)Tools::getValue('back'));
            $shopUrl = $this->context->shop->getBaseURL(true);
            if ($back === '' || strpos($back, $shopUrl) !== 0) {
                $back = $this->context->link->getPageLink('my-account', true);
            }

            die(json_encode([
                'success' => false,
                'requireLogin' => true,
                'message' => 'Vous devez être connecté.',
                'loginUrl' => $this->context->link->getPageLink('authentication', true, null, ['back' => $back]),
                'registerUrl' => $this->context->link->getPageLink('registration', true, null, ['back' => $back]),
            ]));
        }

        if (!$idProduct) {
            die(json_encode(['success' => false, 'message' => 'Produit invalide.']));
        }

        // Vérifie si le produit est déjà dans la wishlist
        $exists = (bool)Db::getInstance()->getValue('
            SELECT COUNT(*) FROM `'._DB_PREFIX_.'wishlist`
            WHERE id_customer = '.(int)$idCustomer.' AND id_product = '.(int)$idProduct
        );

        if ($exists) {
            // Supprimer uniquement si on reclique (toggle)
            Db::getInstance()->delete(
                'wishlist',
                'id_customer='.(int)$idCustomer.' AND id_product='.(int)$idProduct
            );
            die(json_encode(['success' => true, 'action' => 'removed']));
        } else {
            // Ajout sans suppression d'autres produits
            Db::getInstance()->insert('wishlist', [
                'id_customer' => (int)$idCustomer,
                'id_product' => (int)$idProduct,
                'date_add' => date('Y-m-d H:i:s'),
            ]);
            die(json_encode(['success' => true, 'action' => 'added']));
        }
    }
}
