<?php
namespace App\Controllers;

use App\Core\Auth;
use App\Core\Response;
use App\Models\CookieConsent;
use Throwable;

class CookieController extends BaseController
{
    public function save(): Response
    {
        $input = $this->input();
        $consent = [
            'necessary' => true,
            'analytics' => $this->bool($input['analytics'] ?? false),
            'personalization' => $this->bool($input['personalization'] ?? false),
            'marketing' => $this->bool($input['marketing'] ?? false),
        ];

        $token = $this->consentToken();
        $stored = false;

        $this->setConsentCookie($consent);

        try {
            (new CookieConsent())->record([
                'user_id' => Auth::id(),
                'visitor_id' => $token,
                'consent_token' => $token,
                'necessary' => $consent['necessary'],
                'analytics' => $consent['analytics'],
                'personalization' => $consent['personalization'],
                'marketing' => $consent['marketing'],
                'preferences' => $consent['personalization'],
                'consent_status' => ($consent['analytics'] || $consent['personalization'] || $consent['marketing']) ? 'accepted' : 'necessary',
                'ip_address' => $_SERVER['REMOTE_ADDR'] ?? null,
                'user_agent' => substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255),
            ]);
            $stored = true;
        } catch (Throwable) {
            $stored = false;
        }

        return Response::json([
            'ok' => true,
            'stored' => $stored,
            'token' => $token,
            'consent' => $consent,
        ]);
    }

    private function input(): array
    {
        $raw = file_get_contents('php://input') ?: '';
        $json = json_decode($raw, true);

        return is_array($json) ? $json : $_POST;
    }

    private function bool(mixed $value): bool
    {
        return filter_var($value, FILTER_VALIDATE_BOOLEAN);
    }

    private function consentToken(): string
    {
        if (!empty($_COOKIE['zalorox_cookie_token'])) {
            return (string) $_COOKIE['zalorox_cookie_token'];
        }

        $token = bin2hex(random_bytes(24));
        $secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');

        setcookie('zalorox_cookie_token', $token, [
            'expires' => time() + 31536000,
            'path' => '/',
            'secure' => $secure,
            'httponly' => true,
            'samesite' => 'Lax',
        ]);

        return $token;
    }

    private function setConsentCookie(array $consent): void
    {
        $secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');

        setcookie('zalorox_cookie_consent', json_encode($consent, JSON_UNESCAPED_UNICODE), [
            'expires' => time() + 31536000,
            'path' => '/',
            'secure' => $secure,
            'httponly' => false,
            'samesite' => 'Lax',
        ]);
    }
}
