<?php

namespace App\Http\Controllers;

use App\Models\Payroll;
use App\Models\PayrollEmployee;
use App\Models\User;
use Exception;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use App\Interfaces\UserRepositoryInterface;
use App\Interfaces\OrganisationRepositoryInterface;
use App\Interfaces\UserOrgPermissionRepositoryInterface;
use App\Interfaces\SuperAdminRepositoryInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use App\Imports\DataImport;
use PhpParser\Builder\FunctionLike;
use Illuminate\Support\Facades\Log;
use App\Exports\PayrollExport;
use App\Exports\UsersExport;
use App\Exports\AttendanceExport;
use App\Exports\AllowanceReport;
use App\Exports\DeductionsReport;
use App\Exports\TaxReport;
use App\Exports\PensionReport;
use App\Exports\BankExport;
use App\Exports\EndOfMonth;
use App\Exports\SubscriptionExport;
use App\Exports\BillingExport;
use App\Exports\AdminPayrollExport;
use App\Exports\OrganisationExport;
use App\Exports\TeamAttendanceExport;
use Barryvdh\DomPDF\Facade\Pdf;

class AppExports extends Controller
{
    private UserRepositoryInterface $userRepository;
    private OrganisationRepositoryInterface $organisationRepository;

    private UserOrgPermissionRepositoryInterface $userOrgPermissionRepository;

    private SuperAdminRepositoryInterface $superAdminRepository;

    public function __construct(UserRepositoryInterface $userRepository, OrganisationRepositoryInterface $organisationRepository, UserOrgPermissionRepositoryInterface $userOrgPermissionRepository, SuperAdminRepositoryInterface $superAdminRepository)
    {
        $this->middleware('auth.api');
        $this->userRepository = $userRepository;
        $this->organisationRepository = $organisationRepository;
        $this->userOrgPermissionRepository = $userOrgPermissionRepository;
        $this->superAdminRepository = $superAdminRepository;
    }

    //Export Employee Data
    public function exportEmployeeData(Request $request)
    {
        try {
            $user = Auth::user();

            //check if org exists
            $org = $this->organisationRepository->findById($user->organisation_id);
            if (!$org || $org->is_active === false) {

                return response()->json([
                    'status' => 'failed',
                    'message' => 'You cannot export data at the moment',
                ], 400);
            }

            $startDate = $request->startDate ?? "2020-01-01";
            $endDate = $request->endDate ?? "2090-01-01";
            $department = $request->department ?? null;
            $employeeId = $request->employeeId;
            $type = $request->type;
            $filter = $request->filter;

            //Add Validations
            $validator = Validator::make($request->all(), [
                'startDate' => 'date|nullable',
                'endDate' => 'date|nullable',
                'department' => 'integer|nullable',
            ]);

            // Check if validation fails
            if ($validator->fails()) {
                return response()->json([
                    'status' => 'failed',
                    'message' => $validator->errors()->first(),
                ], 422);
            }

            $data = $this->organisationRepository->findEmployees($startDate, $endDate, $org->id, $employeeId, $department);
            if ($filter == "true") {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Report returned successfully',
                    'data' => $data
                ], 200);
            }
            if ($type == 'csv') {
                $export = new UsersExport($data);
                return Excel::download($export, 'employees-from-' . $startDate . '-' . $endDate . '.csv', \Maatwebsite\Excel\Excel::CSV);
            } elseif ($type == 'pdf') {
                $pdf = PDF::loadView('pdfs.employees', ['data' => $data, 'startDate' => $startDate, 'endDate' => $endDate, 'department' => $department])->setPaper('a3', 'landscape');
                return $pdf->download('employees-report-' . $startDate . '-' . $endDate . '.pdf');
            }
            return Excel::download(new UsersExport($data), 'employees.xlsx');
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failed',
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    //Export Orgnisation Attendance Reports
    public function exportAttendanceData(Request $request)
    {
        try {
            $user = Auth::user();

            //check if org exists
            $org = $this->organisationRepository->findById($user->organisation_id);
            if (!$org || $org->is_active === false) {

                return response()->json([
                    'status' => 'failed',
                    'message' => 'You cannot add permissions at the moment',
                ], 400);
            }

            $startDate = $request->startDate ?? "2020-01-01";
            $endDate = $request->endDate ?? "2090-01-01";
            $department = $request->department ?? null;
            $employeeId = $request->employeeId;
            $type = $request->type;
            $filter = $request->filter;
            $clockIn = $request->clockIn;
            $clockOut = $request->clockOut;
            $lateTime = $request->lateTime;
            $overTime = $request->overTime;

            //Add Validations
            $validator = Validator::make($request->all(), [
                'startDate' => 'date|nullable',
                'endDate' => 'date|nullable',
                'department' => 'integer|nullable',
            ]);

            //Check if validation fails
            if ($validator->fails()) {
                return response()->json([
                    'status' => 'failed',
                    'message' => $validator->errors()->first(),
                ], 422);
            }

            $data = $this->organisationRepository->getAllEmployeeAttendance($startDate, $endDate, $org->id, $employeeId, $clockOut, $clockIn, $lateTime, $overTime);
            if ($filter == "true") {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Report returned successfully',
                    'data' => $data
                ], 200);
            }
            if ($type == 'csv') {
                $export = new AttendanceExport($data);
                return Excel::download($export, 'attendance-from-' . $startDate . '-' . $endDate . '.csv', \Maatwebsite\Excel\Excel::CSV);
            } elseif ($type == 'pdf') {
                $pdf = PDF::loadView('pdfs.attendance', ['data' => $data, 'startDate' => $startDate, 'endDate' => $endDate])->setPaper('a3', 'landscape');
                return $pdf->download('attendance-report-' . $startDate . '-' . $endDate . '.pdf');
            }
            return Excel::download(new AttendanceExport($data), 'attendance.xlsx');
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failed',
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    //Generate Allowance Reports
    public function exportAllowanceReport(Request $request)
    {
        try {
            $user = Auth::user();

            //check if org exists
            $org = $this->organisationRepository->findById($user->organisation_id);
            if (!$org || $org->is_active === false) {

                return response()->json([
                    'status' => 'failed',
                    'message' => 'You cannot add permissions at the moment',
                ], 400);
            }

            $startDate = $request->startDate ?? "2020-01-01";
            $endDate = $request->endDate ?? "2090-01-01";
            $employeeId = $request->employeeId;
            $type = $request->type;
            $filter = $request->filter;
            $allowanceId = $request->allowanceId;

            //Add Validations
            $validator = Validator::make($request->all(), [
                'startDate' => 'date|nullable',
                'endDate' => 'date|nullable',
            ]);

            //Check if validation fails
            if ($validator->fails()) {
                return response()->json([
                    'status' => 'failed',
                    'message' => $validator->errors()->first(),
                ], 422);
            }

            $payrollData = $this->organisationRepository->getPayrollReport($startDate, $endDate, $org->id, $employeeId, $allowanceId);
            $data = [];
            $allAllowances = [];

            foreach ($payrollData as $item) {
                $allowances = json_decode($item['allowances_array'], true);

                if (!empty($allowances) && is_array($allowances)) {
                    foreach ($allowances as $allowance) {
                        $allAllowances[$allowance['name']] = true;
                    }
                }
            }
            // Get all unique allowance names
            $allAllowancesName = array_keys($allAllowances);

            foreach ($payrollData as $item) {
                $row = [
                    'Employee ID' => $item['employee_id'],
                    'Employee Name' => $item["first_name"] . ' ' . $item["middle_name"] . ' ' . $item["last_name"],
                    'Basic Pay' => !empty($item['basic_salary_amount']) ? $item['basic_salary_amount'] : "0:00",
                    'Gross Pay' => !empty($item['gross_amount']) ? $item['gross_amount'] : "0:00",
                    'Tax Paid' => !empty($item['tax_amount']) ? $item['tax_amount'] : "0:00",
                    'Total Tax Calculation' => !empty($item['tax_amount']) ? $item['tax_amount'] : "0:00",
                    'Pay Deducts Calculation' => !empty($item['deduction_amount']) ? $item['deduction_amount'] : "0:00",
                    'Net Pay Calculation' => !empty($item['taxable_income_amount']) ? $item['taxable_income_amount'] : "0.00",
                    'Pension Employee' => !empty($item['pension_amount']) ? $item['pension_amount'] : '0.00',
                    'Payable Amount' => !empty($item['payable_amount']) ? $item['payable_amount'] : '0.00',
                ];

                $allowances = json_decode($item['allowances_array'], true);

                // Initialize all allowances to 0.00
                foreach ($allAllowancesName as $allowanceName) {
                    $row[$allowanceName] = '0.00';
                }

                // Adding dynamic allowances if deduction_array is an array
                if (!empty($allowances) && is_array($allowances)) {
                    foreach ($allowances as $allowance) {
                        $row[$allowance['name']] = $allowance['value'];
                    }
                }

                $data[] = $row;
            }

            if ($filter == "true") {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Report returned successfully',
                    'data' => $data
                ], 200);
            }
            if ($type == 'csv') {
                $export = new AllowanceReport($data);
                return Excel::download($export, 'allowance-from-' . $startDate . '-' . $endDate . '.csv', \Maatwebsite\Excel\Excel::CSV);
            } elseif ($type == 'pdf') {
                $pdf = PDF::loadView('pdfs.allowance', ['data' => $data, 'startDate' => $startDate, 'endDate' => $endDate, 'allAllowancesName' => $allAllowancesName])->setPaper('a3', 'landscape');
                return $pdf->download('allowance-report-' . $startDate . '-' . $endDate . '.pdf');
            }
            $export = new AllowanceReport($data);
            return Excel::download($export, 'allowance-from-' . $startDate . '-' . $endDate . '.xlsx');
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failed',
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    //Generate Deductions Reports
    public function exportDeductionReport(Request $request)
    {
        try {
            $user = Auth::user();

            //check if org exists
            $org = $this->organisationRepository->findById($user->organisation_id);
            if (!$org || $org->is_active === false) {

                return response()->json([
                    'status' => 'failed',
                    'message' => 'You cannot add permissions at the moment',
                ], 400);
            }

            $startDate = $request->startDate ?? "2020-01-01";
            $endDate = $request->endDate ?? "2090-01-01";
            $employeeId = $request->employeeId;
            $type = $request->type;
            $filter = $request->filter;
            $deductionId = $request->deductionId;

            //Add Validations
            $validator = Validator::make($request->all(), [
                'startDate' => 'date|nullable',
                'endDate' => 'date|nullable',
            ]);

            //Check if validation fails
            if ($validator->fails()) {
                return response()->json([
                    'status' => 'failed',
                    'message' => $validator->errors()->first(),
                ], 422);
            }

            $payrollData = $this->organisationRepository->getPayrollReport($startDate, $endDate, $org->id, $employeeId, null, $deductionId);
            $data = [];
            $allDeductions = [];

            foreach ($payrollData as $item) {
                $deductions = json_decode($item['deduction_array'], true);

                if (!empty($deductions) && is_array($deductions)) {
                    foreach ($deductions as $deduction) {
                        $allDeductions[$deduction['name']] = true;
                    }
                }
            }
            // Get all unique deduction names
            $allDeductionNames = array_keys($allDeductions);

            foreach ($payrollData as $item) {
                $row = [
                    'Employee ID' => $item['employee_id'],
                    'Employee Name' => $item["first_name"] . ' ' . $item["middle_name"] . ' ' . $item["last_name"],
                    'Basic Pay' => !empty($item['basic_salary_amount']) ? $item['basic_salary_amount'] : "Not Set",
                    'Gross Pay' => !empty($item['gross_amount']) ? $item['gross_amount'] : "Not Set",
                    'Tax Paid' => !empty($item['tax_amount']) ? $item['tax_amount'] : "Not Set",
                    'Total Tax Calculation' => !empty($item['tax_amount']) ? $item['tax_amount'] : "Not Set",
                    'Pension Employee' => !empty($item['pension_amount']) ? $item['pension_amount'] : '0.00',
                    'Payable Amount' => !empty($item['payable_amount']) ? $item['payable_amount'] : '0.00',
                ];

                $deductions = json_decode($item['deduction_array'], true);

                // Initialize all deductions to 0.00
                foreach ($allDeductionNames as $deductionName) {
                    $row[$deductionName] = '0.00';
                }

                // Adding dynamic deductions if deduction_array is an array
                if (!empty($deductions) && is_array($deductions)) {
                    foreach ($deductions as $deduction) {
                        $row[$deduction['name']] = $deduction['value'];
                    }
                }

                $data[] = $row;
            }

            if ($filter == "true") {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Report returned successfully',
                    'data' => $data
                ], 200);
            }
            if ($type == 'csv') {
                $export = new DeductionsReport($data);
                return Excel::download($export, 'deductions-from-' . $startDate . '-' . $endDate . '.csv', \Maatwebsite\Excel\Excel::CSV);
            } elseif ($type == 'pdf') {
                $pdf = PDF::loadView('pdfs.deduction', ['data' => $data, 'startDate' => $startDate, 'endDate' => $endDate, 'allDeductionNames' => $allDeductionNames])->setPaper('a3', 'landscape');
                return $pdf->download('deduction-report-' . $startDate . '-' . $endDate . '.pdf');
            }
            $export = new DeductionsReport($data);
            return Excel::download($export, 'deductions-from-' . $startDate . '-' . $endDate . '.xlsx');
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failed',
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    //Generate Tax Reports
    public function exportTaxReport(Request $request)
    {
        try {
            $user = Auth::user();

            //check if org exists
            $org = $this->organisationRepository->findById($user->organisation_id);
            if (!$org || $org->is_active === false) {

                return response()->json([
                    'status' => 'failed',
                    'message' => 'You cannot add permissions at the moment',
                ], 400);
            }

            $startDate = $request->startDate ?? "2020-01-01";
            $endDate = $request->endDate ?? "2090-01-01";
            $employeeId = $request->employeeId;
            $type = $request->type;
            $filter = $request->filter;

            //Add Validations
            $validator = Validator::make($request->all(), [
                'startDate' => 'date|nullable',
                'endDate' => 'date|nullable',
            ]);

            //Check if validation fails
            if ($validator->fails()) {
                return response()->json([
                    'status' => 'failed',
                    'message' => $validator->errors()->first(),
                ], 422);
            }

            $payrollData = $this->organisationRepository->getPayrollReport($startDate, $endDate, $org->id, $employeeId);
            $data = [];
            foreach ($payrollData as $key => $item) {
                $data[] = [
                    'Employee ID' => $item['employee_id'],
                    'Employee Name' => $item["first_name"] . ' ' . $item["middle_name"] . ' ' . $item["last_name"],
                    'Basic Pay' => !empty($item['basic_salary_amount']) ? $item['basic_salary_amount'] : "0.00",
                    'Gross Earning Calculation' => !empty($item['gross_amount']) ? $item['gross_amount'] : "0.00",
                    'Net Taxable Calculation' => !empty($item['taxable_income_amount']) ? $item['taxable_income_amount'] : "0.00",
                    'Tax Paid' => !empty($item['tax_amount']) ? $item['tax_amount'] : "0.00",
                    'Total Tax Calculation' => !empty($item['tax_amount']) ? $item['tax_amount'] : "0.00",
                    'Tax' => !empty($item['tax_amount']) ? $item['tax_amount'] : "0.00",
                    'Tax State' => !empty($item['tax_state']) ? $item['tax_state'] : "Not Set",
                    'Tax Number' => !empty($item['tax_id']) ? $item['tax_id'] : "Not Set",
                ];
            }

            if ($filter == "true") {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Report returned successfully',
                    'data' => $data
                ], 200);
            }
            if ($type == 'csv') {
                $export = new TaxReport($data);
                return Excel::download($export, 'tax-deductions-from-' . $startDate . '-' . $endDate . '.csv', \Maatwebsite\Excel\Excel::CSV);
            } elseif ($type == 'pdf') {
                $pdf = PDF::loadView('pdfs.tax', ['data' => $data, 'startDate' => $startDate, 'endDate' => $endDate])->setPaper('a3', 'landscape');
                return $pdf->download('tax-report-' . $startDate . '-' . $endDate . '.pdf');
            }
            $export = new TaxReport($data);
            return Excel::download($export, 'tax-deductions-from-' . $startDate . '-' . $endDate . '.xlsx');
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failed',
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    //Generate Single Payroll Tax Report
    public function exportSinglePayrollTaxReport(Request $request, $payrollId)
    {
        try {
            $user = Auth::user();
            $org = $this->organisationRepository->findById($user->organisation_id);

            if (!$org || $org->is_active === false) {
                return response()->json(['status' => 'failed', 'message' => 'Unauthorized'], 400);
            }

            $type = $request->type;
            $filter = $request->filter;

            // Fetch data for specific payroll ID
            $payrollData = $this->organisationRepository->getTaxReportByPayrollId($payrollId, $org->id);

            if ($payrollData->isEmpty()) {
                return response()->json(['status' => 'failed', 'message' => 'No record found for this payroll'], 404);
            }

            $data = [];
            foreach ($payrollData as $item) {
                $data[] = [
                    'Employee ID'               => $item->employee_id,
                    'Employee Name'             => trim(($item->first_name ?? '') . ' ' . ($item->middle_name ?? '') . ' ' . ($item->last_name ?? '')),
                    'Basic Pay'                 => $item->basic_salary_amount ?: "0.00",
                    'Gross Earning Calculation' => $item->gross_amount ?: "0.00",
                    'Net Taxable Calculation'   => $item->taxable_income_amount ?: "0.00",
                    'Tax Paid'                  => $item->tax_amount ?: "0.00",
                    'Total Tax Calculation'     => $item->tax_amount ?: "0.00",
                    'Tax'                       => $item->tax_amount ?: "0.00",
                    'Tax State'                 => $item->tax_state ?: "Not Set",
                    'Tax Number'                => $item->tax_id ?: "Not Set",
                ];
            }

            if ($filter == "true") {
                return response()->json([
                    'status' => 'success', 
                    'message' => 'Report returned successfully', 
                    'data' => $data
                ], 200);
            }

            $filename = 'tax-report-payroll-' . $payrollId;

            if ($type == 'csv') {
                return Excel::download(new TaxReport($data), $filename . '.csv', \Maatwebsite\Excel\Excel::CSV);
            } elseif ($type == 'pdf') {
                $pdf = PDF::loadView('pdfs.tax', ['data' => $data])->setPaper('a3', 'landscape');
                return $pdf->download($filename . '.pdf');
            }

            return Excel::download(new TaxReport($data), $filename . '.xlsx');

        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failed', 
                'message' => "Line {$e->getLine()}: " . $e->getMessage()
            ], 500);
        }
    }

    // Generate Pension Reports
    public function exportPensionReport(Request $request)
    {
        try {
            $user = Auth::user();

            //check if org exists
            $org = $this->organisationRepository->findById($user->organisation_id);
            if (!$org || $org->is_active === false) {

                return response()->json([
                    'status' => 'failed',
                    'message' => 'You cannot add permissions at the moment',
                ], 400);
            }

            $startDate = $request->startDate ?? "2020-01-01";
            $endDate = $request->endDate ?? "2090-01-01";
            $employeeId = $request->employeeId;
            $type = $request->type;
            $filter = $request->filter;

            //Add Validations
            $validator = Validator::make($request->all(), [
                'startDate' => 'date|nullable',
                'endDate' => 'date|nullable',
            ]);

            //Check if validation fails
            if ($validator->fails()) {
                return response()->json([
                    'status' => 'failed',
                    'message' => $validator->errors()->first(),
                ], 422);
            }

            $payrollData = $this->organisationRepository->getPayrollReport($startDate, $endDate, $org->id, $employeeId);
            $data = [];
            foreach ($payrollData as $key => $item) {
                $dob = $item['dob'];
                $age = 'Unknown';

                if ($dob && preg_match('/^\d{4}-\d{2}-\d{2}$/', $dob)) {
                    try {
                        $dob = Carbon::parse($dob);
                        $age = $dob->age;
                    } catch (\Exception $e) {
                        // Handle exception if Carbon parsing fails
                        $age = 'Invalid Date';
                    }
                }

                $data[] = [
                    'Employee ID' => $item['employee_id'],
                    'Employee Name' => $item["first_name"] . ' ' . $item["middle_name"] . ' ' . $item["last_name"],
                    'PIN Number' => !empty($item['pfa']) ? $item['pfa'] : "Not Set",
                    'PFA Name' => !empty($item['pfa_name']) ? $item['pfa_name'] : "Not Set",
                    'Pension Employee' => !empty($item['pension_amount']) ? (float) $item['pension_amount'] * ((float) $item['pension_percentage'] / 100) : '0.00',
                    'Pension Employer' => !empty($item['pension_amount']) ? (float) $item['pension_amount'] - ((float) $item['pension_amount'] * ((float) $item['pension_percentage'] / 100)) : "0:00",
                    'Total Pension Calculation' => !empty($item['pension_amount']) ? $item['pension_amount'] : "0:00",
                    'Age' => !empty($item['dob']) ? $age : "Not Set",
                ];
            }
            if ($filter == "true") {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Report returned successfully',
                    'data' => $data
                ], 200);
            }
            if ($type === 'csv') {
                $export = new PensionReport($data);
                return Excel::download($export, 'pension.csv', \Maatwebsite\Excel\Excel::CSV);
            } elseif ($type == 'pdf') {
                $pdf = PDF::loadView('pdfs.pension', ['data' => $data, 'startDate' => $startDate, 'endDate' => $endDate])->setPaper('a3', 'landscape');
                return $pdf->download('pension-report-' . $startDate . '-' . $endDate . '.pdf');
            }
            $export = new PensionReport($data);
            return Excel::download($export, 'pension-from-' . $startDate . '-' . $endDate . '.xlsx');
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failed',
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    //Generate Single Payroll Pension Report
    public function exportSinglePayrollPensionReport(Request $request, $payrollId)
    {
        try {
            $user = Auth::user();
            $org = $this->organisationRepository->findById($user->organisation_id);

            if (!$org || $org->is_active === false) {
                return response()->json(['status' => 'failed', 'message' => 'Unauthorized'], 400);
            }

            $type = $request->type;
            $filter = $request->filter;

            $payrollData = $this->organisationRepository->getPensionReportByPayrollId($payrollId, $org->id);

            if ($payrollData->isEmpty()) {
                return response()->json(['status' => 'failed', 'message' => 'No pension records found'], 404);
            }

            $data = [];
            foreach ($payrollData as $item) {
                $age = 'Not Set';
                if (!empty($item->dob)) {
                    try {
                        $age = \Carbon\Carbon::parse($item->dob)->age;
                    } catch (\Exception $e) {
                        $age = 'Invalid Date';
                    }
                }

                $totalPension = (float)($item->pension_amount ?? 0);
                $pensionPerc  = (float)($item->pension_percentage ?? 0);
                
                // Assuming pension_amount is the Total, and we split based on percentage
                $empContribution = $totalPension * ($pensionPerc / 100);
                $orgContribution = $totalPension - $empContribution;

                $data[] = [
                    'Employee ID'               => $item->employee_id,
                    'Employee Name'             => trim(($item->first_name ?? '') . ' ' . ($item->middle_name ?? '') . ' ' . ($item->last_name ?? '')),
                    'PIN Number'                => $item->rsa_number ?? ($item->pfa ?? "Not Set"),
                    'PFA Name'                  => $item->pfa_name ?: "Not Set",
                    'Pension Employee'          => number_format($empContribution, 2, '.', ''),
                    'Pension Employer'          => number_format($orgContribution, 2, '.', ''),
                    'Total Pension Calculation' => number_format($totalPension, 2, '.', ''),
                    'Age'                       => $age,
                ];
            }

            if ($filter == "true") {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Pension report returned',
                    'data' => $data
                ], 200);
            }

            $filename = 'pension-report-payroll-' . $payrollId;

            if ($type === 'csv') {
                return Excel::download(new PensionReport($data), $filename . '.csv', \Maatwebsite\Excel\Excel::CSV);
            } elseif ($type == 'pdf') {
                $pdf = PDF::loadView('pdfs.pension', ['data' => $data])->setPaper('a3', 'landscape');
                return $pdf->download($filename . '.pdf');
            }

            return Excel::download(new PensionReport($data), $filename . '.xlsx');

        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failed',
                'message' => "Line {$e->getLine()}: " . $e->getMessage()
            ], 500);
        }
    }


    //Generate Bank Reports
    public function exportBankReport(Request $request)
    {
        try {
            $user = Auth::user();

            //check if org exists
            $org = $this->organisationRepository->findById($user->organisation_id);
            if (!$org || $org->is_active === false) {

                return response()->json([
                    'status' => 'failed',
                    'message' => 'You cannot add permissions at the moment',
                ], 400);
            }

            $startDate = $request->startDate ?? "2020-01-01";
            $endDate = $request->endDate ?? "2090-01-01";
            $employeeId = $request->employeeId;
            $type = $request->type;
            $filter = $request->filter;

            //Add Validations
            $validator = Validator::make($request->all(), [
                'startDate' => 'date|nullable',
                'endDate' => 'date|nullable',
            ]);

            //Check if validation fails
            if ($validator->fails()) {
                return response()->json([
                    'status' => 'failed',
                    'message' => $validator->errors()->first(),
                ], 422);
            }

            $payrollData = $this->organisationRepository->getPayrollReport($startDate, $endDate, $org->id, $employeeId);
            $data = [];
            foreach ($payrollData as $key => $item) {
                $data[] = [
                    'Employee Name' => $item["first_name"] . ' ' . $item["middle_name"] . ' ' . $item["last_name"],
                    'Account Number' => !empty($item['account_number']) ? $item['account_number'] : "Not Set",
                    'Bank Name' => !empty($item['bank_name']) ? $item['bank_name'] : "Not Set",
                    'Pension Amount' => !empty($item['payable_amount']) ? $item['payable_amount'] : '0.00',
                ];
            }

            if ($filter == "true") {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Report returned successfully',
                    'data' => $data
                ], 200);
            }
            if ($type == 'csv') {
                $export = new BankExport($data);
                return Excel::download($export, 'employees.csv', \Maatwebsite\Excel\Excel::CSV);
            } elseif ($type == 'pdf') {
                $pdf = PDF::loadView('pdfs.bank', ['data' => $data, 'startDate' => $startDate, 'endDate' => $endDate])->setPaper('a3', 'landscape');
                return $pdf->download('bank-report-' . $startDate . '-' . $endDate . '.pdf');
            }
            $export = new BankExport($data);
            return Excel::download($export, 'bank-report-from-' . $startDate . '-' . $endDate . '.xlsx');
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failed',
                'message' => $e->getMessage(),
            ], 500);
        }
    }


    //Generate End Of Month Report
    // public function exportEndOfMonth(Request $request)
    // {
    //     try {
    //         $user = Auth::user();

    //         //check if org exists
    //         $org = $this->organisationRepository->findById($user->organisation_id);
    //         if (!$org || $org->is_active === false) {
    //             return response()->json([
    //                 'status' => 'failed',
    //                 'message' => 'You cannot add permissions at the moment',
    //             ], 400);
    //         }

    //         $startDate = $request->startDate ?? "2020-01-01";
    //         $endDate = $request->endDate ?? "2090-01-01";
    //         $employeeId = $request->employeeId;
    //         $type = $request->type;
    //         $filter = $request->filter;

    //         //Add Validations
    //         $validator = Validator::make($request->all(), [
    //             'startDate' => 'date|nullable',
    //             'endDate' => 'date|nullable',
    //         ]);

    //         //Check if validation fails
    //         if ($validator->fails()) {
    //             return response()->json([
    //                 'status' => 'failed',
    //                 'message' => $validator->errors()->first(),
    //             ], 422);
    //         }

    //         // Get the current date
    //         $now = Carbon::now();

    //         // Calculate the start and end dates for the previous month
    //         $start = $now->subMonth()->startOfMonth()->toDateString();
    //         $end = $now->endOfMonth()->toDateString();
    //         $employeeData = $this->organisationRepository->findEmployees($start, $end ,$org->id,$employeeId);
    //         $employeeComparisonData = $this->organisationRepository->getEmployeePayrollComparison($org->id, $employeeId);
    //         $data1 = [];
    //         $data2 = [];
    //         $data3 = [];
    //         $data3 = [];
    //         $data5 = [];

    //         $currentPayroll = $this->organisationRepository->getPayrollReportMonthly($startDate, $endDate, $org->id, $employeeId);
    //         if ($currentPayroll) {
    //             $data1 = [
    //                 'section' => 'Last Period',
    //                 'headings' => [
    //                     'Staff Count', 'Basic Salary', 'Total Allowance', 'Gross Pay', 'Total Tax Calculation', 'Pay Deducts Calculation', 'Total Deduction'
    //                 ],
    //                 'data' => [
    //                     [
    //                         'Staff Count' => $currentPayroll->staff_count ?: "Not Set",
    //                         'Basic Salary' => $currentPayroll->total_basic_salary ?: "0.00",
    //                         'Total Allowance' => $currentPayroll->total_allowance ?: "0.00",
    //                         'Gross Pay' => $currentPayroll->total_gross_pay ?: "0.00",
    //                         'Total Tax Calculation' => $currentPayroll->total_tax_calculation ?: "0.00",
    //                         'Pay Deducts Calculation' => $currentPayroll->total_deduction_amount ?: "0.00",
    //                         'Total Deduction' => $currentPayroll->total_tax_calculation + $currentPayroll->total_deduction_amount ?: "0.00",
    //                     ]
    //                 ]
    //             ];
    //         }

    //         // Previous Period Data
    //         $previousPayroll = $this->organisationRepository->getPayrollReportPrevious($org->id);
    //         if ($previousPayroll) {
    //             $data2 = [
    //                 'section' => 'Current Period',
    //                 'headings' => [
    //                     'Staff Count', 'Basic Salary', 'Total Allowance', 'Gross Pay', 'Total Tax Calculation', 'Pay Deducts Calculation', 'Total Deduction'
    //                 ],
    //                 'data' => [
    //                     [
    //                         'Staff Count' => $previousPayroll->staff_count ?: "Not Set",
    //                         'Basic Salary' => $previousPayroll->total_basic_salary ?: "0.00",
    //                         'Total Allowance' => $previousPayroll->total_allowance ?: "0.00",
    //                         'Gross Pay' => $previousPayroll->total_gross_pay ?: "0.00",
    //                         'Total Tax Calculation' => $previousPayroll->total_tax_calculation ?: "0.00",
    //                         'Pay Deducts Calculation' => $previousPayroll->total_deduction_amount ?: "0.00",
    //                         'Total Deduction' => $previousPayroll->total_tax_calculation + $previousPayroll->total_deduction_amount ?: "0.00",
    //                     ]
    //                 ]
    //             ];
    //         }

    //         // Difference Data
    //         $differenceData = [];
    //         if ($currentPayroll && $previousPayroll) {
    //             $differenceData = [
    //                 'section' => 'Difference',
    //                 'headings' => [
    //                     'Staff Count', 'Basic Salary', 'Total Allowance', 'Gross Pay', 'Total Tax Calculation', 'Pay Deducts Calculation', 'Total Deduction'
    //                 ],
    //                 'data' => [
    //                     [
    //                         'Staff Count' => $currentPayroll->staff_count - $previousPayroll->staff_count,
    //                         'Basic Salary' => $currentPayroll->total_basic_salary - $previousPayroll->total_basic_salary,
    //                         'Total Allowance' => $currentPayroll->total_allowance - $previousPayroll->total_allowance,
    //                         'Gross Pay' => $currentPayroll->total_gross_pay - $previousPayroll->total_gross_pay,
    //                         'Total Tax Calculation' => $currentPayroll->total_tax_calculation - $previousPayroll->total_tax_calculation,
    //                         'Pay Deducts Calculation' => $currentPayroll->total_deduction_amount - $previousPayroll->total_deduction_amount,
    //                         'Total Deduction' => ($currentPayroll->total_tax_calculation + $currentPayroll->total_deduction_amount) - ($previousPayroll->total_tax_calculation + $previousPayroll->total_deduction_amount),
    //                     ]
    //                 ]
    //             ];
    //         }

    //         // New Staff Data
    //         $newStaffData = [];
    //         foreach ($employeeData as $item) {
    //             $newStaffData[] = [
    //                 'Employee Number' => $item['id'] ?? "Not Set",
    //                 'Employee Name' => $item['profile']['first_name'] . ' ' . $item['profile']['last_name'] ?? "Not Set",
    //                 'Last Period Gross' => "0.00",
    //                 'Current Period Gross' => $item['job_info']['pay_rate'] ?? "0.00",
    //                 'Difference' => "0.00",
    //                 'Date Employed' => Carbon::parse($item['created_at'])->format('d-m-Y') ?? "Not Set"
    //             ];
    //         }
    //         $data3 = [
    //             'section' => 'New Staff',
    //             'headings' => ['Employee Number', 'Employee Name', 'Last Period Gross', 'Current Period Gross', 'Difference', 'Date Employed'],
    //             'data' => $newStaffData
    //         ];

    //         // Salary Review Data
    //         $salaryReviewData = [];
    //         foreach ($employeeComparisonData as $item) {
    //             $salaryReviewData[] = [
    //                 'Employee Number' => $item['Employee_Number'] ?? "Not Set",
    //                 'Employee Name' => $item['Employee_Name'],
    //                 'Last Period Gross' => $item['Last_Period_Gross'] ?? "0.00",
    //                 'Current Period Gross' => $item['Current_Period_Gross'] ?? "0.00",
    //                 'Difference' => $item['Difference'] ?? "0.00",
    //                 'Review Date' => $item['Review_Date'] ?? "0.00"
    //             ];
    //         }
    //         $data5 = [
    //             'section' => 'Salary Review',
    //             'headings' => ['Employee Number', 'Employee Name', 'Last Period Gross', 'Current Period Gross', 'Difference', 'Review Date'],
    //             'data' => $salaryReviewData
    //         ];

    //         // Combine the data
    //         $combinedData = [$data1, $data2, $differenceData, $data3, $data5];
    //         $sectionHeadings = ['LAST PERIOD', 'CURRENT PERIOD', 'DIFFERENCE', 'NEW STAFF', 'SALARY REVIEW'];
    //         if ($filter == "true") {
    //             return response()->json([
    //                 'status' => 'success',
    //                 'message' => 'Report returned successfully',
    //                 'data' => [
    //                     "Last Period" => $data1,
    //                     "Current Period" => $data2,
    //                     "Difference" => $differenceData,
    //                     "New Staff" => $data3,
    //                     'Salary Review' => $data5
    //                 ]
    //             ], 200);
    //         }
    //         if($type == 'csv'){
    //             $export = new EndOfMonth($combinedData,$sectionHeadings);
    //             return Excel::download($export, 'end-of-report-' . $startDate . '-' . $endDate . '.xlsx', \Maatwebsite\Excel\Excel::CSV);
    //         }elseif ($type == 'pdf') {
    //             $pdf = PDF::loadView('pdfs.end_of_month', array('data' =>  $combinedData));
    //             return $pdf->download('end-of-report-' . $startDate . '-' . $endDate . '.pdf');
    //         }
    //         $export = new EndOfMonth($combinedData,$sectionHeadings);
    //         return Excel::download($export, 'end-of-report-' . $startDate . '-' . $endDate . '.xlsx');
    //     } catch (\Exception $e) {
    //         return response()->json([
    //             'status' => 'failed',
    //             'message' => $e->getMessage(),
    //         ], 500);
    //     }
    // }

    public function exportEndOfMonth(Request $request)
    {
        try {
            $user = Auth::user();

            // Check if org exists
            $org = $this->organisationRepository->findById($user->organisation_id);
            if (!$org || $org->is_active === false) {
                return response()->json([
                    'status' => 'failed',
                    'message' => 'You cannot add permissions at the moment',
                ], 400);
            }

            $startDate = $request->startDate ?? "2020-01-01";
            $endDate = $request->endDate ?? "2090-01-01";
            $employeeId = $request->employeeId;
            $type = $request->type;
            $filter = $request->filter;

            // Add validations
            $validator = Validator::make($request->all(), [
                'startDate' => 'date|nullable',
                'endDate' => 'date|nullable',
            ]);

            // Check if validation fails
            if ($validator->fails()) {
                return response()->json([
                    'status' => 'failed',
                    'message' => $validator->errors()->first(),
                ], 422);
            }

            // Get the current date
            $now = Carbon::now();

            // Calculate the start and end dates for the previous month
            $start = $now->subMonth()->startOfMonth()->toDateString();
            $end = $now->endOfMonth()->toDateString();
            $employeeData = $this->organisationRepository->findEmployees($start, $end, $org->id, $employeeId);
            $employeeComparisonData = $this->organisationRepository->getEmployeePayrollComparison($org->id, $employeeId);

            $data1 = [];
            $data2 = [];
            $data3 = [];
            $data5 = [];

            // Get current payroll report
            $currentPayroll = $this->organisationRepository->getPayrollReportMonthly($startDate, $endDate, $org->id, $employeeId);
            if ($currentPayroll) {
                $data1 = [
                    'section' => 'Last Period',
                    'headings' => [
                        'Staff Count',
                        'Basic Salary',
                        'Total Allowance',
                        'Gross Pay',
                        'Total Tax Calculation',
                        'Pay Deducts Calculation',
                        'Total Deduction'
                    ],
                    'data' => [
                        [
                            'Staff Count' => $currentPayroll->staff_count ?: "Not Set",
                            'Basic Salary' => $currentPayroll->total_basic_salary ?: "0.00",
                            'Total Allowance' => $currentPayroll->total_allowance ?: "0.00",
                            'Gross Pay' => $currentPayroll->total_gross_pay ?: "0.00",
                            'Total Tax Calculation' => $currentPayroll->total_tax_calculation ?: "0.00",
                            'Pay Deducts Calculation' => $currentPayroll->total_deduction_amount ?: "0.00",
                            'Total Deduction' => $currentPayroll->total_tax_calculation + $currentPayroll->total_deduction_amount ?: "0.00",
                        ]
                    ]
                ];
            }

            // Get previous payroll report
            $previousPayroll = $this->organisationRepository->getPayrollReportPrevious($org->id);
            if ($previousPayroll) {
                $data2 = [
                    'section' => 'Current Period',
                    'headings' => [
                        'Staff Count',
                        'Basic Salary',
                        'Total Allowance',
                        'Gross Pay',
                        'Total Tax Calculation',
                        'Pay Deducts Calculation',
                        'Total Deduction'
                    ],
                    'data' => [
                        [
                            'Staff Count' => $previousPayroll->staff_count ?: "Not Set",
                            'Basic Salary' => $previousPayroll->total_basic_salary ?: "0.00",
                            'Total Allowance' => $previousPayroll->total_allowance ?: "0.00",
                            'Gross Pay' => $previousPayroll->total_gross_pay ?: "0.00",
                            'Total Tax Calculation' => $previousPayroll->total_tax_calculation ?: "0.00",
                            'Pay Deducts Calculation' => $previousPayroll->total_deduction_amount ?: "0.00",
                            'Total Deduction' => $previousPayroll->total_tax_calculation + $previousPayroll->total_deduction_amount ?: "0.00",
                        ]
                    ]
                ];
            }

            // Calculate the difference between current and previous payroll
            $differenceData = [];
            if ($currentPayroll && $previousPayroll) {
                $differenceData = [
                    'section' => 'Difference',
                    'headings' => [
                        'Staff Count',
                        'Basic Salary',
                        'Total Allowance',
                        'Gross Pay',
                        'Total Tax Calculation',
                        'Pay Deducts Calculation',
                        'Total Deduction'
                    ],
                    'data' => [
                        [
                            'Staff Count' => $currentPayroll->staff_count - $previousPayroll->staff_count,
                            'Basic Salary' => $currentPayroll->total_basic_salary - $previousPayroll->total_basic_salary,
                            'Total Allowance' => $currentPayroll->total_allowance - $previousPayroll->total_allowance,
                            'Gross Pay' => $currentPayroll->total_gross_pay - $previousPayroll->total_gross_pay,
                            'Total Tax Calculation' => $currentPayroll->total_tax_calculation - $previousPayroll->total_tax_calculation,
                            'Pay Deducts Calculation' => $currentPayroll->total_deduction_amount - $previousPayroll->total_deduction_amount,
                            'Total Deduction' => ($currentPayroll->total_tax_calculation + $currentPayroll->total_deduction_amount) - ($previousPayroll->total_tax_calculation + $previousPayroll->total_deduction_amount),
                        ]
                    ]
                ];
            }

            // New staff data
            $newStaffData = [];
            foreach ($employeeData as $item) {
                $newStaffData[] = [
                    'Employee Number' => $item['id'] ?? "Not Set",
                    'Employee Name' => $item['profile']['first_name'] . ' ' . $item['profile']['last_name'] ?? "Not Set",
                    'Last Period Gross' => "0.00",
                    'Current Period Gross' => $item['job_info']['pay_rate'] ?? "0.00",
                    'Difference' => "0.00",
                    'Date Employed' => Carbon::parse($item['created_at'])->format('d-m-Y') ?? "Not Set"
                ];
            }
            $data3 = [
                'section' => 'New Staff',
                'headings' => ['Employee Number', 'Employee Name', 'Last Period Gross', 'Current Period Gross', 'Difference', 'Date Employed'],
                'data' => $newStaffData
            ];

            // Salary review data
            $salaryReviewData = [];
            foreach ($employeeComparisonData as $item) {
                $salaryReviewData[] = [
                    'Employee Number' => $item['Employee_Number'] ?? "Not Set",
                    'Employee Name' => $item['Employee_Name'],
                    'Last Period Gross' => $item['Last_Period_Gross'] ?? "0.00",
                    'Current Period Gross' => $item['Current_Period_Gross'] ?? "0.00",
                    'Difference' => $item['Difference'] ?? "0.00",
                    'Review Date' => $item['Review_Date'] ?? "0.00"
                ];
            }
            $data5 = [
                'section' => 'Salary Review',
                'headings' => ['Employee Number', 'Employee Name', 'Last Period Gross', 'Current Period Gross', 'Difference', 'Review Date'],
                'data' => $salaryReviewData
            ];

            // Combine all data sections
            $combinedData = [$data1, $data2, $differenceData, $data3, $data5];
            $sectionHeadings = ['LAST PERIOD', 'CURRENT PERIOD', 'DIFFERENCE', 'NEW STAFF', 'SALARY REVIEW'];

            if ($filter == "true") {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Report returned successfully',
                    'data' => [
                        "Last Period" => $data1,
                        "Current Period" => $data2,
                        "Difference" => $differenceData,
                        "New Staff" => $data3,
                        'Salary Review' => $data5
                    ]
                ], 200);
            }

            if ($type == 'csv') {
                $export = new EndOfMonth($combinedData, $sectionHeadings);
                return Excel::download($export, 'end-of-report-' . $startDate . '-' . $endDate . '.xlsx', \Maatwebsite\Excel\Excel::CSV);
            } elseif ($type == 'pdf') {
                $pdf = PDF::loadView('pdfs.end_of_month', ['data' => $combinedData]);
                return $pdf->download('end-of-report-' . $startDate . '-' . $endDate . '.pdf');
            }

            $export = new EndOfMonth($combinedData, $sectionHeadings);
            return Excel::download($export, 'end-of-report-' . $startDate . '-' . $endDate . '.xlsx');
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failed',
                'message' => $e->getMessage(),
            ], 500);
        }
    }


    public function exportSubscriptionData(Request $request)
    {
        try {
            $user = Auth::user();

            $startDate = $request->startDate ?? '2020-01-01';
            $endDate = $request->endDate ?? '3000-01-01';
            $status = $request->status ?? null;
            $plan = $request->plan;
            $duration = $request->duration;
            $limit = (int) $request->limit ?? 100000;
            $type = $request->type;


            $data = $this->superAdminRepository->subscriptionsHistory($startDate, $endDate, $status, $limit, $duration, $plan);
            $subscriptionsCollection = $data->getCollection();
            if ($type == 'csv') {
                $export = new SubscriptionExport($subscriptionsCollection);
                return Excel::download($export, 'subscriptions-from-' . $startDate . '-' . $endDate . '.csv', \Maatwebsite\Excel\Excel::CSV);
            }
            return Excel::download(new SubscriptionExport($subscriptionsCollection), 'subscriptions-from-' . $startDate . '-' . $endDate . '.xlsx');
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failed',
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    public function exportBillingData(Request $request)
    {
        try {
            $user = Auth::user();

            $startDate = $request->startDate ?? '2020-01-01';
            $endDate = $request->endDate ?? '3000-01-01';
            $status = $request->status ?? null;
            $limit = (int) $request->limit ?? 100000;
            $type = $request->type;


            $data = $this->superAdminRepository->billingHistory($startDate, $endDate, $status, $limit);
            $billingCollection = $data->getCollection();
            if ($type == 'csv') {
                $export = new BillingExport($billingCollection);
                return Excel::download($export, 'billings-from-' . $startDate . '-' . $endDate . '.csv', \Maatwebsite\Excel\Excel::CSV);
            }
            return Excel::download(new BillingExport($billingCollection), 'billings-from-' . $startDate . '-' . $endDate . '.xlsx');
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failed',
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    public function exportAdminPayrollData(Request $request)
    {
        try {
            $user = Auth::user();

            $startDate = $request->startDate ?? '2020-01-01';
            $endDate = $request->endDate ?? '3000-01-01';
            $status = $request->status;
            $limit = (int) $request->limit ?? 100000;
            $paygroup = $request->payGroup;
            $type = $request->type;


            $data = $this->superAdminRepository->payrollHistory($startDate, $endDate, $status, $limit, $paygroup);
            $payrolls = $data->getCollection();
            if ($type == 'csv') {
                $export = new AdminPayrollExport($payrolls);
                return Excel::download($export, 'payrolls-from-' . $startDate . '-' . $endDate . '.csv', \Maatwebsite\Excel\Excel::CSV);
            }
            return Excel::download(new AdminPayrollExport($payrolls), 'payrolls-from-' . $startDate . '-' . $endDate . '.xlsx');
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failed',
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    public function exportOrganisationData(Request $request)
    {
        try {
            $user = Auth::user();

            $startDate = $request->startDate ?? '2020-01-01';
            $endDate = $request->endDate ?? '3000-01-01';
            $status = $request->status;
            $limit = (int) $request->limit ?? 100000;
            $type = $request->type;


            $data = $this->superAdminRepository->getAllOrg($startDate, $endDate, $status, $limit);
            $organisation = $data->getCollection();
            if ($type == 'csv') {
                $export = new OrganisationExport($organisation);
                return Excel::download($export, 'organisations-from-' . $startDate . '-' . $endDate . '.csv', \Maatwebsite\Excel\Excel::CSV);
            }
            return Excel::download(new OrganisationExport($organisation), 'organisations-from-' . $startDate . '-' . $endDate . '.xlsx');
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failed',
                'message' => $e->getMessage(),
            ], 500);
        }
    }
    public function exportTeamAttendance(Request $request)
    {
        try {
            $user = Auth::user();
            //check if org exists
            $org = $this->organisationRepository->findById($user->organisation_id);
            if (!$org || $org->is_active === false) {

                return response()->json([
                    'status' => 'failed',
                    'message' => 'You cannot access attendance data at the moment',
                ], 400);
            }
            $startDate = $request->startDate ?? '2020-01-01';
            $endDate = $request->endDate ?? '3000-01-01';
            $type = $request->type;
            $employeeId = $request->employeeId;
            $managerId = $user->id;
            $type = $request->type;
            $clockIn = $request->clockIn;
            $clockOut = $request->clockOut;
            $lateTime = $request->lateTime;
            $overTime = $request->overTime;

            $data = $this->organisationRepository->getTeamEmployeeAttendance($startDate, $endDate, $org->id, $managerId, $employeeId, $clockOut, $clockIn, $lateTime, $overTime);
            $attendance = $data->getCollection();
            if ($type == 'csv') {
                $export = new TeamAttendanceExport($attendance);
                return Excel::download($export, 'team-attendance-from-' . $startDate . '-' . $endDate . '.csv', \Maatwebsite\Excel\Excel::CSV);
            }
            return Excel::download(new TeamAttendanceExport($attendance), 'team-attendance-from-' . $startDate . '-' . $endDate . '.xlsx');
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failed',
                'message' => $e->getMessage(),
            ], 500);
        }
    }
}
