<?php
namespace App\Models;

use CodeIgniter\Model;

class AdminOrderModel extends Model
{
    protected $table = 'orders';
    protected $primaryKey = 'id';
    protected $allowedFields = [
        'apartment_id', 'customer_name', 'email', 'phone', 'address', 
        'payment_method', 'total_amount', 'delivery_charge', 
        'status', 'created_at'
    ];

    // Fetch all pending orders with apartment details
    public function getOrdersWithApartment($status = 'Pending')
    {
        $builder = $this->db->table('orders o');
        $builder->select('o.*, a.apartName, a.apartAddress');
        $builder->join('apartmentdetails a', 'a.id = o.apartment_id', 'left');
        $builder->where('o.status', $status);
        $builder->orderBy('o.created_at', 'DESC');
        $orders = $builder->get()->getResultArray();

        // Fetch order items for each order
        foreach ($orders as &$order) {
            $order['items'] = $this->db->table('order_items')
                                        ->where('order_id', $order['id'])
                                        ->get()
                                        ->getResultArray();
        }

        return $orders;
    }

    // Update order status
    public function updateOrderStatus($orderId, $status)
    {
        return $this->update($orderId, ['status' => $status]);
    }
}
