<?php

namespace App\Services;

use App\Models\EmployeeSalaryAssignment;
use App\Models\SalaryIncrement;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class SalaryIncrementService
{
    /**
     * Approve a pending salary increment and apply it to the employee's assignment.
     */
    public function approveIncrement(SalaryIncrement $increment, User $approver): void
    {
        if ($increment->status !== 'pending') {
            throw new \Exception('Only pending increments can be approved.');
        }

        DB::transaction(function () use ($increment, $approver) {
            $assignment = EmployeeSalaryAssignment::where('employee_id', $increment->employee_id)
                ->orderByDesc('effective_from')
                ->firstOrFail();

            // Apply the new salary
            $assignment->update([
                'gross_salary' => $increment->new_salary,
                'effective_from' => $increment->effective_date->format('Y-m-d'),
            ]);

            $increment->update([
                'status' => 'approved',
                'approved_by' => $approver->id,
                'approved_at' => now(),
            ]);
        });
    }

    /**
     * Reject a pending salary increment.
     */
    public function rejectIncrement(SalaryIncrement $increment, User $approver): void
    {
        if ($increment->status !== 'pending') {
            throw new \Exception('Only pending increments can be rejected.');
        }

        $increment->update([
            'status' => 'rejected',
            'approved_by' => $approver->id,
            'approved_at' => now(),
        ]);
    }
}
