<?php

/**
 * Product Dashboard Controller V1
 *
 * @package Licenzo\Http\Controller\Api\V1
 */

namespace Licenzo\Http\Controller\Api\V1;

use Licenzo\Framework\Http\Request;
use Licenzo\Model\LicenseActivation;
use Licenzo\Model\LicenseEvent;
use Licenzo\Model\LicenseProduct;
use Licenzo\Model\Product;
use Licenzo\Model\SubscriptionProduct;
use Licenzo\Model\SubscriptionTransaction;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Product Dashboard API controller for product analytics
 */
class ProductDashboardController
{
    /**
     * Get product statistics
     */
    public function stats($id)
    {
        $product = Product::find($id);

        if (!$product) {
            return [
                'success' => false,
                'message' => __('Product not found.', 'licenzo')
            ];
        }

        // Total activations for this product
        $totalActivations = LicenseActivation::where('product_id', $id)->count();

        // Total unique customers who activated this product
        $totalCustomers = LicenseProduct::where('product_id', $id)
            ->with('license')
            ->get()
            ->pluck('license.customer_id')
            ->unique()
            ->count();

        // Total licenses associated with this product
        $totalLicenses = LicenseProduct::where('product_id', $id)
            ->distinct('license_id')
            ->count('license_id');

        $subscriptionIds = SubscriptionProduct::where('product_id', $id)
            ->pluck('subscription_id')
            ->unique()
            ->all();

        $totalSales = count($subscriptionIds);
        $totalRevenue = $subscriptionIds
            ? (float) SubscriptionTransaction::whereIn('subscription_id', $subscriptionIds)
                ->where('status', SubscriptionTransaction::STATUS_SUCCESS)
                ->sum('total')
            : 0.0;

        // Calculate previous week metrics
        $oneWeekAgo = gmdate('Y-m-d H:i:s', time() - WEEK_IN_SECONDS);

        $previousActivations = LicenseActivation::where('product_id', $id)
            ->where('created_at', '<', $oneWeekAgo)
            ->count();

        $previousCustomers = LicenseProduct::where('product_id', $id)
            ->where('created_at', '<', $oneWeekAgo)
            ->with('license')
            ->get()
            ->pluck('license.customer_id')
            ->unique()
            ->count();

        $previousLicenses = LicenseProduct::where('product_id', $id)
            ->where('created_at', '<', $oneWeekAgo)
            ->distinct('license_id')
            ->count('license_id');

        // Helper to calculate % change
        $percentChange = function ($current, $previous) {
            if ($previous == 0) {
                return $current > 0 ? '+100%' : '0%';
            }
            $change = (($current - $previous) / $previous) * 100;
            return ($change >= 0 ? '+' : '') . round($change, 1) . '%';
        };

        return [
            'success' => true,
            'stats' => [
                'total_customers' => $totalCustomers,
                'total_customers_delta' => $percentChange($totalCustomers, $previousCustomers),
                'total_sales' => $totalSales,
                'total_sales_delta' => $percentChange($totalSales, $totalSales),
                'total_revenue' => round($totalRevenue, 2),
                'total_revenue_delta' => $percentChange($totalRevenue, $totalRevenue),
                'total_activations' => $totalActivations,
                'total_activations_delta' => $percentChange($totalActivations, $previousActivations),
                'total_licenses' => $totalLicenses,
                'total_licenses_delta' => $percentChange($totalLicenses, $previousLicenses),
            ]
        ];
    }




    /**
     * Get recent activation requests
     */
    public function recentRequests($id)
    {
        $activities = LicenseActivation::with('events')->where('product_id', $id)
            ->orderBy('created_at', 'desc')
            ->limit(20)
            ->get();

        $logs = [];

        foreach ($activities as $activation) {
            $productName = $activation->product_name ?? 'Unknown Product';
            $variationName = $activation->variation_name ?? '';

            foreach ($activation->events as $event) {
                $customer = $event->event_data['customer'] ?? [];
                $license = $event->event_data['license'] ?? [];
                $activationData = $event->event_data['activation'] ?? [];

                $logs[] = [
                    'id' => $activation->id . '-' . $event->id,
                    'event_type' => $event->event_type ?? 'Unknown',
                    'event_source' => $event->event_source ?? 'api',
                    'date' => $event->created_at ?? null,
                    'product' => trim($productName . ' ' . ($variationName ? "($variationName)" : '')),
                    'license_key' => $license['license_key'] ?? 'N/A',
                    'instance' => $activationData['instance_identifier'] ?? 'N/A',
                    'status' => $event->response_status,
                    'author' => trim(($customer['first_name'] ?? '') . ' ' . ($customer['last_name'] ?? '')) ?: 'System',
                    'description' => 'Event: ' . ($event->event_type ?? 'Unknown') . ' via ' . ($event->event_source ?? 'api'),
                ];
            }
        }

        // Sort newest first
        usort($logs, fn($a, $b) => strtotime($b['date']) <=> strtotime($a['date']));

        return [
            'success' => true,
            'activities' => $logs,
        ];
    }

    /**
     * Get chart data for all products over the last N days
     *
     * @param  \Licenzo\Framework\Http\Request $request
     * @return array
     */
    public function chartData($id, Request $request)
    {
        $days = absint($request->get('days') ?? 14);
        $chartData = [];
        $labels = [];

        for ($i = $days - 1; $i >= 0; $i--) {
            $date = gmdate('Y-m-d', strtotime("-{$i} days"));
            $dateStart = $date . ' 00:00:00';
            $dateEnd = $date . ' 23:59:59';

            $count = LicenseActivation::where('product_id', $id)
                ->where('created_at', '>=', $dateStart)
                ->where('created_at', '<=', $dateEnd)
                ->count();

            $chartData[] = $count;
            $labels[] = gmdate('M j', strtotime($date));
        }

        return [
            'success' => true,
            'data' => [
                'labels' => $labels,
                'data' => $chartData,
                'period' => $days . ' days'
            ]
        ];
    }
}
