<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\MenuModel;
use App\Models\CommissionOverrideModel;

/**
 * CommissionSettings
 *
 * Admin-only page for commission overrides and menu.
 */
class CommissionSettings extends Controller
{
    public function index()
    {
        // Must be logged in
        if (! service('auth')->loggedIn()) {
            return redirect()->to('/login');
        }

        // Must be admin
        $user = service('auth')->user();
        if ((int) $user->is_admin !== 1) {
            return redirect()->to('/')->with('error', 'Access denied: Admins only.');
        }

        // Get only admin menu items
        $menuModel = new MenuModel();
        $menuItems = $menuModel->where('is_admin', 1)->orderBy('order', 'ASC')->findAll();

        // Get commission override data
        $commissionModel = new CommissionOverrideModel();
        $commissionData = $commissionModel
            ->select('commission_override.*, bbt_users.first_name, bbt_users.last_name')
            ->join('bbt_users', 'commission_override.user_id = bbt_users.id', 'left')
            ->findAll();

        // Show the view
        return view('commissionsettings/index', [
            'menuItems'      => $menuItems,
            'commissionData' => $commissionData
        ]);
    }

    public function updateAll()
    {
        // Must be logged in
        if (! service('auth')->loggedIn()) {
            return redirect()->to('/login');
        }

        // Must be admin
        $user = service('auth')->user();
        if ((int) $user->is_admin !== 1) {
            return redirect()->to('/')->with('error', 'Access denied: Admins only.');
        }

        // CommissionOverrideModel
        $commissionModel = new CommissionOverrideModel();

        // Gather posted arrays
        $deposit            = $this->request->getPost('deposit');
        $customer_care      = $this->request->getPost('customer_care');
        $title_work         = $this->request->getPost('title_work');
        $checkout_completed = $this->request->getPost('checkout_completed');
        $upsells            = $this->request->getPost('upsells');

        if (! is_array($deposit)) {
            return redirect()->back()->with('error', 'No data to update.');
        }

        // Loop each row
        foreach ($deposit as $id => $val) {
            $data = [
                'deposit'            => $deposit[$id]            ?? 0,
                'customer_care'      => $customer_care[$id]      ?? 0,
                'title_work'         => $title_work[$id]         ?? 0,
                'checkout_completed' => $checkout_completed[$id] ?? 0,
                'upsells'            => $upsells[$id]            ?? 0,
            ];
            $commissionModel->update($id, $data);
        }

        return redirect()->back()->with('success', 'All rows updated successfully!');
    }
}
