<?php

namespace App\Services;

use App\Models\Tenants\Site;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;

class SiteService extends Service
{
    /**
     * 현장 목록 조회
     */
    public function index(array $params): LengthAwarePaginator
    {
        $tenantId = $this->tenantId();

        $query = Site::query()
            ->with('client:id,name')
            ->where('tenant_id', $tenantId);

        // 검색 필터
        if (! empty($params['search'])) {
            $search = $params['search'];
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('site_code', 'like', "%{$search}%")
                    ->orWhere('address', 'like', "%{$search}%");
            });
        }

        // 활성화 상태 필터
        if (isset($params['is_active'])) {
            $query->where('is_active', $params['is_active']);
        }

        // 상태 필터
        if (! empty($params['status'])) {
            $query->where('status', $params['status']);
        }

        // 거래처 필터
        if (! empty($params['client_id'])) {
            $query->where('client_id', $params['client_id']);
        }

        // 날짜 필터
        if (! empty($params['start_date'])) {
            $query->whereDate('created_at', '>=', $params['start_date']);
        }
        if (! empty($params['end_date'])) {
            $query->whereDate('created_at', '<=', $params['end_date']);
        }

        // 정렬
        $sortBy = $params['sort_by'] ?? 'created_at';
        $sortDir = $params['sort_dir'] ?? 'desc';
        $query->orderBy($sortBy, $sortDir);

        // 페이지네이션
        $perPage = $params['per_page'] ?? 20;

        return $query->paginate($perPage);
    }

    /**
     * 현장 통계 조회
     */
    public function stats(): array
    {
        $tenantId = $this->tenantId();

        $total = Site::where('tenant_id', $tenantId)->count();

        $statusCounts = Site::where('tenant_id', $tenantId)
            ->selectRaw('status, COUNT(*) as count')
            ->groupBy('status')
            ->pluck('count', 'status')
            ->toArray();

        return [
            'total' => $total,
            'construction' => $statusCounts[Site::STATUS_ACTIVE] ?? 0,
            'unregistered' => $statusCounts[Site::STATUS_UNREGISTERED] ?? 0,
            'suspended' => $statusCounts[Site::STATUS_SUSPENDED] ?? 0,
            'pending' => $statusCounts[Site::STATUS_PENDING] ?? 0,
        ];
    }

    /**
     * 현장 상세 조회
     */
    public function show(int $id): Site
    {
        $tenantId = $this->tenantId();

        return Site::query()
            ->with('client:id,name')
            ->where('tenant_id', $tenantId)
            ->findOrFail($id);
    }

    /**
     * 현장 등록
     */
    public function store(array $data): Site
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        return DB::transaction(function () use ($data, $tenantId, $userId) {
            $site = Site::create([
                'tenant_id' => $tenantId,
                'site_code' => $data['site_code'] ?? null,
                'client_id' => $data['client_id'] ?? null,
                'name' => $data['name'],
                'address' => $data['address'] ?? null,
                'latitude' => $data['latitude'] ?? null,
                'longitude' => $data['longitude'] ?? null,
                'is_active' => $data['is_active'] ?? true,
                'status' => $data['status'] ?? Site::STATUS_UNREGISTERED,
                'created_by' => $userId,
                'updated_by' => $userId,
            ]);

            return $site->load('client:id,name');
        });
    }

    /**
     * 현장 수정
     */
    public function update(int $id, array $data): Site
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        return DB::transaction(function () use ($id, $data, $tenantId, $userId) {
            $site = Site::query()
                ->where('tenant_id', $tenantId)
                ->findOrFail($id);

            $site->fill([
                'site_code' => $data['site_code'] ?? $site->site_code,
                'client_id' => array_key_exists('client_id', $data) ? $data['client_id'] : $site->client_id,
                'name' => $data['name'] ?? $site->name,
                'address' => $data['address'] ?? $site->address,
                'latitude' => $data['latitude'] ?? $site->latitude,
                'longitude' => $data['longitude'] ?? $site->longitude,
                'is_active' => $data['is_active'] ?? $site->is_active,
                'status' => $data['status'] ?? $site->status,
                'updated_by' => $userId,
            ]);

            $site->save();

            return $site->fresh()->load('client:id,name');
        });
    }

    /**
     * 현장 삭제
     */
    public function destroy(int $id): bool
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        return DB::transaction(function () use ($id, $tenantId, $userId) {
            $site = Site::query()
                ->where('tenant_id', $tenantId)
                ->findOrFail($id);

            $site->deleted_by = $userId;
            $site->save();
            $site->delete();

            return true;
        });
    }

    /**
     * 현장 일괄 삭제
     */
    public function bulkDestroy(array $ids): int
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        return DB::transaction(function () use ($ids, $tenantId, $userId) {
            $sites = Site::query()
                ->where('tenant_id', $tenantId)
                ->whereIn('id', $ids)
                ->get();

            $deletedCount = 0;
            foreach ($sites as $site) {
                $site->deleted_by = $userId;
                $site->save();
                $site->delete();
                $deletedCount++;
            }

            return $deletedCount;
        });
    }

    /**
     * 활성화된 현장 목록 조회 (셀렉트박스용)
     */
    public function getActiveSites(): array
    {
        $tenantId = $this->tenantId();

        return Site::query()
            ->where('tenant_id', $tenantId)
            ->where('is_active', true)
            ->orderBy('name')
            ->get(['id', 'site_code', 'name', 'address'])
            ->toArray();
    }
}
