<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Models\EmployeePayment;
use App\Models\Expense;
use App\Models\Purchase;
use App\Models\Sale;
use App\Models\Shareholder;
use App\Models\Vendor;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;

class ReportController extends Controller
{
    public function dailyIncome(Request $request)
    {
        $date = $request->input('date', today()->toDateString());

        $sales = Sale::whereDate('sale_date', $date)->sum('amount');
        $purchases = Purchase::whereDate('purchase_date', $date)->sum('cost');
        $expenses = Expense::whereDate('expense_date', $date)->sum('amount');
        $customers = Customer::where('current_due', '>', 0)->get();

        return view('reports.daily', compact('date', 'sales', 'purchases', 'expenses', 'customers'));
    }

    public function dailyPdf(Request $request)
    {
        $date = $request->input('date', today()->toDateString());

        $sales = Sale::whereDate('sale_date', $date)->sum('amount');
        $purchases = Purchase::whereDate('purchase_date', $date)->sum('cost');
        $expenses = Expense::whereDate('expense_date', $date)->sum('amount');
        $customers = Customer::where('current_due', '>', 0)->get();

        $pdf = Pdf::loadView('reports.pdf.daily', compact('date', 'sales', 'purchases', 'expenses', 'customers'));

        return $pdf->download("daily-income-report-{$date}.pdf");
    }

    public function monthlyProfitLoss(Request $request)
    {
        $month = $request->input('month', today()->format('Y-m'));
        $from = substr($month, 0, 7) . '-01';
        $to = date('Y-m-t', strtotime($from));

        $sales = Sale::whereBetween('sale_date', [$from, $to])->sum('amount');
        $purchases = Purchase::whereBetween('purchase_date', [$from, $to])->sum('cost');
        $expenses = Expense::whereBetween('expense_date', [$from, $to])->sum('amount');
        $profit = $sales - $purchases - $expenses;

        return view('reports.monthly', compact('month', 'sales', 'purchases', 'expenses', 'profit'));
    }

    public function monthlyProfitLossPdf(Request $request)
    {
        $month = $request->input('month', today()->format('Y-m'));
        $from = substr($month, 0, 7) . '-01';
        $to = date('Y-m-t', strtotime($from));

        $sales = Sale::whereBetween('sale_date', [$from, $to])->sum('amount');
        $purchases = Purchase::whereBetween('purchase_date', [$from, $to])->sum('cost');
        $expenses = Expense::whereBetween('expense_date', [$from, $to])->sum('amount');
        $profit = $sales - $purchases - $expenses;

        $pdf = Pdf::loadView('reports.pdf.monthly', compact('month', 'sales', 'purchases', 'expenses', 'profit'));

        return $pdf->download("monthly-profit-loss-{$month}.pdf");
    }

    public function vendorReport(Request $request)
    {
        $from = $request->input('from', today()->startOfMonth()->toDateString());
        $to   = $request->input('to', today()->toDateString());

        $vendors = Vendor::withCount('purchases')
            ->with(['purchases' => fn($q) => $q->whereBetween('purchase_date', [$from, $to])])
            ->orderBy('name')
            ->get()
            ->map(function ($vendor) use ($from, $to) {
                $vendor->period_total    = $vendor->purchases->sum('cost');
                $vendor->period_due      = $vendor->purchases->where('payment_type', 'due')->sum('cost');
                $vendor->period_cash     = $vendor->purchases->where('payment_type', 'cash')->sum('cost');
                return $vendor;
            });

        return view('reports.vendor', compact('vendors', 'from', 'to'));
    }

    public function shareholderReport()
    {
        $shareholders = Shareholder::with(['transactions' => fn($q) => $q->orderBy('transaction_date')])
            ->orderBy('name')
            ->get();

        $totals = $this->buildShareholderTotals($shareholders);

        return view('reports.shareholder', compact('shareholders', 'totals'));
    }

    public function shareholderAllPdf()
    {
        $shareholders = Shareholder::with(['transactions' => fn($q) => $q->orderBy('transaction_date')])
            ->orderBy('name')
            ->get();

        $totals = $this->buildShareholderTotals($shareholders);

        $pdf = Pdf::loadView('reports.pdf.shareholder_all', compact('shareholders', 'totals'))
            ->setPaper('a4', 'landscape');

        return $pdf->download('shareholder-report-all.pdf');
    }

    public function shareholderOnePdf(Shareholder $shareholder)
    {
        $shareholder->load(['transactions' => fn($q) => $q->orderBy('transaction_date')]);

        $pdf = Pdf::loadView('reports.pdf.shareholder_one', compact('shareholder'));

        return $pdf->download('shareholder-report-' . str()->slug($shareholder->name) . '.pdf');
    }

    private function buildShareholderTotals($shareholders): array
    {
        $totals = [
            'investment'        => $shareholders->sum('total_investment'),
            'withdrawal'        => $shareholders->sum('total_withdrawal'),
            'profit'            => $shareholders->sum('total_profit'),
            'profit_withdrawal' => $shareholders->sum('total_profit_withdrawal'),
        ];
        $totals['net_investment'] = $totals['investment'] - $totals['withdrawal'];
        $totals['net_profit']     = $totals['profit']     - $totals['profit_withdrawal'];

        return $totals;
    }
}
