<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\ClientModel;
use App\Models\ServiceModel;

class ServiceController extends BaseController
{
    public function index()
    {
        $model = new ServiceModel();
        $services = $model->forCompany($this->currentCompanyId())
            ->select('services.*, clients.name as client_name')
            ->join('clients', 'clients.id = services.client_id')
            ->orderBy('renewal_date', 'ASC')
            ->paginate(15);

        return view('admin/services/index', ['services' => $services, 'pager' => $model->pager]);
    }

    public function create()
    {
        $clients = (new ClientModel())->forCompany($this->currentCompanyId())->findAll();
        return view('admin/services/form', ['service' => null, 'clients' => $clients, 'currencies' => $this->activeCurrencies()]);
    }

    public function store()
    {
        $model = new ServiceModel();
        $data = $this->serviceData();
        $data['company_id'] = $this->currentCompanyId();

        if (! $model->insert($data)) {
            return redirect()->back()->withInput()->with('errors', $model->errors());
        }

        return redirect()->to('/admin/services')->with('message', lang('App.saved_successfully'));
    }

    public function edit($id)
    {
        $model = new ServiceModel();
        $service = $model->forCompany($this->currentCompanyId())->find($id);
        if (! $service) return redirect()->to('/admin/services');

        $clients = (new ClientModel())->forCompany($this->currentCompanyId())->findAll();
        return view('admin/services/form', ['service' => $service, 'clients' => $clients, 'currencies' => $this->activeCurrencies()]);
    }

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

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

    private function serviceData(): array
    {
        return [
            'client_id' => $this->request->getPost('client_id'),
            'type' => $this->request->getPost('type'),
            'name' => $this->request->getPost('name'),
            'price' => $this->request->getPost('price'),
            'currency' => $this->request->getPost('currency'),
            'billing_cycle' => $this->request->getPost('billing_cycle'),
            'start_date' => $this->request->getPost('start_date'),
            'renewal_date' => $this->request->getPost('renewal_date'),
            'status' => $this->request->getPost('status'),
            'notes' => $this->request->getPost('notes'),
        ];
    }
}
