<?php

$dates = [];
$clicks = [];
$uclicks = [];
$leads = [];
$sales = [];

$visits = ___salesloo('clicks');
$orders = ___salesloo('sales');

foreach (___salesloo('period') as $key => $value) {
    $dates[] = $value->format('d-M');

    $date_key = $value->format('Y-m-d');
    if (isset($visits[$date_key])) {
        $clicks[] = $visits[$date_key]->clicks;
        $uclicks[] = $visits[$date_key]->uclicks;
    } else {
        $clicks[] = 0;
        $uclicks[] = 0;
    }

    if (isset($orders[$date_key])) {
        $leads[] = $orders[$date_key]->leads;
        $sales[] = $orders[$date_key]->sales;
    } else {
        $leads[] = 0;
        $sales[] = 0;
    }
}


$data = [
    'labels' => $dates,
    'datasets' => [
        [
            'label' => 'Clicks',
            'backgroundColor' => 'rgba(255, 255, 255, 0.1)',
            'borderColor' => 'rgba(255, 255, 255, 1)',
            'pointBackgroundColor' => 'rgba(255, 255, 255, 1)',
            'data' => $clicks,
        ],
        [
            'label' => 'Unique Clicks',
            'backgroundColor' => 'rgba(252, 165, 165, 0.5)',
            'borderColor' => 'rgba(252, 165, 165, 1)',
            'pointBackgroundColor' => 'rgba(252, 165, 165, 1)',
            'data' => $uclicks,
        ],
        [
            'label' => 'Lead',
            'backgroundColor' => 'rgba(25, 181, 254, 0.5)',
            'borderColor' => 'rgba(25, 181, 254, 1)',
            'pointBackgroundColor' => 'rgba(25, 181, 254, 1)',
            'data' => $leads,
        ],
        [
            'label' => 'Sales',
            'backgroundColor' => 'rgba(16, 185, 129, 0.5)',
            'borderColor' => 'rgba(16, 185, 129, 1)',
            'pointBackgroundColor' => 'rgba(16, 185, 129, 1)',
            'data' => $sales,
        ],
    ]
];

?>
<div class="" x-data="<?php echo salesloo_make_json($data); ?>" x-init="$chartline($refs.chart, labels, datasets)">
    <div class="rounded shadow-sm overflow-hidden w-full md:flex">
        <div class="w-full bg-blue-500 text-white p-5 rounded-lg">
            <canvas x-ref="chart" class="w-full text-white"></canvas>
        </div>
    </div>
</div>