<?php

namespace App\Models;

use CodeIgniter\Model;

class CommissionOverrideModel extends Model
{
    protected $table      = 'commission_override';
    protected $primaryKey = 'id';
    
    // IMPORTANT: 'upsells' must be here so updates to that column are allowed.
    protected $allowedFields = [
        'user_id',
        'deposit',
        'customer_care',
        'title_work',
        'checkout_completed',
        'upsells', // <-- added
    ];

    /**
     * Retrieve a single commission override row by user_id.
     * Returns null if not found.
     */
    public function getOverrideByUser(int $userId)
    {
        return $this->where('user_id', $userId)->first();
    }

    /**
     * Retrieve overrides for multiple users at once, keyed by user_id.
     */
    public function getOverridesForUsers(array $userIds): array
    {
        if (empty($userIds)) {
            return [];
        }

        $rows = $this->whereIn('user_id', $userIds)->findAll();

        // Build an associative array: [ user_id => row ]
        $results = [];
        foreach ($rows as $row) {
            $results[$row['user_id']] = $row;
        }

        return $results;
    }

    /**
     * Upsert an override (insert if it doesn't exist, update if it does).
     */
    public function upsertOverride(int $userId, array $fields): bool
    {
        // Ensure user_id is always set
        $fields['user_id'] = $userId;

        // Check if row already exists
        $existing = $this->where('user_id', $userId)->first();

        if ($existing) {
            // Update existing row
            return (bool) $this->update($existing['id'], $fields);
        } else {
            // Insert new row
            return (bool) $this->insert($fields);
        }
    }
}
