<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Models\Prescription;
use App\Models\Product;
use App\Models\Sale;
use App\Models\Supplier;
use Carbon\Carbon;

class ReportController extends Controller
{
    private function getStartDate($period)
    {
        return match ($period) {
            'week' => Carbon::now()->subWeek(),
            'month' => Carbon::now()->subMonth(),
            'quarter' => Carbon::now()->subQuarter(),
            'year' => Carbon::now()->subYear(),
            default => Carbon::now()->subMonth(),
        };
    }

    public function sales()
    {
        $period = request('period', 'month');
        $startDate = $this->getStartDate($period);
        $endDate = Carbon::now();

        $salesData = Sale::whereBetween('created_at', [$startDate, $endDate])
            ->selectRaw('DATE(created_at) as date, COUNT(*) as count, SUM(total_amount) as total')
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        $topProducts = Sale::join('sale_items', 'sales.id', '=', 'sale_items.sale_id')
            ->join('products', 'sale_items.product_id', '=', 'products.id')
            ->whereBetween('sales.created_at', [$startDate, $endDate])
            ->selectRaw('products.name, SUM(sale_items.quantity) as total_quantity, SUM(sale_items.total_price) as total_revenue')
            ->groupBy('products.id', 'products.name')
            ->orderByDesc('total_revenue')
            ->limit(10)
            ->get();

        $topCustomers = Sale::join('customers', 'sales.customer_id', '=', 'customers.id')
            ->whereBetween('sales.created_at', [$startDate, $endDate])
            ->selectRaw('customers.name, COUNT(*) as purchase_count, SUM(sales.total_amount) as total_spent')
            ->groupBy('customers.id', 'customers.name')
            ->orderByDesc('total_spent')
            ->limit(10)
            ->get();

        return view('dashboard.reports.sales', compact('salesData', 'topProducts', 'topCustomers', 'period'));
    }

    public function stock()
    {
        $products = Product::with(['category', 'saleUnit'])
            ->orderBy('current_stock', 'asc')
            ->get();

        $lowStockProducts = $products->where('current_stock', '<=', 10);
        $outOfStockProducts = $products->where('current_stock', 0);
        $expiringProducts = Product::whereNotNull('expiry_date')
            ->where('expiry_date', '<=', Carbon::now()->addMonths(3))
            ->orderBy('expiry_date')
            ->get();

        $stockValue = $products->sum(function ($product) {
            return ($product->current_stock ?? 0) * ($product->purchase_price ?? 0);
        });

        return view('dashboard.reports.stock', compact(
            'products',
            'lowStockProducts',
            'outOfStockProducts',
            'expiringProducts',
            'stockValue'
        ));
    }

    public function prescriptions()
    {
        $period = request('period', 'month');
        $startDate = $this->getStartDate($period);
        $endDate = Carbon::now();

        $prescriptionsData = Prescription::whereBetween('created_at', [$startDate, $endDate])
            ->selectRaw('DATE(created_at) as date, COUNT(*) as count')
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        $prescriptionsByStatus = Prescription::whereBetween('created_at', [$startDate, $endDate])
            ->selectRaw('status, COUNT(*) as count')
            ->groupBy('status')
            ->get();

        // Note: prescription_items table removed - this query is disabled
        $topPrescribedProducts = collect([]);

        return view('dashboard.reports.prescriptions', compact(
            'prescriptionsData',
            'prescriptionsByStatus',
            'topPrescribedProducts',
            'period'
        ));
    }

    public function general()
    {
        $period = request('period', 'month');
        $startDate = $this->getStartDate($period);
        $endDate = Carbon::now();

        // General statistics
        $stats = [
            'total_sales' => Sale::whereBetween('created_at', [$startDate, $endDate])
                ->count(),
            'total_revenue' => Sale::whereBetween('created_at', [$startDate, $endDate])
                ->sum('total_amount'),
            'total_customers' => Customer::count(),
            'total_products' => Product::count(),
            'total_suppliers' => Supplier::count(),
            'active_prescriptions' => Prescription::where('status', 'active')
                ->count(),
        ];

        // Monthly trends
        $monthlyTrends = Sale::whereBetween('created_at', [$startDate, $endDate])
            ->selectRaw('YEAR(created_at) as year, MONTH(created_at) as month, COUNT(*) as sales_count, SUM(total_amount) as revenue')
            ->groupBy('year', 'month')
            ->orderBy('year')
            ->orderBy('month')
            ->get();

        return view('dashboard.reports.general', compact('stats', 'monthlyTrends', 'period'));
    }
}
