<?php

require_once __DIR__ . '/../core/Controller.php';
require_once __DIR__ . '/../models/PedidoModel.php';

class PedidosController extends Controller
{
    public function index(): void
    {
        $currentUser = $_SESSION['user'] ?? null;
        if (!$currentUser) {
            $this->redirect('index.php?page=login');
        }

        $this->render('pedidos', [
            'title' => 'PetCare | Pedidos'
        ]);
    }

    public function store(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->redirect('index.php?page=pedidos');
        }

        $currentUser = $_SESSION['user'] ?? null;
        if (!$currentUser) {
            $this->redirect('index.php?page=login');
        }

        $rawProducts = $_POST['productos'] ?? '[]';
        $products = json_decode($rawProducts, true);
        if (!is_array($products) || $products === []) {
            $this->redirect('index.php?page=productos');
        }

        $productNames = [];
        $quantityTotal = 0;
        foreach ($products as $item) {
            $productNames[] = ucfirst((string) ($item['key'] ?? 'producto'));
            $quantityTotal += max(1, (int) ($item['quantity'] ?? 1));
        }

        $payload = [
            'usuario_id' => (int) ($currentUser['id'] ?? 0),
            'producto' => implode(', ', $productNames),
            'cantidad' => $quantityTotal,
            'total' => (float) ($_POST['total'] ?? 0),
            'estado' => 'pendiente'
        ];

        PedidoModel::create($payload);
        $this->redirect('index.php?page=pedidos&purchase=success');
    }
}
