<?php
namespace App\Repositories;

use App\Models\SiteSettings;
use App\Models\User;
use App\Repositories\Interfaces\UserInterface;
use DB;
use Illuminate\Http\Request;

class UserRepository implements UserInterface
{
    public function getUserList(Request $request)
    {
        $query = User::select(
            'id',
            'ref_employee_id',
            'ref_code',
            'first_name',
            'last_name',
            'email',
            'phone_number',
            'status',
            'role_id',
            'is_delete',
            'created_at',
            DB::raw("DATE_FORMAT(created_at, '%d/%m/%Y') as joining_date")
        )
            ->where('role_id', 3)
            ->with('ref_user')
            ->orderBy('id', 'desc');

if ($request->filled('name')) {
    $search = $request->name;

    $query->where(function ($q) use ($search) {
        $q->where(DB::raw("CONCAT(first_name, ' ', last_name)"), 'like', '%' . $search . '%')
          ->orWhere('first_name', 'like', '%' . $search . '%')
          ->orWhere('last_name', 'like', '%' . $search . '%');
    });
}

        if ($request->filled('email')) {
            $query->where('email', 'like', '%' . $request->email . '%');
        }

        if ($request->filled('from_date')) {
            $query->whereDate('created_at', '>=', $request->from_date);
        }

        if ($request->filled('to_date')) {
            $query->whereDate('created_at', '<=', $request->to_date);
        }

        return $query->get();
    }

    public function siteSettingsList()
    {
        return ['site_settings' => SiteSettings::first()];
    }

    public function updateSiteSettings($data)
    {
        $siteSettings = SiteSettings::first();

        if ($siteSettings) {
            $siteSettings->update($data);
            return $siteSettings;
        }
        return null;
    }

}
