<?php
// POST /api/employees/create.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user = requireRole([1, 5]);
$db   = getDB();

$firstName = trim(post('first_name', ''));
$lastName  = trim(post('last_name', ''));
$startDate = trim(post('start_date', ''));

if (!$firstName) apiError('First name required.', 422);
if (!$lastName)  apiError('Last name required.', 422);
if (!$startDate) apiError('Start date required.', 422);

// Generate employee number
$year     = date('Y');
$countStmt = $db->query("SELECT COUNT(*) FROM employees WHERE YEAR(created_at) = $year");
$count    = (int)$countStmt->fetchColumn() + 1;
$empNo    = sprintf('EW-%s-%04d', $year, $count);

$db->prepare("
    INSERT INTO employees (
        employee_number, first_name, last_name, id_number, passport_number,
        date_of_birth, gender, race, nationality, marital_status,
        personal_email, work_email, phone,
        emergency_contact_name, emergency_contact_phone,
        address_line1, address_line2, city, province, postal_code,
        job_title, department, employment_type,
        start_date, end_date, probation_end_date, status,
        bank_name, bank_branch_code, bank_account_no, account_type,
        tax_number, uif_number, created_by
    ) VALUES (
        ?, ?, ?, ?, ?,
        ?, ?, ?, ?, ?,
        ?, ?, ?,
        ?, ?,
        ?, ?, ?, ?, ?,
        ?, ?, ?,
        ?, ?, ?, ?,
        ?, ?, ?, ?,
        ?, ?, ?
    )
")->execute([
    $empNo, $firstName, $lastName, post('id_number'), post('passport_number'),
    post('date_of_birth') ?: null, post('gender'), post('race'), post('nationality', 'South African'), post('marital_status'),
    post('personal_email'), post('work_email'), post('phone'),
    post('emergency_contact_name'), post('emergency_contact_phone'),
    post('address_line1'), post('address_line2'), post('city'), post('province'), post('postal_code'),
    post('job_title'), post('department'), post('employment_type', 'permanent'),
    $startDate, post('end_date') ?: null, post('probation_end_date') ?: null, post('status', 'active'),
    post('bank_name'), post('bank_branch_code'), post('bank_account_no'), post('account_type'),
    post('tax_number'), post('uif_number'), $user['id']
]);

$empId = (int)$db->lastInsertId();

// Add initial salary if provided
$basicSalary = (float)post('basic_salary', 0);
if ($basicSalary > 0) {
    $db->prepare("
        INSERT INTO employee_salaries (employee_id, effective_date, salary_type, basic_salary, created_by)
        VALUES (?, ?, ?, ?, ?)
    ")->execute([$empId, $startDate, post('salary_type', 'monthly'), $basicSalary, $user['id']]);
}

apiSuccess(['id' => $empId, 'employee_number' => $empNo], 'Employee created successfully.', 201);
