<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\EmployeeAdvance;
use App\Models\EmployeeLedger;
use App\Models\Payroll;
use App\Models\PayrollItem;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;

class HrPdfController extends Controller
{
    public function payslip($payrollId, $itemId)
    {
        $payroll = Payroll::where('user_id', auth()->id())
            ->findOrFail($payrollId);

        $item = PayrollItem::where('user_id', auth()->id())
            ->where('payroll_id', $payroll->id)
            ->with(['employee.designation'])
            ->findOrFail($itemId);

        $data = [
            'payroll'  => $payroll,
            'item'     => $item,
            'employee' => $item->employee,
        ];

        $pdf = Pdf::loadView('user.hr.pdf.payslip', $data)
            ->setPaper('a4', 'portrait');

        $fileName = 'payslip-' .
            ($item->employee->employee_code ?? 'employee') . '-' .
            sprintf('%02d-%04d', $payroll->payroll_month, $payroll->payroll_year) .
            '.pdf';

        return $pdf->download($fileName);
    }

    public function employeeLedger(Request $request, $employeeId)
    {
        $employee = Employee::where('user_id', auth()->id())
            ->with(['designation', 'currentSalaryStructure'])
            ->findOrFail($employeeId);

        $query = EmployeeLedger::where('user_id', auth()->id())
            ->where('employee_id', $employee->id)
            ->orderBy('entry_date')
            ->orderBy('id');

        if ($request->filled('type')) {
            $query->where('type', $request->type);
        }

        if ($request->filled('date_from')) {
            $query->whereDate('entry_date', '>=', $request->date_from);
        }

        if ($request->filled('date_to')) {
            $query->whereDate('entry_date', '<=', $request->date_to);
        }

        $entries = $query->get();

        $latestBalanceRow = EmployeeLedger::where('user_id', auth()->id())
            ->where('employee_id', $employee->id)
            ->orderByDesc('entry_date')
            ->orderByDesc('id')
            ->first();

        $summary = [
            'total_debit' => (float) EmployeeLedger::where('user_id', auth()->id())
                ->where('employee_id', $employee->id)
                ->sum('debit'),

            'total_credit' => (float) EmployeeLedger::where('user_id', auth()->id())
                ->where('employee_id', $employee->id)
                ->sum('credit'),

            'balance' => (float) ($latestBalanceRow->balance ?? 0),

            'outstanding_advance' => (float) EmployeeAdvance::where('user_id', auth()->id())
                ->where('employee_id', $employee->id)
                ->whereIn('status', ['active', 'partial_adjusted'])
                ->sum('remaining_amount'),
        ];

        $data = [
            'employee' => $employee,
            'entries'  => $entries,
            'summary'  => $summary,
            'filters'  => [
                'type' => $request->type,
                'date_from' => $request->date_from,
                'date_to' => $request->date_to,
            ],
        ];

        $pdf = Pdf::loadView('user.hr.pdf.employee-ledger', $data)
            ->setPaper('a4', 'landscape');

        return $pdf->download('employee-ledger-' . ($employee->employee_code ?? 'employee') . '.pdf');
    }

    public function payrollSheet($payrollId)
    {
        $payroll = Payroll::where('user_id', auth()->id())
            ->with(['items.employee.designation'])
            ->findOrFail($payrollId);

        $totals = [
            'gross'     => (float) $payroll->items->sum('gross_salary'),
            'ot'        => (float) $payroll->items->sum('overtime_amount'),
            'bonus'     => (float) $payroll->items->sum('bonus_amount'),
            'deduction' => (float) $payroll->items->sum('deduction_amount'),
            'advance'   => (float) $payroll->items->sum('advance_adjusted'),
            'net'       => (float) $payroll->items->sum('net_salary'),
            'paid'      => (float) $payroll->items->sum('paid_amount'),
            'due'       => (float) $payroll->items->sum('due_amount'),
        ];

        $pdf = Pdf::loadView('user.hr.pdf.payroll-sheet', [
            'payroll' => $payroll,
            'totals'  => $totals,
        ])->setPaper('a4', 'landscape');

        return $pdf->download(
            'payroll-sheet-' .
            sprintf('%02d-%04d', $payroll->payroll_month, $payroll->payroll_year) .
            '.pdf'
        );
    }

    public function payrollSummary(Request $request)
{
    $query = Payroll::where('user_id', auth()->id())
        ->with(['items.employee']);

    if ($request->filled('month')) {
        $query->where('payroll_month', (int) $request->month);
    }

    if ($request->filled('year')) {
        $query->where('payroll_year', (int) $request->year);
    }

    if ($request->filled('status')) {
        $query->where('status', $request->status);
    }

    $payrolls = $query
        ->orderByDesc('payroll_year')
        ->orderByDesc('payroll_month')
        ->get();

    $payrollItemStats = [];

    foreach ($payrolls as $payroll) {
        $items = $payroll->items ?? collect();

        $payrollItemStats[$payroll->id] = [
            'gross'   => (float) $items->sum('gross_salary'),
            'ot'      => (float) $items->sum('overtime_amount'),
            'advance' => (float) $items->sum('advance_adjusted'),
            'net'     => (float) $items->sum('net_salary'),
            'paid'    => (float) $items->sum('paid_amount'),
            'due'     => (float) $items->sum('due_amount'),
        ];
    }

    $pdf = Pdf::loadView('user.hr.pdf.payroll-summary', [
        'payrolls' => $payrolls,
        'payrollItemStats' => $payrollItemStats,
    ])->setPaper('a4', 'portrait');

    return $pdf->download('payroll-summary-report.pdf');
}
}