<?php

namespace App\Reports\NewPurchases;

use App\Reports\BaseReport;
use Illuminate\Support\Facades\DB;

class NewPurchases extends BaseReport
{
    public function getName(): string
    {
        return __('admin/reports.new_purchases_name');
    }

    public function getDescription(): string
    {
        return __('admin/reports.new_purchases_description');
    }

    public function getCategory(): string
    {
        return __('admin/reports.new_purchases_category');
    }

    public function getIcon(): string
    {
        return 'fas fa-shopping-cart';
    }

    public function getRouteName(): string
    {
        return 'new-purchases';
    }

    public function getRequiredPermission(): string
    {
        return 'generate reports';
    }

    public function getData(array $filters = []): array
    {
        $filters = $this->validateFilters($filters);

        $startDate = $filters['start_date'] ?? now()->subMonth();
        $endDate = $filters['end_date'] ?? now();

        $query = DB::table('client_products')
            ->whereNull('client_products.deleted_at') // PRC-752 — soft-deleted hariç
            ->whereBetween('client_products.created_at', [$startDate, $endDate]);

        $period = $filters['period'] ?? 'monthly';
        $product_category = $filters['product_category'] ?? 'all';
        $payment_method = $filters['payment_method'] ?? 'all';

        $query->join('clients', 'client_products.client_id', '=', 'clients.id')
            ->whereNull('clients.deleted_at') // PRC-735 — soft-deleted hariç
            ->join('products', 'client_products.product_id', '=', 'products.id');

        if ($product_category !== 'all') {
            $query->join('product_categories', 'products.category_id', '=', 'product_categories.id')
                ->where('product_categories.slug', $product_category);
        }

        if ($payment_method !== 'all') {
            $query->leftJoin('transactions', function ($join) {
                $join->on('client_products.id', '=', 'transactions.reference_id')
                    ->where('transactions.reference_type', '=', 'client_product');
            })->where('transactions.payment_method', $payment_method);
        }

        switch ($period) {
            case 'daily':
                $query->selectRaw('
                    DATE(client_products.created_at) as period,
                    COUNT(*) as total_purchases,
                    COUNT(DISTINCT client_products.client_id) as unique_customers,
                    SUM(client_products.recurring_amount) as total_revenue,
                    AVG(client_products.recurring_amount) as average_order_value
                ')
                    ->groupByRaw('DATE(client_products.created_at)')
                    ->orderBy('period');
                break;

            case 'weekly':
                $query->selectRaw('
                    YEARWEEK(client_products.created_at) as period,
                    COUNT(*) as total_purchases,
                    COUNT(DISTINCT client_products.client_id) as unique_customers,
                    SUM(client_products.recurring_amount) as total_revenue,
                    AVG(client_products.recurring_amount) as average_order_value
                ')
                    ->groupByRaw('YEARWEEK(client_products.created_at)')
                    ->orderBy('period');
                break;

            case 'monthly':
            default:
                $query->selectRaw('
                    DATE_FORMAT(client_products.created_at, "%Y-%m") as period,
                    COUNT(*) as total_purchases,
                    COUNT(DISTINCT client_products.client_id) as unique_customers,
                    SUM(client_products.recurring_amount) as total_revenue,
                    AVG(client_products.recurring_amount) as average_order_value
                ')
                    ->groupByRaw('DATE_FORMAT(client_products.created_at, "%Y-%m")')
                    ->orderBy('period');
                break;
        }

        return $query->get()->toArray();
    }

    public function getColumns(): array
    {
        return [
            'period' => [
                'title' => __('admin/reports.new_purchases_column_period'),
                'type' => 'string',
                'sortable' => true,
            ],
            'total_purchases' => [
                'title' => __('admin/reports.new_purchases_column_total_purchases'),
                'type' => 'number',
                'sortable' => true,
            ],
            'unique_customers' => [
                'title' => __('admin/reports.new_purchases_column_unique_customers'),
                'type' => 'number',
                'sortable' => true,
            ],
            'total_revenue' => [
                'title' => __('admin/reports.new_purchases_column_total_revenue'),
                'type' => 'currency',
                'sortable' => true,
            ],
            'average_order_value' => [
                'title' => __('admin/reports.new_purchases_column_average_order_value'),
                'type' => 'currency',
                'sortable' => true,
            ],
        ];
    }

    public function getFilters(): array
    {
        return [
            'start_date' => [
                'type' => 'date',
                'label' => __('admin/reports.new_purchases_filter_start_date'),
                'required' => false,
                'default' => now()->subMonth()->format('Y-m-d'),
            ],
            'end_date' => [
                'type' => 'date',
                'label' => __('admin/reports.new_purchases_filter_end_date'),
                'required' => false,
                'default' => now()->format('Y-m-d'),
            ],
            'period' => [
                'type' => 'select',
                'label' => __('admin/reports.new_purchases_filter_period'),
                'required' => false,
                'options' => [
                    'daily' => __('admin/reports.new_purchases_period_daily'),
                    'weekly' => __('admin/reports.new_purchases_period_weekly'),
                    'monthly' => __('admin/reports.new_purchases_period_monthly'),
                ],
                'default' => 'monthly',
            ],
            'product_category' => [
                'type' => 'select',
                'label' => __('admin/reports.new_purchases_filter_product_category'),
                'required' => false,
                'options' => [
                    'all' => __('admin/reports.new_purchases_category_all'),
                    'hosting' => __('admin/reports.new_purchases_category_hosting'),
                    'domain' => __('admin/reports.new_purchases_category_domain'),
                    'ssl' => __('admin/reports.new_purchases_category_ssl'),
                    'software' => __('admin/reports.new_purchases_category_software'),
                ],
                'default' => 'all',
            ],
            'payment_method' => [
                'type' => 'select',
                'label' => __('admin/reports.new_purchases_filter_payment_method'),
                'required' => false,
                'options' => [
                    'all' => __('admin/reports.new_purchases_payment_all'),
                    'credit_card' => __('admin/reports.new_purchases_payment_credit_card'),
                    'bank_transfer' => __('admin/reports.new_purchases_payment_bank_transfer'),
                    'paypal' => __('admin/reports.new_purchases_payment_paypal'),
                    'crypto' => __('admin/reports.new_purchases_payment_crypto'),
                ],
                'default' => 'all',
            ],
        ];
    }

    public function hasChart(): bool
    {
        return true;
    }

    public function getChartData(array $filters = []): ?array
    {
        $data = $this->getData($filters);

        return [
            'labels' => array_column($data, 'period'),
            'datasets' => [
                [
                    'label' => __('admin/reports.new_purchases_chart_total_purchases'),
                    'data' => array_column($data, 'total_purchases'),
                    'backgroundColor' => 'rgba(255, 99, 132, 0.8)',
                    'borderColor' => 'rgba(255, 99, 132, 1)',
                    'borderWidth' => 2,
                    'yAxisID' => 'y',
                ],
                [
                    'label' => __('admin/reports.new_purchases_chart_total_revenue'),
                    'data' => array_column($data, 'total_revenue'),
                    'backgroundColor' => 'rgba(54, 162, 235, 0.8)',
                    'borderColor' => 'rgba(54, 162, 235, 1)',
                    'borderWidth' => 2,
                    'yAxisID' => 'y1',
                ],
            ],
        ];
    }

    public function getChartType(): string
    {
        return 'bar';
    }
}
