<?php

namespace App\Controllers\Api;

use CodeIgniter\RESTful\ResourceController;
use App\Models\ProductModel;

class CartApi extends ResourceController
{
    public function add()
    {
        $input = $this->request->getJSON();
        
        if (!isset($input->id_product) || !isset($input->qty)) {
            return $this->fail('Invalid request data', 400);
        }

        $productModel = new ProductModel();
        $product = $productModel->find($input->id_product);
        
        if (!$product) return $this->failNotFound('Produk tidak ditemukan');

        $cart = session()->get('cart') ?? [];
        $cart[$input->id_product] = [
            'id_product' => $product['id_product'],
            'nama'       => $product['nama_product'],
            'qty'        => $input->qty,
            'harga'      => $product['harga_jual']
        ];
        
        session()->set('cart', $cart);

        return $this->respond(['status' => 200, 'message' => 'Berhasil ditambahkan ke keranjang']);
    }
}