<?php

namespace App\Http\Controllers;

use App\Models\Sale;
use App\Models\Customer;
use Illuminate\Http\Request;

class SaleController extends Controller
{
    public function index(Request $request)
{
    $query = Sale::with('customer');
    
    // Apply date filters
    if ($request->start_date) {
        $query->whereDate('created_at', '>=', $request->start_date);
    }
    
    if ($request->end_date) {
        $query->whereDate('created_at', '<=', $request->end_date);
    }
    
    // Apply status filter
    if ($request->payment_status) {
        $query->where('payment_status', $request->payment_status);
    }
    
    $sales = $query->orderBy('created_at', 'desc')->paginate(15);
    
    // Calculate totals for the filtered data
    $totalSubtotal = $query->sum('subtotal');
    $totalDiscount = $query->sum('discount');
    $totalTax = $query->sum('tax_amount');
    $totalSales = $query->sum('total');
    $totalDue = $query->where('payment_status', '!=', 'paid')->sum('total');
    
    // Get filter values for the view
    $startDate = $request->start_date;
    $endDate = $request->end_date;
    
    return view('sales.index', compact(
        'sales', 
        'totalSubtotal', 
        'totalDiscount', 
        'totalTax', 
        'totalSales',
        'totalDue',
        'startDate',
        'endDate'
    ));
}

    public function show(Sale $sale)
    {
        $sale->load('items.product', 'customer', 'user');
        return view('sales.show', compact('sale'));
    }

    public function invoice(Sale $sale)
    {
        $sale->load('items.product', 'customer', 'user');
        return view('sales.invoice', compact('sale'));
    }

    public function sendReceipt(Sale $sale)
    {
        // Send receipt via email
        return redirect()->back()->with('success', 'Receipt sent successfully!');
    }
    public function sales(Request $request)
{
    $startDate = $request->get('start_date', date('Y-m-d', strtotime('first day of this month')));
    $endDate = $request->get('end_date', date('Y-m-d'));
    $paymentStatus = $request->get('payment_status');
    
    $query = Sale::with('customer')
        ->whereBetween('created_at', [$startDate . ' 00:00:00', $endDate . ' 23:59:59']);
    
    if ($paymentStatus) {
        $query->where('payment_status', $paymentStatus);
    }
    
    $sales = $query->orderBy('created_at', 'desc')->get();
    
    // Calculate totals
    $totalSubtotal = $sales->sum('subtotal');
    $totalDiscount = $sales->sum('discount');
    $totalTax = $sales->sum('tax_amount');
    $totalSales = $sales->sum('total');
    $totalDue = $sales->where('payment_status', '!=', 'paid')->sum('total');
    
    // Prepare chart data
    $chartData = $this->getSalesChartData($startDate, $endDate, $paymentStatus);
    
    return view('reports.sales', compact(
        'sales', 
        'startDate', 
        'endDate',
        'totalSubtotal',
        'totalDiscount', 
        'totalTax', 
        'totalSales',
        'totalDue',
        'chartData'
    ));
}

private function getSalesChartData($startDate, $endDate, $paymentStatus = null)
{
    $dates = [];
    $values = [];
    
    $currentDate = strtotime($startDate);
    $endDateTimestamp = strtotime($endDate);
    
    while ($currentDate <= $endDateTimestamp) {
        $date = date('Y-m-d', $currentDate);
        $dates[] = date('M d', $currentDate);
        
        $query = Sale::whereDate('created_at', $date);
        if ($paymentStatus) {
            $query->where('payment_status', $paymentStatus);
        }
        $values[] = $query->sum('total');
        
        $currentDate = strtotime('+1 day', $currentDate);
    }
    
    return ['labels' => $dates, 'values' => $values];
}
}