<?php

namespace App\Services\Finance;

use App\Models\Expense;
use Illuminate\Support\Facades\Schema;

class ExpensePayrollService
{
    public function markProcessedForEmployee(int $userId, int $companyId, int $cycleId, int $year, int $month): int
    {
        if (! class_exists(Expense::class)) {
            return 0;
        }

        $table = (new Expense)->getTable();
        if (! Schema::hasTable($table) || ! Schema::hasColumn($table, 'payroll_cycle_id')) {
            return 0;
        }

        $query = Expense::withoutGlobalScopes()
            ->where('company_id', $companyId)
            ->where('user_id', $userId)
            ->where('status', 'approved')
            ->whereNull('payroll_cycle_id');

        $this->applyPeriodFilter($query, $table, $year, $month);

        return $query->update([
            'payroll_cycle_id' => $cycleId,
            'status' => 'paid',
        ]);
    }

    public function revertForPeriod(int $companyId, int $year, int $month): int
    {
        if (! class_exists(Expense::class)) {
            return 0;
        }

        $table = (new Expense)->getTable();
        if (! Schema::hasTable($table) || ! Schema::hasColumn($table, 'payroll_cycle_id')) {
            return 0;
        }

        $query = Expense::withoutGlobalScopes()
            ->where('company_id', $companyId)
            ->where('status', 'paid')
            ->whereNotNull('payroll_cycle_id');

        $this->applyPeriodFilter($query, $table, $year, $month);

        return $query->update([
            'payroll_cycle_id' => null,
            'status' => 'approved',
        ]);
    }

    protected function applyPeriodFilter($query, string $table, int $year, int $month): void
    {
        if (Schema::hasColumn($table, 'date')) {
            $query->whereYear('date', $year)->whereMonth('date', $month);
        } elseif (Schema::hasColumn($table, 'expense_date')) {
            $query->whereYear('expense_date', $year)->whereMonth('expense_date', $month);
        } elseif (Schema::hasColumn($table, 'year') && Schema::hasColumn($table, 'month')) {
            $query->where('year', $year)->where('month', $month);
        } else {
            $query->whereRaw('1 = 0');
        }
    }
}
