<?php
namespace App\Services;

use App\Models\Entry_time;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Schema;

class EntrytimeServices
{
    public function getEntrytimeData(
        int $page,
        int $length,
        ?string $searchValue = null,
        ?string $status = null,
        ?int $companyId = null
    ): LengthAwarePaginator
    {
        $query = Entry_time::query()
            ->select(['id', 'entry_time', 'exit_time', 'period', 'is_active', 'created_at'])
            ->orderByDesc('id');

        if ($companyId !== null && $companyId > 0) {
            $query->where('company_id', $companyId);
        }

        if (! empty($searchValue)) {
            $query->where(function ($subQuery) use ($searchValue): void {
                $subQuery->where('entry_time', 'like', "%{$searchValue}%")
                    ->orWhere('exit_time', 'like', "%{$searchValue}%")
                    ->orWhere('period', 'like', "%{$searchValue}%");
            });
        }

        if (! empty($status) && Schema::hasColumn('entry_time', 'status')) {
            $query->where('status', $status);
        }

        return $query->paginate($length, ['*'], 'page', $page);
    }

    public function getEntrytimeDataCollection(?int $companyId = null): Collection
    {
        $query = Entry_time::query()->orderBy('entry_time');

        if ($companyId !== null && $companyId > 0) {
            $query->where('company_id', $companyId);
        }

        return $query->get();
    }

    public function getEntrytimeById(int $id, ?int $companyId = null)
    {
        if($id) {
            return Entry_time::find($id);
        }

        $query = Entry_time::query()->orderBy('entry_time');
        if ($companyId !== null && $companyId > 0) {
            $query->where('company_id', $companyId);
        }
        return $query->get();
    }

    public function createEntrytime(array $data): Entry_time
    {
        return Entry_time::create([
            'entry_time' => $data['entry_time'],
            'exit_time' => $data['exit_time'],
            'period' => $data['period'],
            'is_active' => (bool) ($data['is_active'] ?? true),
            'company_id' => $data['company_id'] ?? null,
        ]);
    }

    public function updateEntrytime(Entry_time $entryTime, array $data): Entry_time
    {
        $entryTime->update([
            'entry_time' => $data['entry_time'],
            'exit_time' => $data['exit_time'],
            'period' => $data['period'],
            'is_active' => (bool) ($data['is_active'] ?? false),
        ]);

        return $entryTime->refresh();
    }

    public function deleteEntrytime(Entry_time $entryTime): void
    {
        $entryTime->delete();
    }
}
