<?php

namespace App\Repositories;

use App\Models\AuditLog;
use Illuminate\Database\Eloquent\Builder;

class AuditLogRepository extends BaseRepository
{
    protected $model;

    public function __construct()
    {
        $this->model = new AuditLog();
    }

    public function getAllByOrganization(?string $orgHex)
    {
        $query = $this->model->query();
        return $this->applyOrganizationScope($query, $orgHex)
            ->orderBy('created_at', 'desc')
            ->get();
    }

    public function paginateByOrganization(?string $orgHex, int $perPage = 50, array $filters = [])
    {
        $safePerPage = max(1, min(200, $perPage));

        $query = $this->model->query();
        $query = $this->applyOrganizationScope($query, $orgHex);
        $query = $this->applyDateFilterScope($query, $filters);

        $user = $filters['user'] ?? null;
        if ($user) {
            $query->where('username', $user);
        }

        $tab = $filters['tab'] ?? null;
        if ($tab) {
            $query->where('tab_name', $tab);
        }

        $query->orderBy('created_at', 'desc');

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

    public function getUsersByOrganization(?string $orgHex)
    {
        $query = $this->model->select('username')
            ->distinct()
            ->whereNotNull('username')
            ->where('username', '!=', '');
        return $this->applyOrganizationScope($query, $orgHex)
            ->orderBy('username')
            ->pluck('username')
            ->toArray();
    }

    public function getDashboardMetrics(?string $orgHex, array $filters = [])
    {
        $query = $this->model->query();
        $query = $this->applyOrganizationScope($query, $orgHex);
        $query = $this->applyDateFilterScope($query, $filters);

        $result = (clone $query)
            ->selectRaw('COUNT(*) as total')
            ->selectRaw("SUM(CASE WHEN action = 'Tạo KOC' THEN 1 ELSE 0 END) as create_koc")
            ->selectRaw("SUM(CASE WHEN action = 'Cập nhật KOC' THEN 1 ELSE 0 END) as update_koc")
            ->selectRaw("SUM(CASE WHEN action = 'Xóa KOC' THEN 1 ELSE 0 END) as delete_koc")
            ->selectRaw("SUM(CASE WHEN action = 'Tạo chiến dịch' THEN 1 ELSE 0 END) as create_campaign")
            ->selectRaw("SUM(CASE WHEN action = 'Cập nhật chiến dịch' THEN 1 ELSE 0 END) as update_campaign")
            ->selectRaw("SUM(CASE WHEN action = 'Xóa chiến dịch' THEN 1 ELSE 0 END) as delete_campaign")
            ->selectRaw("SUM(CASE WHEN action = 'Thêm KOC vào chiến dịch' THEN 1 ELSE 0 END) as add_koc_campaign")
            ->selectRaw("SUM(CASE WHEN action = 'Loại bỏ KOC khỏi chiến dịch' THEN 1 ELSE 0 END) as remove_koc_campaign")
            ->selectRaw("SUM(CASE WHEN action = 'Cập nhật booking koc' THEN 1 ELSE 0 END) as update_booking")
            ->selectRaw("SUM(CASE WHEN action IN ('Nhập hàng loạt KOC', 'Nhập CSV KOC', 'Cập nhật hàng loạt KOC') THEN 1 ELSE 0 END) as import_koc")
            ->selectRaw("SUM(CASE WHEN action = 'Đăng nhập' THEN 1 ELSE 0 END) as login_count")
            ->selectRaw("SUM(CASE WHEN action IN ('Tạo người dùng', 'Cập nhật người dùng', 'Xóa người dùng', 'Thay đổi mật khẩu') THEN 1 ELSE 0 END) as user_actions")
            ->selectRaw("SUM(CASE WHEN action IN ('Tải lên video', 'Cập nhật video', 'Xóa video') THEN 1 ELSE 0 END) as video_actions")
            ->first();

        return [
            'total_operations' => number_format((int)($result->total ?? 0)),
            'koc_created' => number_format((int)($result->create_koc ?? 0)),
            'koc_updated' => number_format((int)($result->update_koc ?? 0)),
            'koc_deleted' => number_format((int)($result->delete_koc ?? 0)),
            'campaigns_created' => number_format((int)($result->create_campaign ?? 0)),
            'campaigns_updated' => number_format((int)($result->update_campaign ?? 0)),
            'campaigns_deleted' => number_format((int)($result->delete_campaign ?? 0)),
            'koc_added_to_campaign' => number_format((int)($result->add_koc_campaign ?? 0)),
            'koc_removed_from_campaign' => number_format((int)($result->remove_koc_campaign ?? 0)),
            'bookings_updated' => number_format((int)($result->update_booking ?? 0)),
            'imports_bulk' => number_format((int)($result->import_koc ?? 0)),
            'logins' => number_format((int)($result->login_count ?? 0)),
            'user_management' => number_format((int)($result->user_actions ?? 0)),
            'video_management' => number_format((int)($result->video_actions ?? 0)),
        ];
    }

    public function deleteByIdInOrganization(int $id, ?string $orgHex)
    {
        $query = $this->model->where('id', $id);
        $record = $this->applyOrganizationScope($query, $orgHex)->first();
        if ($record) {
            return $record->delete();
        }
        return false;
    }

    public function deleteAllInOrganization(?string $orgHex)
    {
        $query = $this->model->query();
        $query = $this->applyOrganizationScope($query, $orgHex);
        return $query->delete();
    }

    public function countInOrganization(?string $orgHex)
    {
        $query = $this->model->query();
        return $this->applyOrganizationScope($query, $orgHex)->count();
    }

    private function applyDateFilterScope(Builder $query, array $filters): Builder
    {
        $startDate = $filters['start_date'] ?? null;
        if ($startDate) {
            $query->where('created_at', '>=', $startDate . ' 00:00:00');
        }

        $endDate = $filters['end_date'] ?? null;
        if ($endDate) {
            $query->where('created_at', '<=', $endDate . ' 23:59:59');
        }

        return $query;
    }
}
