<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\CommissionModel;
use App\Models\MarketerModel;

class MarketerController extends BaseController
{
    public function index()
    {
        $model = new MarketerModel();
        $marketers = $model->forCompany($this->currentCompanyId())->findAll();

        $commissionModel = new CommissionModel();
        foreach ($marketers as &$m) {
            $m['total_commissions'] = $commissionModel->where('marketer_id', $m['id'])->selectSum('amount')->first()['amount'] ?? 0;
        }

        return view('admin/marketers/index', ['marketers' => $marketers]);
    }

    public function create()
    {
        return view('admin/marketers/form', ['marketer' => null]);
    }

    public function store()
    {
        $data = $this->marketerData();
        $data['company_id'] = $this->currentCompanyId();
        (new MarketerModel())->insert($data);
        return redirect()->to('/admin/marketers')->with('message', lang('App.saved_successfully'));
    }

    public function edit($id)
    {
        $marketer = (new MarketerModel())->forCompany($this->currentCompanyId())->find($id);
        return view('admin/marketers/form', ['marketer' => $marketer]);
    }

    public function update($id)
    {
        (new MarketerModel())->update($id, $this->marketerData());
        return redirect()->to('/admin/marketers')->with('message', lang('App.saved_successfully'));
    }

    public function delete($id)
    {
        (new MarketerModel())->delete($id);
        return redirect()->to('/admin/marketers')->with('message', lang('App.deleted_successfully'));
    }

    private function marketerData(): array
    {
        return [
            'name' => $this->request->getPost('name'),
            'email' => $this->request->getPost('email'),
            'phone' => $this->request->getPost('phone'),
            'commission_type' => $this->request->getPost('commission_type'),
            'commission_value' => $this->request->getPost('commission_value'),
            'is_active' => $this->request->getPost('is_active') ? 1 : 0,
        ];
    }
}
