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

$user = requireRole([1, 5]);
$db   = getDB();
$id   = (int)post('id', 0);

if (!$id) apiError('Employee ID required.', 422);

$stmt = $db->prepare("SELECT id FROM employees WHERE id = ?");
$stmt->execute([$id]);
if (!$stmt->fetch()) apiError('Employee not found.', 404);

$firstName = trim(post('first_name', ''));
$lastName  = trim(post('last_name', ''));
if (!$firstName || !$lastName) apiError('First and last name required.', 422);

$db->prepare("
    UPDATE employees SET
        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 = ?,
        user_id = ?, days_per_month = ?, hours_per_day = ?
    WHERE id = ?
")->execute([
    $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'),
    post('start_date'), 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'),
    post('user_id') ?: null,
    post('days_per_month', 21.67),
    post('hours_per_day', 8),
    $id
]);

apiSuccess([], 'Employee updated successfully.');
