<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\GlobalTransaction;
use App\Models\User;
use App\Models\Market\Store;
use App\Models\Market\Product;
use Hypervel\Support\Facades\DB;
use Hypervel\Support\Facades\Log;

class ActivityService
{
    /**
     * Get recent activities from multiple sources.
     *
     * @param int $limit
     * @return array
     */
    public function getRecentActivities(int $limit = 10): array
    {
        $activities = [];

        // 1. Recent Transactions
        try {
            $transactions = GlobalTransaction::with(['user', 'product', 'store'])
                ->orderBy('id', 'desc')
                ->limit($limit)
                ->get();

            foreach ($transactions as $txn) {
                $userName = $txn->user->name ?? 'System';
                $productName = $txn->product->name ?? '';
                $amount = number_format((float) $txn->amount, 2);
                $typeName = $txn->type->name ?? 'Sale';
                
                $subtitle = $typeName . ' - ₱' . $amount;
                if ($productName) {
                    $subtitle .= ' (' . $productName . ')';
                }

                $activities[] = [
                    'id' => 'txn_' . $txn->id,
                    'type' => 'transaction',
                    'title' => 'New Transaction',
                    'subtitle' => $subtitle,
                    'icon' => '/assets/transaction.png',
                    'timestamp' => $txn->created_at->toISOString(),
                    'pagename' => 'ManageGlobalTransactions',
                    'pagestring' => (string) $txn->id
                ];
            }
        } catch (\Exception $e) {
            Log::warning('ActivityService: Failed to fetch transactions', ['error' => $e->getMessage()]);
        }

        // 2. Recent Users
        try {
            $users = User::orderBy('id', 'desc')
                ->limit(min(5, $limit))
                ->get();

            foreach ($users as $user) {
                $activities[] = [
                    'id' => 'user_' . $user->id,
                    'type' => 'user_registration',
                    'title' => 'User Registered',
                    'subtitle' => $user->name . ' (' . ($user->role ?? 'Member') . ')',
                    'icon' => '/assets/user-list.png',
                    'timestamp' => $user->created_at->toISOString(),
                    'pagename' => 'UserList',
                    'pagestring' => (string) $user->id
                ];
            }
        } catch (\Exception $e) {
            Log::warning('ActivityService: Failed to fetch users', ['error' => $e->getMessage()]);
        }

        // 3. Recent Stores
        try {
            $stores = Store::orderBy('id', 'desc')
                ->limit(min(5, $limit))
                ->get();

            foreach ($stores as $store) {
                $activities[] = [
                    'id' => 'store_' . $store->id,
                    'type' => 'store_creation',
                    'title' => 'Store Created',
                    'subtitle' => $store->name . ' - ' . ($store->category ?? 'General'),
                    'icon' => '/assets/store.png',
                    'timestamp' => $store->created_at->toISOString(),
                    'pagename' => 'ManageStoresAdmin',
                    'pagestring' => (string) $store->id
                ];
            }
        } catch (\Exception $e) {
            Log::warning('ActivityService: Failed to fetch stores', ['error' => $e->getMessage()]);
        }

        // 4. Recent Products
        try {
            $products = Product::orderBy('id', 'desc')
                ->limit(min(5, $limit))
                ->get();

            foreach ($products as $product) {
                $price = number_format((float) ($product->price ?? 0), 2);
                $activities[] = [
                    'id' => 'product_' . $product->id,
                    'type' => 'product_added',
                    'title' => 'Product Added',
                    'subtitle' => $product->name . ' - ₱' . $price,
                    'icon' => '/assets/products.png',
                    'timestamp' => $product->created_at->toISOString(),
                    'pagename' => 'ManageProductsAdmin',
                    'pagestring' => (string) $product->id
                ];
            }
        } catch (\Exception $e) {
            Log::warning('ActivityService: Failed to fetch products', ['error' => $e->getMessage()]);
        }

        // Sort by timestamp descending
        usort($activities, function ($a, $b) {
            return strcmp($b['timestamp'], $a['timestamp']);
        });

        return array_slice($activities, 0, $limit);
    }

    /**
     * Search activities.
     *
     * @param string $query
     * @param int $limit
     * @return array
     */
    public function searchActivities(string $query, int $limit = 20): array
    {
        // Simple search logic for demo purposes
        $activities = $this->getRecentActivities(100);
        $q = strtolower($query);

        $filtered = array_filter($activities, function ($a) use ($q) {
            return str_contains(strtolower($a['title']), $q) ||
                   str_contains(strtolower($a['subtitle']), $q);
        });

        return array_slice(array_values($filtered), 0, $limit);
    }
}
