<?php

namespace App\Controllers\HR;

use CodeIgniter\Controller;
use Config\Database;

class SalaryGrades extends Controller
{
    public function index()
    {
        $db = Database::connect();
        $grades = $db->table('salary_grades')->orderBy('name', 'ASC')->get()->getResult();

        return view('hr/salary_grades/index', [
            'title' => lang('App.salary_grades'),
            'grades' => $grades,
        ]);
    }

    public function create()
    {
        return view('hr/salary_grades/create', [
            'title' => lang('App.salary_grades'),
        ]);
    }

    public function store()
    {
        $db = Database::connect();
        $data = [
            'code'        => trim($this->request->getPost('code')),
            'name'        => trim($this->request->getPost('name')),
            'base_salary' => (string) ($this->request->getPost('base_salary') ?: '0.00'),
            'currency'    => trim($this->request->getPost('currency')) ?: 'SAR',
            'created_at'  => date('Y-m-d H:i:s'),
        ];

        if (!$data['code'] || !$data['name']) {
            return redirect()->back()->with('error', 'Code and Name are required.');
        }

        // Ensure unique code
        $exists = $db->table('salary_grades')->where('code', $data['code'])->get()->getRow();
        if ($exists) {
            return redirect()->back()->withInput()->with('error', 'Salary grade code already exists.');
        }

        $db->table('salary_grades')->insert($data);

        return redirect()->to('/hr/salary-grades')->with('message', 'Salary grade created successfully.');
    }
}
