<?php
namespace App\Models;

use CodeIgniter\Model;

class OrdersDataModel extends Model
{
    protected $table = 'orders';
    protected $allowedFields = ['total_amount'];

    public function createOrder($cart)
    {
        $db = \Config\Database::connect();
        $db->transStart();

        // Insert order
        $this->insert(['total_amount' => array_reduce($cart, fn($sum,$i)=>$sum+$i['price']*$i['quantity'],0)]);
        $orderId = $this->getInsertID();

        // Insert items
        $orderItems = $db->table('order_items');
        foreach($cart as $item){
            $orderItems->insert([
                'order_id' => $orderId,
                'product_id' => $item['id'],
                'product_name' => $item['name'],
                'price' => $item['price'],
                'quantity' => $item['quantity']
            ]);
        }

        $db->transComplete();
        return $db->transStatus() ? $orderId : false;
    }
}
