<?php
namespace App\Core;

class Cart
{
    private static string $key = '_cart';

    public static function get(): array
    {
        return $_SESSION[self::$key] ?? [];
    }

    public static function add(int $id, int $qty = 1): void
    {
        $cart = self::get();
        $cart[$id] = ($cart[$id] ?? 0) + $qty;
        $_SESSION[self::$key] = $cart;
    }

    public static function set(int $id, int $qty): void
    {
        $cart = self::get();
        if ($qty <= 0) unset($cart[$id]);
        else $cart[$id] = $qty;
        $_SESSION[self::$key] = $cart;
    }

    public static function remove(int $id): void
    {
        $cart = self::get();
        unset($cart[$id]);
        $_SESSION[self::$key] = $cart;
    }

    public static function clear(): void
    {
        $_SESSION[self::$key] = [];
    }

    public static function count(): int
    {
        return (int) \array_sum(self::get());
    }

    public static function totals(): array
    {
        $cart  = self::get();
        $items = (int) \array_sum($cart);
        $preco = (float) config('app.preco_foto');

        // Promoção: paga PROMO_C (10), recebe PROMO_O (1) EXTRA grátis
        // Foto grátis é adicional — 10 pagas → total 11; 20 pagas → total 22
        // floor(11/11)*1=1; floor(22/11)*1=2
        $pc    = (int) config('app.promo_compra');
        $po    = (int) config('app.promo_oferta');
        $ciclo = $pc + $po;
        $free  = ($ciclo > 0 && $items > 0) ? (int)\floor($items / $ciclo) * $po : 0;
        $pay   = $items - $free;

        return [
            'items'    => $items,
            'free'     => $free,
            'pay'      => $pay,
            'subtotal' => \round($pay * $preco, 2),
        ];
    }

    public static function shipping(string $method): float
    {
        return match($method) {
            'ctt'           => (float) config('app.preco_ctt'),
            'internacional' => (float) config('app.preco_internacional'),
            default         => 0.0,
        };
    }
}
