<?php

namespace App\Http\Controllers\Admin\Charts;

use Backpack\CRUD\app\Http\Controllers\ChartController;
use ConsoleTVs\Charts\Classes\Chartjs\Chart;
use App\Models\Product;
use App\Models\Subscription;

/**
 * Class ProductsSplitChartController
 * @package App\Http\Controllers\Admin\Charts
 * @property-read \Backpack\CRUD\app\Library\CrudPanel\CrudPanel $crud
 */
class ProductsSplitChartController extends ChartController
{
    public function setup()
    {
        $this->chart = new Chart();

        // Set the type of chart to 'pie'
        $this->chart->type('pie');

        // RECOMMENDED. Set URL that the ChartJS library should call, to get its data using AJAX.
        $this->chart->load(backpack_url('charts/products-split'));

        // OPTIONAL
        $this->chart->minimalist(false);
        $this->chart->displayLegend(true);
    }

    /**
     * Respond to AJAX calls with all the chart data points.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function data()
    {
        // Fetch product names and total contract value for each product from subscriptions
        $productsData = Subscription::selectRaw('product_id, SUM(contract_value) as total_contract_value')
            ->groupBy('product_id')
            ->with('product')
            ->get()
            ->map(function ($subscription) {
                return [
                    'label' => $subscription->product->name ?? 'Unknown Product',
                    'value' => $subscription->total_contract_value,
                ];
            });

        // Extract labels and values for the chart
        $labels = $productsData->pluck('label')->toArray();
        $values = $productsData->pluck('value')->toArray();

        // Create the dataset for the pie chart
        $this->chart->dataset('Product Contract Value Split', 'pie', $values)
            ->backgroundColor([
                '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40',
            ])
            ->color([
                '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40',
            ]);

        // Set labels on the chart
        $this->chart->labels($labels);

        // Return chart data as JSON
        return response()->json($this->chart);
    }
}