<?php

namespace App\Controllers;

use App\Models\TaxModel;

class Tax extends BaseController
{
    protected $taxModel;

    public function __construct()
    {
        $this->taxModel = new TaxModel();
    }

    public function index()
    {
        $data = [
            'title' => 'Konfigurasi Pajak',
            'taxes' => $this->taxModel->findAll()
        ];
        return view('setting/tax/index', $data);
    }

    public function create()
    {
        return view('setting/tax/create', ['title' => 'Tambah Pajak']);
    }

    public function save()
    {
        $this->taxModel->save([
            'nama' => $this->request->getPost('nama'),
            'persen' => $this->request->getPost('persen'),
            'aktif' => 1
        ]);
        return redirect()->to(base_url('admin/setting/tax'))->with('success', 'Pajak ditambahkan');
    }

    public function edit($id)
    {
        $data = [
            'title' => 'Edit Pajak',
            'tax' => $this->taxModel->find($id)
        ];
        return view('setting/tax/edit', $data);
    }

    public function update($id)
    {
        $this->taxModel->update($id, [
            'nama' => $this->request->getPost('nama'),
            'persen' => $this->request->getPost('persen')
        ]);
        return redirect()->to(base_url('admin/setting/tax'))->with('success', 'Pajak diperbarui');
    }

    public function toggle($id)
    {
        $tax = $this->taxModel->find($id);
        $this->taxModel->update($id, ['aktif' => $tax['aktif'] ? 0 : 1]);
        return redirect()->to(base_url('admin/setting/tax'))->with('success', 'Status pajak diubah');
    }
}
