<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\DocumentHeader;
use App\Models\DocumentLine;
use App\Models\CompanySettings;
use PDF;
use Carbon\Carbon;

class SalesAnalysisController extends Controller
{
    public function index()
    {
        $currentDate = Carbon::now()->format('Y-m-d');
        
        return view('reports.sales-analysis', compact('currentDate'));
    }

    public function generate(Request $request)
    {
        $request->validate([
            'date_from' => 'required|date',
            'date_to' => 'required|date|after_or_equal:date_from',
        ]);

        $dateFrom = $request->date_from;
        $dateTo = $request->date_to;
        $company = CompanySettings::first();

        // Get processed sales documents (invoices, sales orders) within date range
        $documentHeaders = DocumentHeader::whereIn('type', ['invoice', 'sales_order'])
            ->where('status', 'processed')
            ->whereBetween('document_date', [$dateFrom, $dateTo])
            ->orderBy('document_date')
            ->get();

        $salesData = [];
        $grandTotalAmount = 0;
        $grandTotalCost = 0;
        $grandTotalProfit = 0;
        
        foreach ($documentHeaders as $header) {
            foreach ($header->lines as $line) {
                if ($line->module === 'ST' && $line->item_id) { // Only stock items
                    $amount = $line->confirmed_quantity * $line->price;
                    $cost = $line->confirmed_quantity * ($line->item->standard_cost ?? 0);
                    $grossProfit = $amount - $cost;
                    
                    $salesData[] = [
                        'date' => $header->document_date,
                        'reference' => $header->document_number,
                        'amount' => $amount,
                        'cost' => $cost,
                        'gross_profit' => $grossProfit
                    ];
                    
                    $grandTotalAmount += $amount;
                    $grandTotalCost += $cost;
                    $grandTotalProfit += $grossProfit;
                }
            }
        }

        return view('reports.sales-analysis', compact(
            'salesData',
            'dateFrom',
            'dateTo',
            'company',
            'grandTotalAmount',
            'grandTotalCost',
            'grandTotalProfit'
        ));
    }

    public function downloadPdf(Request $request)
    {
        $request->validate([
            'date_from' => 'required|date',
            'date_to' => 'required|date|after_or_equal:date_from',
        ]);

        $dateFrom = $request->date_from;
        $dateTo = $request->date_to;
        $company = CompanySettings::first();

        // Get processed sales documents (invoices, sales orders) within date range
        $documentHeaders = DocumentHeader::whereIn('type', ['invoice', 'sales_order'])
            ->where('status', 'processed')
            ->whereBetween('document_date', [$dateFrom, $dateTo])
            ->orderBy('document_date')
            ->get();

        $salesData = [];
        $grandTotalAmount = 0;
        $grandTotalCost = 0;
        $grandTotalProfit = 0;
        
        foreach ($documentHeaders as $header) {
            foreach ($header->lines as $line) {
                if ($line->module === 'ST' && $line->item_id) { // Only stock items
                    $amount = $line->confirmed_quantity * $line->price;
                    $cost = $line->confirmed_quantity * ($line->item->standard_cost ?? 0);
                    $grossProfit = $amount - $cost;
                    
                    $salesData[] = [
                        'date' => $header->document_date,
                        'reference' => $header->document_number,
                        'amount' => $amount,
                        'cost' => $cost,
                        'gross_profit' => $grossProfit
                    ];
                    
                    $grandTotalAmount += $amount;
                    $grandTotalCost += $cost;
                    $grandTotalProfit += $grossProfit;
                }
            }
        }

        $pdf = PDF::loadView('reports.sales-analysis-pdf', compact(
            'salesData',
            'dateFrom',
            'dateTo',
            'company',
            'grandTotalAmount',
            'grandTotalCost',
            'grandTotalProfit'
        ));

        return $pdf->download('sales-analysis-report.pdf');
    }
}