<?php

namespace App\Services\Dashboard;

use App\Enums\PropertyStatus;
use App\Enums\SalesType;
use App\Enums\StagesOpportunity;
use App\Models\Property;
use App\Repositories\Dashboard\DashboardRepositoryInterface;

class DashboardService
{
    protected $dashboardRepository;

    public function __construct(
        DashboardRepositoryInterface $dashboardRepository,
    ) {
        $this->dashboardRepository = $dashboardRepository;
    }

    public function getKeyReports($filter)
    {
        $project_id = isset($filter['project_id']) ? $filter['project_id'] : null;
        if ($project_id != '0') {
            return [
                'total_customer' => $this->dashboardRepository->countCustomer($filter['fromDate'], $filter['toDate']),
                'total_conversation' => $this->dashboardRepository->countConversation($filter['fromDate'], $filter['toDate']),
                'total_opportunities' => $this->dashboardRepository->countOpportunitiesProject($filter['fromDate'], $filter['toDate'], $project_id),
                'total_leads' => $this->dashboardRepository->countOpportunityStageProject($filter['fromDate'], $filter['toDate'],  StagesOpportunity::LEAD->value(), $project_id),
                'total_prospect' => $this->dashboardRepository->countOpportunityStageProject($filter['fromDate'], $filter['toDate'], StagesOpportunity::PROSPECT->value(),  $project_id),
                'total_presales' => $this->dashboardRepository->countOpportunityStageProject($filter['fromDate'], $filter['toDate'], StagesOpportunity::PRESALE->value(),  $project_id),
                'total_sales' => $this->dashboardRepository->countOpportunityStageProject($filter['fromDate'], $filter['toDate'], StagesOpportunity::SALE->value(),  $project_id),
                'total_delivery' => $this->dashboardRepository->countOpportunityStageProject($filter['fromDate'], $filter['toDate'], StagesOpportunity::DELIVERY->value(),  $project_id),

                'average_closure_time' => $this->dashboardRepository->averageClosureTimeProject($filter['fromDate'], $filter['toDate'], $project_id),
                'total_amount_sale' => $this->dashboardRepository->totalAmountSaleProject($filter['fromDate'], $filter['toDate'], $project_id),
                'count_sales' => $this->dashboardRepository->countSaleProject($filter['fromDate'], $filter['toDate'],  $project_id),
            ];
        } else {
            return [
                'total_customer' => $this->dashboardRepository->countCustomer($filter['fromDate'], $filter['toDate']),
                'total_conversation' => $this->dashboardRepository->countConversation($filter['fromDate'], $filter['toDate']),
                'total_opportunities' => $this->dashboardRepository->countOpportunities($filter['fromDate'], $filter['toDate']),
                'total_leads' => $this->dashboardRepository->countOpportunityStage($filter['fromDate'], $filter['toDate'], StagesOpportunity::LEAD->value()),
                'total_prospect' => $this->dashboardRepository->countOpportunityStage($filter['fromDate'], $filter['toDate'], StagesOpportunity::PROSPECT->value()),
                'total_presales' => $this->dashboardRepository->countOpportunityStage($filter['fromDate'], $filter['toDate'], StagesOpportunity::PRESALE->value()),
                'total_sales' => $this->dashboardRepository->countOpportunityStage($filter['fromDate'], $filter['toDate'], StagesOpportunity::SALE->value()),
                'total_delivery' => $this->dashboardRepository->countOpportunityStage($filter['fromDate'], $filter['toDate'], StagesOpportunity::DELIVERY->value()),

                'average_closure_time' => $this->dashboardRepository->averageClosureTime($filter['fromDate'], $filter['toDate']),
                'total_amount_sale' => $this->dashboardRepository->totalAmountSale($filter['fromDate'], $filter['toDate']),
                'count_sales' => $this->dashboardRepository->countSale($filter['fromDate'], $filter['toDate']),
            ];
        }
    }

    public function getSalesFunnel($filter)
    {
        // Todo: no se para que es esto
        $project_id = isset($filter['project_id']) ? $filter['project_id'] : null;
        if ($project_id != '0') {
            return [
                'total_prospect' => $this->dashboardRepository->countOpportunityStageProject($filter['fromDate'], $filter['toDate'], StagesOpportunity::PROSPECT->value(),  $project_id),
                'total_visit' => $this->dashboardRepository->countActivityVisitProject($filter['fromDate'], $filter['toDate'],  $project_id),
                'total_quote' => $this->dashboardRepository->countQuoteProject($filter['fromDate'], $filter['toDate'],  $project_id),
                'total_presales' => $this->dashboardRepository->countOpportunityStageProject($filter['fromDate'], $filter['toDate'], StagesOpportunity::PRESALE->value(),  $project_id),
                'total_sale' => $this->dashboardRepository->countSaleProject($filter['fromDate'], $filter['toDate'],  $project_id),
            ];
        } else {
            return [
                'total_prospect' => $this->dashboardRepository->countOpportunityStage($filter['fromDate'], $filter['toDate'], StagesOpportunity::PROSPECT->value()),
                'total_visit' => $this->dashboardRepository->countActivityVisit($filter['fromDate'], $filter['toDate']),
                'total_quote' => $this->dashboardRepository->countQuote($filter['fromDate'], $filter['toDate']),
                'total_presales' => $this->dashboardRepository->countOpportunityStage($filter['fromDate'], $filter['toDate'], StagesOpportunity::PRESALE->value()),
                'total_sale' => $this->dashboardRepository->countSale($filter['fromDate'], $filter['toDate']),
            ];
        }
    }

    public function getWeekCustomerSaleQuoteReport()
    {
        $date = now();
        $weeksData = [];

        // Obtener las últimas 4 semanas
        for ($i = 0; $i < 4; $i++) {
            // Calcular el inicio y fin de la semana
            $startOfWeek = $date->copy()->startOfWeek()->subWeeks($i)->format('Y-m-d');
            $endOfWeek = $date->copy()->endOfWeek()->subWeeks($i)->format('Y-m-d');

            // Obtener los datos de la semana
            $weekData = [
                'week' => "$startOfWeek to $endOfWeek",
                'total_customer' => $this->dashboardRepository->countCustomer($startOfWeek, $endOfWeek),
                'total_quote' => $this->dashboardRepository->countQuote($startOfWeek, $endOfWeek),
                'total_sale' => $this->dashboardRepository->countSale($startOfWeek, $endOfWeek),
            ];
            // Agregar los datos de la semana al array
            $weeksData[] = $weekData;
        }

        return $weeksData;
    }

    public function getMonthlyCustomerSaleQuoteReport()
    {
        $date = now(); // Fecha actual
        $monthsData = [];

        // Obtener los últimos 3 meses
        for ($i = 0; $i < 3; $i++) {
            // Calcular el inicio y fin del mes
            $startOfMonth = $date->copy()->startOfMonth()->subMonths($i)->format('Y-m-d');
            $endOfMonth = $date->copy()->endOfMonth()->subMonths($i)->format('Y-m-d');

            // Obtener los datos del mes
            $monthData = [
                'month' => $date->copy()->subMonths($i)->format('F Y'), // Ejemplo: "January 2024"
                'total_customer' => $this->dashboardRepository->countCustomer($startOfMonth, $endOfMonth),
                'total_quote' => $this->dashboardRepository->countQuote($startOfMonth, $endOfMonth),
                'total_sale' => $this->dashboardRepository->countSale($startOfMonth, $endOfMonth),
            ];

            // Agregar los datos del mes al array
            $monthsData[] = $monthData;
        }

        return $monthsData;
    }

    public function getSellersReport($filter)
    {
        //todo : falta el estado delivery.
        $project_id = isset($filter['project_id']) ? $filter['project_id'] : null;
        if ($project_id != '0') {
            return [
                'total_prospect' => $this->dashboardRepository->sellerReportProject($filter['fromDate'], $filter['toDate'], $project_id),
            ];
        } else {
            return [
                'total_prospect' => $this->dashboardRepository->sellerReport($filter['fromDate'], $filter['toDate']),
            ];
        }
    }

    public function getPropertyReport($filter)
    {
        $project_id = isset($filter['project_id']) ? $filter['project_id'] : null;
        if ($project_id != '0') {
            $totalproperties = Property::where('project_id', $project_id)->count();
            $totalpropertysale = $this->dashboardRepository->countSaleProject($filter['fromDate'], $filter['toDate'],  $project_id);
            $totalpropertydelivery = $this->dashboardRepository->countSaleStateProject($filter['fromDate'], $filter['toDate'], SalesType::DELIVERY->name, $project_id);

            return [
                // 'total_property' => $this->dashboardRepository->totalpropertyProject($filter['fromDate'], $filter['toDate'], $project_id),
                'total_property' => $totalproperties,
                'average_property_price' => $this->dashboardRepository->propertyAveragePriceProject($filter['fromDate'], $filter['toDate'], $project_id),
                // 'total_property_available' => $this->dashboardRepository->propertyStatusProject($filter['fromDate'], $filter['toDate'], PropertyStatus::AVAILABLE->name, $project_id),
                'total_property_available' =>  $totalproperties - $totalpropertysale - $totalpropertydelivery,
                // 'total_property_sale__' => $this->dashboardRepository->propertyStatusProject($filter['fromDate'], $filter['toDate'], PropertyStatus::SALE->name, $project_id),
                // 'total_property_delivery__' => $this->dashboardRepository->propertyStatusProject($filter['fromDate'], $filter['toDate'], PropertyStatus::DELIVERED->name, $project_id),
                'total_property_sale' => $totalpropertysale,
                'total_property_delivery' => $totalpropertydelivery,
            ];
        } else {
            $totalproperties = Property::count();
            $totalpropertysale = $this->dashboardRepository->countSale($filter['fromDate'], $filter['toDate']);
            $totalpropertydelivery = $this->dashboardRepository->countSaleState($filter['fromDate'], $filter['toDate'], SalesType::DELIVERY->name);

            return [
                // 'total_property' => $this->dashboardRepository->totalproperty($filter['fromDate'], $filter['toDate']),
                'total_property' => $totalproperties,
                'average_property_price' => $this->dashboardRepository->propertyAveragePrice($filter['fromDate'], $filter['toDate']),
                // 'total_property_available' => $this->dashboardRepository->propertyStatus($filter['fromDate'], $filter['toDate'], PropertyStatus::AVAILABLE->name),
                'total_property_available' =>  $totalproperties - $totalpropertysale - $totalpropertydelivery,

                // 'total_property_sale__' => $this->dashboardRepository->propertyStatus($filter['fromDate'], PropertyStatus::SALE->name, $filter['toDate']),
                // 'total_property_delivery__' => $this->dashboardRepository->propertyStatus($filter['fromDate'], PropertyStatus::DELIVERED->name, $filter['toDate']),
                'total_property_sale' => $totalpropertysale,
                'total_property_delivery' => $totalpropertydelivery,
            ];
        }
    }

    public function getPropertyTypeReport($filter, $type_id)
    {
        $project_id = isset($filter['project_id']) ? $filter['project_id'] : null;
        if ($project_id != '0') {
            return [
                'total_property' => $this->dashboardRepository->totalpropertyTypeProject($project_id, $type_id),
                'total_property_available' => $this->dashboardRepository->propertyTypeStatusProject(PropertyStatus::AVAILABLE->name, $project_id, $type_id),
                'total_property_sale' => $this->dashboardRepository->propertyTypeStatusProject(PropertyStatus::SALE->name, $project_id, $type_id),
                'total_property_presale' => $this->dashboardRepository->propertyTypeStatusProject(PropertyStatus::PRESALE->name, $project_id, $type_id),
            ];
        } else {
            return [
                'total_property' => $this->dashboardRepository->totalpropertyType($type_id),
                'total_property_available' => $this->dashboardRepository->propertyTypeStatus(PropertyStatus::AVAILABLE->name,  $type_id),
                'total_property_sale' => $this->dashboardRepository->propertyTypeStatus(PropertyStatus::SALE->name,  $type_id),
                'total_property_presale' => $this->dashboardRepository->propertyTypeStatus(PropertyStatus::PRESALE->name,  $type_id),
            ];
        }
    }

    public function getQuoteReport($filter)
    {
        $project_id = isset($filter['project_id']) ? $filter['project_id'] : null;
        if ($project_id != '0') {
            return [
                'total_quote' => $this->dashboardRepository->countQuoteProject($filter['fromDate'], $filter['toDate'],  $project_id),
                'total_quote_approved_customer' => $this->dashboardRepository->countQuoteProjectApproved($filter['fromDate'], $filter['toDate'], 'status_customer', $project_id),
                'total_quote_approved_management' => $this->dashboardRepository->countQuoteProjectApproved($filter['fromDate'], $filter['toDate'],  'status', $project_id),
            ];
        } else {
            return [
                'total_quote' => $this->dashboardRepository->countQuote($filter['fromDate'], $filter['toDate']),
                'total_quote_approved_customer' => $this->dashboardRepository->countQuoteApproved($filter['fromDate'], $filter['toDate'],  'status_customer'),
                'total_quote_approved_management' => $this->dashboardRepository->countQuoteApproved($filter['fromDate'], $filter['toDate'],   'status'),
            ];
        }
    }

    public function getActivityReport($filter)
    {
        return [
            'total_activity' => $this->dashboardRepository->countActivity($filter['fromDate'], $filter['toDate']),
            'total_activity_visit' => $this->dashboardRepository->countActivityType($filter['fromDate'], $filter['toDate'],  1),
            'total_activity_call' => $this->dashboardRepository->countActivityType($filter['fromDate'], $filter['toDate'],  2),
            'total_activity_quote' => $this->dashboardRepository->countActivityType($filter['fromDate'], $filter['toDate'],  3),
            'total_activity_other' => $this->dashboardRepository->countActivityType($filter['fromDate'], $filter['toDate'],  4),

            'total_activity_pending' => $this->dashboardRepository->countActivityStage($filter['fromDate'], $filter['toDate'],  'PENDING'),
            'total_activity_complet' => $this->dashboardRepository->countActivityStage($filter['fromDate'], $filter['toDate'],  'COMPLETED'),
            'total_activity_cancell' => $this->dashboardRepository->countActivityStage($filter['fromDate'], $filter['toDate'],  'CANCELLED'),
            'total_activity_discard' => $this->dashboardRepository->countActivityStage($filter['fromDate'], $filter['toDate'],  'DISCARD'),
        ];
    }
}
