<?php

namespace App\Http\Controllers;

use App\Models\Staff_member;
use App\Models\Transaction_detail;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;

class StaffPayableController extends Controller
{
    public function index(Request $request)
    {
        $staffList = Staff_member::select('head_code', 'full_name', 'registration_no')->get();
        $query = Staff_member::select('head_code', 'full_name', 'registration_no', 'status');

        // 🔍 Search filter by head_code (from select)
        if ($request->has('search') && $request->search != '') {
            $query->where('head_code', $request->search);
        }

        // 📄 Entries per page (default 40)
        $perPage = $request->input('entries', 40);
        $staffs = $query->paginate($perPage);

        $totalDebit = 0;
        $totalCredit = 0;

        foreach ($staffs as $s) {
            $staffDebit = Transaction_detail::where('coa_id', $s->head_code)->sum('debit');
            $staffCredit = Transaction_detail::where('coa_id', $s->head_code)->sum('credit');

            $totalDebit += $staffDebit;
            $totalCredit += $staffCredit;

            $s->staffDebit = $staffDebit;
            $s->staffCredit = $staffCredit;
        }

        if ($request->ajax()) {
            return view('staff.partialPayableReport', compact('staffs', 'totalDebit', 'totalCredit'))->render();
        }
        return view('staff.staffPayableReport', compact('staffs', 'totalDebit', 'totalCredit', 'staffList'));
    }

    public function pdfStaffPayable(Request $request)
    {
        $query = Staff_member::select('head_code', 'full_name', 'registration_no', 'status');

        if ($request->has('search') && $request->search != '') {
            $query->where('head_code', $request->search);
        }

        $staffs = $query->get();

        $totalDebit = 0;
        $totalCredit = 0;

        foreach ($staffs as $s) {
            $staffDebit = Transaction_detail::where('coa_id', $s->head_code)->sum('debit');
            $staffCredit = Transaction_detail::where('coa_id', $s->head_code)->sum('credit');

            $totalDebit += $staffDebit;
            $totalCredit += $staffCredit;

            $s->staffDebit = $staffDebit;
            $s->staffCredit = $staffCredit;
        }

        $pdf = PDF::loadView('staff.pdfStaffPayable', compact('staffs', 'totalDebit', 'totalCredit'))
            ->setPaper('A4', 'landscape');

        return $pdf->download('staff-payable-report.pdf');
    }
}
