<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;

class CartController extends Controller
{
    public function index()
    {
        $cart = $_SESSION['cart'] ?? [];
        $total = 0;
        foreach ($cart as $item) {
            $total += $item['total_price'];
        }
        $this->view('client.cart', ['cart' => $cart, 'total' => $total]);
    }

    public function add()
    {
        $productId = $_POST['product_id'];
        $name = $_POST['name'];
        $price = (float) $_POST['price'];
        $quantity = (int) $_POST['quantity'];
        $options = $_POST['options'] ?? [];
        $notes = $_POST['notes'] ?? '';

        $optionsTotal = 0;
        $extras = [];
        $optionIds = [];

        foreach ($options as $opt) {
            if (strpos($opt, 'extra:') === 0) {
                $parts = explode(':', $opt);
                $extraPrice = isset($parts[2]) ? (float) str_replace(',', '.', $parts[2]) : 0;
                $optionsTotal += $extraPrice;
                $extras[] = $opt;
            } elseif (ctype_digit((string) $opt)) {
                $optionIds[] = (int) $opt;
            }
        }

        if (!empty($optionIds)) {
            $db = Database::getInstance()->getConnection();
            $placeholders = implode(',', array_fill(0, count($optionIds), '?'));
            $stmt = $db->prepare("SELECT id, additional_price FROM product_options WHERE id IN ($placeholders)");
            $stmt->execute($optionIds);
            $rows = $stmt->fetchAll();
            $priceById = [];
            foreach ($rows as $row) {
                $priceById[$row['id']] = (float) $row['additional_price'];
            }
            foreach ($optionIds as $id) {
                $optionsTotal += $priceById[$id] ?? 0;
            }
        }

        $unitPrice = $price + $optionsTotal;
        $totalPrice = $unitPrice * $quantity;

        $item = [
            'id' => uniqid(),
            'product_id' => $productId,
            'name' => $name,
            'price' => $unitPrice,
            'quantity' => $quantity,
            'total_price' => $totalPrice,
            'options' => $options,
            'notes' => $notes
        ];

        $_SESSION['cart'][] = $item;

        $redirect = $_POST['redirect'] ?? ($_SERVER['HTTP_REFERER'] ?? '/carrinho');
        $this->redirect($redirect);
    }

    public function remove($index)
    {
        if (isset($_SESSION['cart'][$index])) {
            unset($_SESSION['cart'][$index]);
            $_SESSION['cart'] = array_values($_SESSION['cart']); // Reindex
        }
        $this->redirect('/carrinho');
    }
}
