<?php
// api/leave_hr.php
// HR + Executive leave ledger, audited balance adjustments and DVC1 account controls.

declare(strict_types=1);

require_once __DIR__ . '/leave_common.php';

leave_ensure_tables($pdo);
$user = leave_current_user($pdo);
$profile = leave_official_profile($pdo, $user);
$access = leave_hr_access($pdo, $user);
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$action = strtolower(leave_clean($_GET['action'] ?? '', 40));
$userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
$input = in_array($method, ['POST','PUT','PATCH'], true) ? leave_input() : [];

if (!$access['enabled']) {
    leave_json(['detail' => 'Only authorised HR or executive officers may use the HR leave ledger.'], 403);
}

try {
    if ($method === 'GET' && ($action === '' || $action === 'ledger')) {
        $rows = leave_employee_rows($pdo, $user);
        $totalAvailable = 0.0;
        $lowBalance = 0;
        $pending = 0;
        $campuses = [];
        foreach ($rows as $row) {
            $available = (float)($row['balance']['available_days'] ?? 0);
            $totalAvailable += $available;
            if ($available < 4) $lowBalance++;
            $pending += (int)($row['pending_leave_count'] ?? 0);
            $campus = leave_clean($row['campus'] ?? '', 180);
            if ($campus !== '') $campuses[leave_campus_key($campus)] = $campus;
        }
        leave_json([
            'data' => $rows,
            'summary' => [
                'employees' => count($rows),
                'total_available_days' => $totalAvailable,
                'low_balance_employees' => $lowBalance,
                'pending_leave_requests' => $pending,
                'monthly_accrual_days' => 2.0,
                'year' => (int)date('Y'),
            ],
            'access' => $access,
            'campuses' => array_values($campuses),
            'current_user' => $profile,
        ]);
    }

    if ($method === 'GET' && $action === 'history' && $userId > 0) {
        $employee = leave_assert_hr_employee_scope($pdo, $user, $userId);
        $year = isset($_GET['year']) ? max(2000, (int)$_GET['year']) : (int)date('Y');
        $balance = leave_sync_annual_balance($pdo, $userId, $year);

        $adjust = $pdo->prepare('SELECT * FROM leave_balance_adjustments WHERE user_id = ? AND leave_year = ? ORDER BY created_at DESC, id DESC LIMIT 100');
        $adjust->execute([$userId, $year]);
        $adjustments = $adjust->fetchAll(PDO::FETCH_ASSOC);
        foreach ($adjustments as &$row) {
            $row['id'] = (int)$row['id'];
            $row['user_id'] = (int)$row['user_id'];
            $row['actor_user_id'] = (int)$row['actor_user_id'];
            foreach (['amount','before_balance','after_balance'] as $key) $row[$key] = (float)$row[$key];
        }

        $leaveStmt = $pdo->prepare("SELECT id, leave_type, start_date, end_date, requested_days, status, current_stage, submitted_at, final_decision_at
                                   FROM leave_applications
                                   WHERE applicant_user_id = ? AND EXTRACT(YEAR FROM start_date) = ?
                                   ORDER BY submitted_at DESC, id DESC LIMIT 100");
        $leaveStmt->execute([$userId, $year]);
        $leaves = $leaveStmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($leaves as &$leave) {
            $leave['id'] = (int)$leave['id'];
            $leave['requested_days'] = (float)$leave['requested_days'];
        }

        leave_json([
            'employee' => [
                'user_id' => (int)$employee['id'],
                'full_name' => $employee['full_name'] ?? '',
                'email' => $employee['email'] ?? '',
                'campus' => $employee['campus'] ?? '',
                'department' => $employee['program'] ?? '',
            ],
            'balance' => $balance,
            'adjustments' => $adjustments,
            'leave_history' => $leaves,
        ]);
    }

    if ($method === 'POST' && $action === 'accrue') {
        // Idempotent. Re-running in the same month does not add a second 2 days.
        $rows = leave_employee_rows($pdo, $user);
        leave_json([
            'message' => 'Monthly leave accrual synchronized successfully. Each eligible employee receives 2.00 annual leave days per month, once per month.',
            'employees_processed' => count($rows),
            'monthly_accrual_days' => 2.0,
        ]);
    }

    if ($method === 'POST' && $action === 'adjust' && $userId > 0) {
        $employee = leave_assert_hr_employee_scope($pdo, $user, $userId);
        $direction = strtolower(leave_clean($input['direction'] ?? '', 20));
        $days = isset($input['days']) ? (float)$input['days'] : 0.0;
        $reason = leave_clean($input['reason'] ?? '', 3000);
        if (!in_array($direction, ['add','reduce'], true)) {
            leave_json(['detail' => 'Choose whether to add or reduce leave days.'], 422);
        }
        if (!is_finite($days) || $days <= 0 || $days > 365) {
            leave_json(['detail' => 'Leave adjustment must be greater than 0 and not more than 365 days.'], 422);
        }
        if ($reason === '') {
            leave_json(['detail' => 'An official reason is required for every HR leave-balance adjustment.'], 422);
        }
        $signed = $direction === 'add' ? $days : -$days;
        $year = (int)date('Y');

        $pdo->beginTransaction();
        $balance = leave_sync_annual_balance($pdo, $userId, $year);
        $before = (float)$balance['available_days'];
        $after = $before + $signed;
        if ($after < 0) {
            $pdo->rollBack();
            leave_json(['detail' => 'This reduction would make the employee leave balance negative. Available balance: ' . number_format($before, 2) . ' day(s).'], 422);
        }

        $update = $pdo->prepare("UPDATE leave_balances
            SET adjustment_days = adjustment_days + ?, updated_by_user_id = ?, updated_at = CURRENT_TIMESTAMP
            WHERE user_id = ? AND leave_type = 'annual' AND leave_year = ?");
        $update->execute([$signed, (int)$user['id'], $userId, $year]);

        $audit = $pdo->prepare("INSERT INTO leave_balance_adjustments (
            user_id, leave_year, amount, before_balance, after_balance, reason,
            actor_user_id, actor_name, actor_position, actor_campus
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $audit->execute([
            $userId, $year, $signed, $before, $after, $reason,
            (int)$user['id'], $profile['name'], $profile['position'], $profile['campus'],
        ]);

        $verb = $direction === 'add' ? 'added to' : 'deducted from';
        $title = $direction === 'add' ? 'Leave balance increased by HR' : 'Leave balance reduced by HR';
        $body = $profile['name'] . ' (' . ($profile['position'] ?: $access['label']) . ') ' .
            ($direction === 'add' ? 'added ' : 'reduced ') . number_format($days, 2) .
            ' day(s) ' . ($direction === 'add' ? 'to' : 'from') . ' your annual leave balance. ' .
            'New balance: ' . number_format($after, 2) . ' day(s). Reason: ' . $reason;
        leave_notify($pdo, null, $userId, 'balance_adjustment', $title, $body);

        $pdo->commit();
        leave_json([
            'message' => number_format($days, 2) . ' leave day(s) ' . $verb . ' ' . ($employee['full_name'] ?? 'the employee') . '.',
            'before_balance' => $before,
            'after_balance' => $after,
            'adjustment' => $signed,
        ]);
    }

    if ($method === 'POST' && $action === 'account_status' && $userId > 0) {
        if (empty($access['can_suspend'])) {
            leave_json(['detail' => 'Only DVC1 may suspend or restore user accounts from the leave control centre.'], 403);
        }
        if ($userId === (int)$user['id']) {
            leave_json(['detail' => 'DVC1 cannot suspend their own active account.'], 422);
        }
        $employee = leave_assert_hr_employee_scope($pdo, $user, $userId);
        $operation = strtolower(leave_clean($input['operation'] ?? '', 20));
        $reason = leave_clean($input['reason'] ?? '', 3000);
        if (!in_array($operation, ['suspend','restore'], true)) {
            leave_json(['detail' => 'Choose suspend or restore.'], 422);
        }
        if ($reason === '') {
            leave_json(['detail' => 'An official reason is required for account suspension or restoration.'], 422);
        }

        $previous = strtolower(leave_clean($employee['account_status'] ?? 'active', 30));
        if ($previous === '') $previous = 'active';
        $next = $operation === 'suspend' ? 'suspended' : 'active';
        if ($previous === $next) {
            leave_json(['detail' => 'This account is already ' . $next . '.'], 422);
        }

        $pdo->beginTransaction();
        if ($operation === 'suspend') {
            $stmt = $pdo->prepare("UPDATE users SET account_status='suspended', suspended_at=CURRENT_TIMESTAMP, suspended_by_user_id=?, suspension_reason=? WHERE id=?");
            $stmt->execute([(int)$user['id'], $reason, $userId]);
            // Suspension takes effect immediately on all existing bearer sessions.
            if (leave_table_exists($pdo, 'user_sessions')) {
                $pdo->prepare("UPDATE user_sessions SET revoked_at=CURRENT_TIMESTAMP WHERE user_id=? AND revoked_at IS NULL")->execute([$userId]);
            }
        } else {
            $stmt = $pdo->prepare("UPDATE users SET account_status='active', suspended_at=NULL, suspended_by_user_id=NULL, suspension_reason=NULL WHERE id=?");
            $stmt->execute([$userId]);
        }

        $audit = $pdo->prepare("INSERT INTO leave_account_status_audit (
            target_user_id, action, previous_status, new_status, reason,
            actor_user_id, actor_name, actor_position, actor_campus
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $audit->execute([
            $userId, $operation, $previous, $next, $reason,
            (int)$user['id'], $profile['name'], $profile['position'], $profile['campus'],
        ]);

        $title = $operation === 'suspend' ? 'Your Rockview account was suspended' : 'Your Rockview account was restored';
        $body = $profile['name'] . ' (' . ($profile['position'] ?: 'DVC1') . ') ' .
            ($operation === 'suspend' ? 'suspended' : 'restored') . ' your account. Reason: ' . $reason .
            ($operation === 'suspend' ? ' Contact the university administration if you require clarification.' : ' You may sign in again using your normal credentials.');
        leave_notify($pdo, null, $userId, 'account_status', $title, $body);
        $pdo->commit();

        leave_json([
            'message' => ($employee['full_name'] ?? 'The account') . ' was ' . ($operation === 'suspend' ? 'suspended' : 'restored') . ' successfully.',
            'account_status' => $next,
        ]);
    }

    leave_json(['detail' => 'Unsupported HR leave ledger operation.'], 405);
} catch (PDOException $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    leave_json(['detail' => 'Database error: ' . $e->getMessage()], 500);
} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    leave_json(['detail' => 'HR leave ledger error: ' . $e->getMessage()], 500);
}
