<?php
declare(strict_types=1);

namespace App\Models;

use PDO;

class CookieConsent extends BaseModel
{
    protected string $table = 'cookie_consents';

    public function record(array $data): void
    {
        $statement = $this->db()->prepare(
            "INSERT INTO {$this->table}
            (user_id, visitor_id, consent_token, necessary, analytics, personalization, marketing, preferences, consent_status, ip_address, user_agent)
            VALUES
            (:user_id, :visitor_id, :consent_token, :necessary, :analytics, :personalization, :marketing, :preferences, :consent_status, :ip_address, :user_agent)
            ON DUPLICATE KEY UPDATE
                user_id = VALUES(user_id),
                visitor_id = VALUES(visitor_id),
                necessary = VALUES(necessary),
                analytics = VALUES(analytics),
                personalization = VALUES(personalization),
                marketing = VALUES(marketing),
                preferences = VALUES(preferences),
                consent_status = VALUES(consent_status),
                ip_address = VALUES(ip_address),
                user_agent = VALUES(user_agent),
                updated_at = NOW()"
        );

        $statement->bindValue('user_id', $data['user_id'], $data['user_id'] === null ? PDO::PARAM_NULL : PDO::PARAM_INT);
        $statement->bindValue('visitor_id', $data['visitor_id']);
        $statement->bindValue('consent_token', $data['consent_token']);
        $statement->bindValue('necessary', !empty($data['necessary']) ? 1 : 0, PDO::PARAM_INT);
        $statement->bindValue('analytics', !empty($data['analytics']) ? 1 : 0, PDO::PARAM_INT);
        $statement->bindValue('personalization', !empty($data['personalization']) ? 1 : 0, PDO::PARAM_INT);
        $statement->bindValue('marketing', !empty($data['marketing']) ? 1 : 0, PDO::PARAM_INT);
        $statement->bindValue('preferences', !empty($data['preferences']) ? 1 : 0, PDO::PARAM_INT);
        $statement->bindValue('consent_status', $data['consent_status']);
        $statement->bindValue('ip_address', $data['ip_address']);
        $statement->bindValue('user_agent', $data['user_agent']);
        $statement->execute();
    }
}
