<?php
declare(strict_types=1);

namespace App\Controller;

use Cake\Event\EventInterface;

class CartController extends AppController
{
    public function beforeFilter(EventInterface $event): void
    {
        parent::beforeFilter($event);

        // Allow guests to use the cart
        if ($this->components()->has('Authentication')) {
            $this->Authentication->allowUnauthenticated([
                'index', 'update', 'remove', 'clear','addtocart'
            ]);
        }
    }

    private function skipAuthzIfPresent(): void
    {
        if ($this->components()->has('Authorization')) {
            $this->Authorization->skipAuthorization();
        }
    }

    /** Cart page */
    public function index()
    {
        $this->skipAuthzIfPresent();

        $session = $this->request->getSession();
        $raw = (array)$session->read('Cart'); // [product_id => qty]

        // Empty cart
        if (!$raw) {
            $this->set([
                'items'    => [],
                'total'    => 0.0,  // <- what your template expects
                'totalQty' => 0,
            ]);
            return;
        }

        $Products = $this->fetchTable('Products');
        $rows = $Products->find()
            ->where(['Products.id IN' => array_keys($raw)])
            ->all()
            ->indexBy('id')
            ->toArray();

        $items = [];
        $total = 0.0;
        $totalQty = 0;

        foreach ($raw as $pid => $qty) {
            if (!isset($rows[$pid])) {
                continue;
            }
            $product = $rows[$pid];

            // choose sale price if valid
            $price = isset($product->sale_price) && $product->sale_price !== null
            && (float)$product->sale_price < (float)$product->price
                ? (float)$product->sale_price
                : (float)$product->price;

            $qty = max(0, (int)$qty);
            $lineSubtotal = $price * $qty;

            $items[] = [
                // shape tailored for your existing template:
                'product'  => $product,    // entity so you can do $item['product']->name, ->id, ->image, etc.
                'qty'      => $qty,
                'price'    => $price,
                'subtotal' => $lineSubtotal,
            ];

            $total     += $lineSubtotal;
            $totalQty  += $qty;
        }

        $this->set(compact('items', 'total', 'totalQty'));
    }

    /** Update quantity (POST: id, qty) */
    public function update()
    {
        $this->skipAuthzIfPresent();
        $this->request->allowMethod(['post']);

        $id  = (int)$this->request->getData('id');
        $qty = (int)$this->request->getData('qty');

        $session = $this->request->getSession();
        $cart = (array)$session->read('Cart');

        if ($qty <= 0) {
            unset($cart[$id]);
        } else {
            $cart[$id] = $qty;
        }

        $session->write('Cart', $cart);
        return $this->redirect(['action' => 'index']);
    }

    /** Remove one item */
    public function remove($id = null)
    {
        $this->skipAuthzIfPresent();
        $this->request->allowMethod(['post']);

        $id = (int)$id;
        $session = $this->request->getSession();
        $cart = (array)$session->read('Cart');
        unset($cart[$id]);
        $session->write('Cart', $cart);

        return $this->redirect(['action' => 'index']);
    }

    /** Clear all */
    public function clear()
    {
        $this->skipAuthzIfPresent();
        $this->request->allowMethod(['post']);

        $this->request->getSession()->delete('Cart');

        return $this->redirect(['action' => 'index']);
    }
}

