<?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) {
            die(json_encode(['success' => false, 'message' => 'Vous devez être connecté.']));
        }

        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']));
        }
    }
}
