<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Modules\HR\Core\Models\Employee;
use App\Modules\HR\Payroll\Models\Addition;
use App\Modules\HR\Payroll\Models\Deduction;

class SyncEmployeePayroll extends Command
{
    protected $signature = 'hr:sync-employee-payroll
                            {--force : Skip confirmation prompt}';

    protected $description = 'Clear employee_additions & employee_deductions, then re-seed each employee with their branch additions/deductions';

    public function handle(): int
    {
        if (! $this->option('force')) {
            $this->warn('This will DELETE ALL records from employee_additions and employee_deductions');
            $this->warn('and re-insert them based on each employee\'s branch.');

            if (! $this->confirm('Are you sure you want to continue?')) {
                $this->info('Aborted.');
                return Command::SUCCESS;
            }
        }

        DB::transaction(function () {

            /* ── 1. Empty both tables ───────────────────────────── */
            $deletedAdditions  = DB::table('employee_additions')->delete();
            $deletedDeductions = DB::table('employee_deductions')->delete();

            $this->info("Deleted {$deletedAdditions} employee addition record(s).");
            $this->info("Deleted {$deletedDeductions} employee deduction record(s).");

            /* ── 2. Load all employees ──────────────────────────── */
            $employees = Employee::all();

            $this->info("Found {$employees->count()} employee(s). Processing…");
            $this->newLine();

            $totalAdditions  = 0;
            $totalDeductions = 0;

            foreach ($employees as $employee) {

                if (! $employee->branch_id) {
                    $this->warn("  Employee #{$employee->id} ({$employee->first_name} {$employee->last_name}) has no branch — skipped.");
                    continue;
                }

                /* ── Additions for this branch ─────────────────── */
                $additions = Addition::withoutGlobalScopes()
                    ->where('branch_id', $employee->branch_id)
                    ->where('status', true)
                    ->get();

                foreach ($additions as $addition) {
                    $amount = match ($addition->calculation_type) {
                        'fixed', 'both' => $addition->fixed_amount ?? 0,
                        default         => 0,   // formula
                    };

                    DB::table('employee_additions')->insert([
                        'employee_id'      => $employee->id,
                        'addition_id'      => $addition->id,
                        'calculation_type' => $addition->calculation_type,
                        'amount'           => $amount,
                        'status'           => true,
                        'created_at'       => now(),
                        'updated_at'       => now(),
                    ]);

                    $totalAdditions++;
                }

                /* ── Deductions for this branch ────────────────── */
                $deductions = Deduction::withoutGlobalScopes()
                    ->where('branch_id', $employee->branch_id)
                    ->where('status', true)
                    ->get();

                foreach ($deductions as $deduction) {
                    $amount = match ($deduction->calculation_type) {
                        'fixed', 'both' => $deduction->fixed_amount ?? 0,
                        default         => 0,   // formula
                    };

                    DB::table('employee_deductions')->insert([
                        'employee_id'      => $employee->id,
                        'deduction_id'     => $deduction->id,
                        'calculation_type' => $deduction->calculation_type,
                        'amount'           => $amount,
                        'status'           => true,
                        'created_at'       => now(),
                        'updated_at'       => now(),
                    ]);

                    $totalDeductions++;
                }

                $this->line("  Employee #{$employee->id} {$employee->first_name} {$employee->last_name} — branch {$employee->branch_id}: {$additions->count()} addition(s), {$deductions->count()} deduction(s).");
            }

            $this->newLine();
            $this->info("Done. Inserted {$totalAdditions} addition record(s) and {$totalDeductions} deduction record(s).");
        });

        return Command::SUCCESS;
    }
}
