<?php

namespace App\Services\Admin\Financial;

use App\Models\ConsignmentItem;
use App\Models\Statistic;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Illuminate\Support\Facades\DB;
use Morilog\Jalali\Jalalian;

class SalesChartsService
{
    /** get total sales chart */
    public function getTotalSalesChart($subDays, $flag = 'total')
    {
        // past {$subDays} days period
        $period = CarbonPeriod::create(Carbon::now()->subDays($subDays), Carbon::now());

        // chart date labels
        $dates = [];

        // charts data
        $sales = [];
        $counts = [];

        // Iterate over the period
        foreach ($period as $date) {
            // date labels
            $dates[] = Jalalian::forge($date)->format('m-d');

            // charts sale data
            $sale = 0;
            if ($flag == 'main') {
                $sale = ConsignmentItem::selectRaw("SUM(shop_share) as total")->where(function ($query) {
                    $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
                })->whereDate('created_at', $date)->first()->total;
                $sale = $sale != null ? $sale : 0;
            } else if ($flag == 'sellers') {
                $sale = ConsignmentItem::selectRaw("SUM(seller_share) as total")->where('store_id', '!=', null)->where(function ($query) {
                    $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
                })->whereDate('created_at', $date)->first()->total;
                $sale = $sale != null ? $sale : 0;
            } else if ($flag == 'affiliate') {
                $sale = ConsignmentItem::selectRaw("SUM(affiliate_share) as total")->where('affiliate', '!=', null)->where(function ($query) {
                    $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
                })->whereDate('created_at', $date)->first()->total;
                $sale = $sale != null ? $sale : 0;
            } else {
                $sale = ConsignmentItem::selectRaw("SUM(price * count) as total")->where(function ($query) {
                    $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
                })->whereDate('created_at', $date)->first()->total;
                $sale = $sale != null ? $sale : 0;
            }
            $sales[] = $sale;

            // chart sale count data
            $count = 0;

            if ($flag == 'main') {
                $count = ConsignmentItem::selectRaw("SUM(count) as total")->where(function ($query) {
                    $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
                })->whereDate('created_at', $date)->where('shop_share', '>', 0)->first()->total;
                $count = $count != null ? $count : 0;
            } else if ($flag == 'sellers') {
                $count = ConsignmentItem::selectRaw("SUM(count) as total")->where(function ($query) {
                    $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
                })->whereDate('created_at', $date)->where('seller_share', '>', 0)->first()->total;
                $count = $count != null ? $count : 0;
            } else if ($flag == 'affiliate') {
                $count = ConsignmentItem::selectRaw("SUM(count) as total")->where(function ($query) {
                    $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
                })->whereDate('created_at', $date)->where('affiliate_share', '>', 0)->first()->total;
                $count = $count != null ? $count : 0;
            } else {
                $count = ConsignmentItem::selectRaw("SUM(count) as total")->where(function ($query) {
                    $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
                })->whereDate('created_at', $date)->first()->total;
                $count = $count != null ? $count : 0;
            }
            $counts[] = $count;
        }

        // sales counts
        $today = 0;
        if ($flag == 'main') {
            $today = ConsignmentItem::selectRaw("SUM(shop_share) as total")->where(function ($query) {
                $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
            })->whereDate('created_at', '>=', Carbon::now()->subDay(1))->first();
        } else if ($flag == 'sellers') {
            $today = ConsignmentItem::selectRaw("SUM(seller_share) as total")->where(function ($query) {
                $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
            })->whereDate('created_at', '>=', Carbon::now()->subDay(1))->first();
        } else if ($flag == 'affiliate') {
            $today = ConsignmentItem::selectRaw("SUM(affiliate_share) as total")->where(function ($query) {
                $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
            })->whereDate('created_at', '>=', Carbon::now()->subDay(1))->first();
        } else {
            $today = ConsignmentItem::selectRaw("SUM(price * count) as total")->where(function ($query) {
                $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
            })->whereDate('created_at', '>=', Carbon::now()->subDay(1))->first();
        }

        $month = 0;
        if ($flag == 'main') {
            $month = ConsignmentItem::selectRaw("SUM(shop_share) as total")->where(function ($query) {
                $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
            })->whereDate('created_at', '>=', Carbon::now()->subDay(30))->first();
        } else if ($flag == 'sellers') {
            $month = ConsignmentItem::selectRaw("SUM(seller_share) as total")->where(function ($query) {
                $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
            })->whereDate('created_at', '>=', Carbon::now()->subDay(30))->first();
        } else if ($flag == 'affiliate') {
            $month = ConsignmentItem::selectRaw("SUM(affiliate_share) as total")->where(function ($query) {
                $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
            })->whereDate('created_at', '>=', Carbon::now()->subDay(30))->first();
        } else {
            $month = ConsignmentItem::selectRaw("SUM(price * count) as total")->where(function ($query) {
                $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
            })->whereDate('created_at', '>=', Carbon::now()->subDay(30))->first();
        }

        $total = 0;
        if ($flag == 'main') {
            $total = ConsignmentItem::selectRaw("SUM(shop_share) as total")->where(function ($query) {
                $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
            })->first();
        } else if ($flag == 'sellers') {
            $total = ConsignmentItem::selectRaw("SUM(seller_share) as total")->where(function ($query) {
                $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
            })->first();
        } else if ($flag == 'affiliate') {
            $total = ConsignmentItem::selectRaw("SUM(affiliate_share) as total")->where(function ($query) {
                $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
            })->first();
        } else {
            $total = ConsignmentItem::selectRaw("SUM(price * count) as total")->where(function ($query) {
                $query->orWhere('status', 'sent')->orWhere('status', 'delivered');
            })->first();
        }


        return [
            'dates' => $dates,
            'chart' => [
                'sales' => $sales,
                'count' => $counts,
            ],
            'counts' => [
                'today' => $today->total != null ? $today->total : 0,
                'month' => $month->total != null ? $month->total : 0,
                'total' => $total->total != null ? $total->total : 0,
            ]
        ];
    }

    /**
     * get main financial statistics
     */
    public function getMainStatistics()
    {
        $totalSales = ConsignmentItem::selectRaw("SUM(price * count) as total")
            ->where(function ($query) {
                $query->where('status', 'sent')->orWhere('status', 'delivered');
            })->first();

        // main store sales
        $mainStoreSales = ConsignmentItem::selectRaw("SUM(shop_share) as total")
            ->where(function ($query) {
                $query->where('status', 'sent')->orWhere('status', 'delivered');
            })->first();

        // sellers sales
        $sellersSales = ConsignmentItem::selectRaw("SUM(seller_share) as total")
            ->where('store_id', '!=', null)
            ->where(function ($query) {
                $query->where('status', 'sent')->orWhere('status', 'delivered');
            })->first();

        // affiliate sales
        $affiliateSales = ConsignmentItem::selectRaw("SUM(affiliate_share) as total")
            ->where('affiliate', '!=', null)
            ->where(function ($query) {
                $query->where('status', 'sent')->orWhere('status', 'delivered');
            })->first();

        // جمع کل تخفیف‌ها
        $discounts = ConsignmentItem::with('consignment.order')
            ->get()
            ->pluck('consignment.order.discount')
            ->filter()
            ->unique() // هر سفارش فقط یکبار حساب شود
            ->map(function ($value) {
                $discount = @unserialize($value);
                return is_array($discount) && isset($discount['amount']) ? $discount['amount'] : 0;
            })
            ->sum();

        return [
            'all' => $totalSales->total != null ? (int) $totalSales->total : 0,
            'main' => $mainStoreSales->total != null ? (int) $mainStoreSales->total : 0,
            'sellers' => $sellersSales->total != null ? (int) $sellersSales->total : 0,
            'affiliates' => $affiliateSales->total != null ? (int) $affiliateSales->total : 0,
            'discounts' => (int) $discounts,
        ];
    }
}
