<?php

namespace App\Http\Controllers;

use App\Models\Job_position;
use App\Models\Salary_pay;
use App\Models\Salary_pay_detail;
use App\Models\Staff_member;
use App\Models\Transaction;
use App\Models\Transaction_detail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Barryvdh\DomPDF\Facade\Pdf;

class PaySalaryController extends Controller
{
    public function indexReport(Request $request)
    {
        $staffList = Staff_member::select('head_code', 'full_name', 'registration_no')->get();
        $query = Salary_pay_detail::with(['staff_member'])
            ->orderBy('id', 'desc');


        if ($request->filled('search')) {
            $query->where(function ($q) use ($request) {
                $q->where('reg_no', 'like', '%' . $request->search . '%')
                    ->orWhere('head_code', 'like', '%' . $request->search . '%');
            });
        }

        $staffs = $query->paginate($request->get('entries', 40)); // default to 10

        if ($request->ajax()) {
            return view('salary.partialPayReport', compact('staffs'))->render();
        }

        return view('salary.paySalaryReport', compact('staffs', 'staffList'));
    }


    public function pdfStaffSalaryPayReport(Request $request)
    {
        $query = Salary_pay_detail::with(['staff_member'])->orderBy('id', 'desc');

        if ($request->filled('search')) {
            $query->where(function ($q) use ($request) {
                $q->where('reg_no', 'like', '%' . $request->search . '%')
                    ->orWhere('head_code', 'like', '%' . $request->search . '%');
            });
        }

        $staffs = $query->get(); // No pagination

        $pdf = Pdf::loadView('salary.pdfStaffSalaryPayReport', compact('staffs'))
            ->setPaper('A4', 'portrait');

        return $pdf->download('Staff-Salary-Pay-Report.pdf');
    }



    public function index(Request $request)
    {
        $input = [];
        if (!empty($request->all()) && !isset($request->all)) {
            $stafflists = Staff_member::where('status', 'active')->with('salaryStruct')->whereHas('Job_position', function ($query) use ($request) {
                $i = 0;

                foreach ($request->all() as $key => $value) {
                    if ($i == 0) {
                        $query->where('title', $key);
                    } else {
                        $query->orWhere('title', $key);
                    }
                    $i++;
                }
            })->get();
            foreach ($request->all() as $key => $value) {
                $input[] = $key;
            }
        } else {
            $stafflists = Staff_member::where('status', 'active')->with('SalaryStruct')->get();
        }
        $roles = Job_position::select('id', 'title')->get();
        $staffs = Staff_member::where('status', 'active')->select('head_code', 'full_name')->get();
        return view('salary.paySalary', compact('stafflists', 'staffs', 'roles', 'input'));
    }

    public function store(Request $request)
    {
        $selected = $request->input('select', []);
        $payAmounts = $request->input('pay_amount', []);
        $date = $request->input('date');
        $total_amount = $request->input('total_pay_input');

        DB::beginTransaction(); // Start transaction

        try {
            $pId = Salary_pay::create([
                'date' => $date,
                'total_amount' => $total_amount,
                'remarks' => "Pay Salary",
            ])->id;

            $tId = Transaction::create([
                'transaction_type' => "Pay Salary",
                'trans_type_id' => $pId,
                'transaction_date' => $date,
                'total_amount'     => $total_amount,
                'remarks'          => 'Salary Pay',
            ])->id;

            foreach ($selected as $headCode) {
                $amount = $payAmounts[$headCode] ?? 0;

                $sL = Staff_member::select('id', 'registration_no')->where('head_code', $headCode)->first();

                Salary_pay_detail::create([
                    'pay_salary_id' => $pId,
                    'staff_id' => $sL->id,
                    'head_code' => $headCode,
                    'reg_no' => $sL->registration_no,
                    'date' => $date,
                    'amount' =>  $amount,
                    'remarks' => "Pay Salary",
                ]);

                Transaction_detail::create([
                    'transaction_id'   => $tId,
                    'coa_id'           => $headCode,
                    'transaction_type' => "Pay Salary",
                    'debit'            => $amount,
                    'credit'           => 0,
                ]);
            }

            Transaction_detail::create([
                'transaction_id'   => $tId,
                'coa_id'           => '20300',
                'transaction_type' => "Pay Salary",
                'debit'            => 0,
                'credit'           => $total_amount,
            ]);

            Transaction_detail::create([
                'transaction_id'   => $tId,
                'coa_id'           => "20500",
                'transaction_type' => "Salary pay",
                'debit'            => 0,
                'credit'           => $total_amount,
            ]);

            DB::commit(); // ✅ Everything okay, commit it

            return redirect()->back()->with('success', 'Salaries paid successfully.');
        } catch (\Exception $e) {
            DB::rollBack(); // 
            return redirect()->back()->with('error', 'An error occurred while processing: ' . $e->getMessage());
        }
    }
}
