<?php

namespace App\Controllers\HR;

use CodeIgniter\Controller;
use Config\Database;

class Employees extends Controller
{
    public function index()
    {
        $db = Database::connect();
        $builder = $db->table('employees');
        $builder->select('employees.*, salary_grades.name as grade_name');
        $builder->join('salary_grades', 'salary_grades.id = employees.salary_grade_id', 'left');
        $builder->orderBy('employees.id', 'DESC');
        $employees = $builder->get()->getResult();

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

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

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

    public function store()
    {
        $db = Database::connect();
        $data = [
            'employee_no'    => trim($this->request->getPost('employee_no')),
            'first_name'     => trim($this->request->getPost('first_name')),
            'last_name'      => trim($this->request->getPost('last_name')),
            'gender'         => trim($this->request->getPost('gender')) ?: null,
            'dob'            => $this->request->getPost('dob') ?: null,
            'email'          => trim($this->request->getPost('email')) ?: null,
            'phone'          => trim($this->request->getPost('phone')) ?: null,
            'address'        => trim($this->request->getPost('address')) ?: null,
            'status'         => trim($this->request->getPost('status')) ?: 'Active',
            'hire_date'      => $this->request->getPost('hire_date') ?: null,
            'department'     => trim($this->request->getPost('department')) ?: null,
            'position'       => trim($this->request->getPost('position')) ?: null,
            'salary_grade_id'=> $this->request->getPost('salary_grade_id') ?: null,
            'created_at'     => date('Y-m-d H:i:s'),
        ];

        // Basic validation
        if (!$data['employee_no'] || !$data['first_name'] || !$data['last_name']) {
            return redirect()->back()->with('error', 'Employee No, First Name and Last Name are required.');
        }

        // Ensure unique employee number
        $existing = $db->table('employees')->where('employee_no', $data['employee_no'])->get()->getRow();
        if ($existing) {
            return redirect()->back()->withInput()->with('error', 'Employee number already exists.');
        }

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

        return redirect()->to('/hr/employees')->with('message', 'Employee created successfully.');
    }
}
