<?php

namespace App\Http\Controllers;

use App\Models\Classe;
use App\Models\Fee_structure;
use App\Models\Generate_salary_detail;
use App\Models\School_setting;
use App\Models\Staff_member;
use App\Models\Student;
use App\Models\Student_fee;
use App\Models\Student_fee_detail;
use App\Models\Transaction;
use App\Models\Transaction_detail;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;


class FeeGenerateController extends Controller
{
    public function index(Request $request)
    {
        $stdList = Student::select('head_code', 'student_name', 'reg_no')->where('status', 'active')->get();
        $classList = Classe::select('id', 'name')->get();
        $query = Student_fee::with(['student', 'Student_fee_detail', 'class', 'section'])
            ->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 . '%')
                    ->orWhere('class_id', 'like', '%' . $request->search . '%');
            });
        }

        if ($request->filled('class_search')) {
            $query->where(function ($q) use ($request) {
                $q->where('class_id', $request->class_search);
            });
        }


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

        if ($request->ajax()) {
            return view('stdFeeMgt.partialFeeGen', compact('fees'))->render();
        }

        return view('stdFeeMgt.feeGenReport', compact('fees', 'stdList', 'classList'));
    }

 

    public function feeGeneratedReportPdf(Request $request)
    {
        $query = Student_fee::with(['student', 'Student_fee_detail', 'class', 'section'])
            ->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 . '%')
                    ->orWhere('class_id', 'like', '%' . $request->search . '%');
            });
        }

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

        if ($request->filled('from_date') && $request->filled('to_date')) {
            $query->whereBetween('date', [$request->from_date, $request->to_date]);
        }

        $fees = $query->get();

        $pdf = Pdf::loadView('stdFeeMgt.pdfFeeGeneratedReport', compact('fees'))->setPaper('a4', 'landscape');

        return $pdf->download('Fee_Generated_Report.pdf');
    }


    public function generate_student_fee(Request $request)
    {
        $fees = $request->input('fees', []);
        $total_amount = 0;
        $selectedFees = [];
        $feetypes = [];

        foreach ($fees as $type => $data) {
            // Only include if checkbox was checked
            if (isset($data['active'])) {
                $amount = floatval($data['amount'] ?? 0);
                $selectedFees[$type] = $amount;
                $feetypes[$type] = $type;
                $total_amount += $amount;
            }
        }


        DB::beginTransaction();
        $billingMonth = $request->year . '-' . str_pad($request->month, 2, '0', STR_PAD_LEFT);
        try {
            if ($request->feeMode == 'single') {

                $student = Student::with('latestAdmission')->find($request->student_id);
                $admission = $student->latestAdmission;
                $fee_structures = Fee_structure::where('class_id', $admission->class_id)->get();


                // Check if fee record already exists for this student and billing month
                $existingFee = Student_fee::where('student_id', $request->student_id)
                    ->where('billing_month', $billingMonth)
                    ->exists();

                if ($existingFee) {

                    // Sample Data (Replace with dynamic data)
                $data = [
                    'school_name' => School_setting::where('setting_key', 'school_name')->first()->setting_value,
                    'school_address' => School_setting::where('setting_key', 'school_address')->first()->setting_value,
                    'student_name' => $request->student_name,
                    'academic_year' => School_setting::where('setting_key', 'academic_year')->first()->setting_value,
                    'class' =>   $request->student_class_name,
                    'section' => $request->student_section_name,
                    'billing_month' => $request->month . ' ' . $request->year,
                    'due_date' => ($request->dueDate),
                    'receipt_no' => 'REC-'.date('Y').'-'.date('m').'-'.Str::random(5),
                    'date' => now()->format('M d, Y'),
                    'fees' => $fees,
                ];
                // Generate PDF
                $pdf = Pdf::loadView('stdFeeRecipt.feeRecipt', compact('data'));

                return $pdf->download('fee_receipt.pdf');

                 //   return redirect()->back()->with('error', 'Receipt already generated for this month.');
                }

                $std = student::where('id', $request->student_id)->first();
                $student_fee = Student_fee::create([
                    'student_id'   => $request->student_id,
                    'head_code'    => $std->head_code,
                    'reg_no'       => $std->reg_no,
                    'class_id'     => $admission->class_id ?? null,  // Get from latest admission
                    'section_id'   => $admission->section_id ?? null, // Get from latest admission
                    'description'  => 'Monthly fee generate slip',
                    'status'       => 'unpaid',
                    'discount'     => NULL,
                    'total_amount' => $total_amount,
                    'date'         => date('Y-m-d'),
                    'billing_month' => $billingMonth,
                ]);


                // Create or Update fee details

                $academicYear = School_setting::where('setting_key', 'academic_year')->first()->setting_value;

                Student_fee_detail::create(array_merge([
                    'student_id'    => $student->id,
                    'head_code'    => $std->head_code,
                    'reg_no'       => $std->reg_no,
                    'class_id'      => $admission->class_id,
                    'std_fee_id'    => $student_fee->id,
                    'academic_year' => $academicYear,
                    'billing_month' => $billingMonth,
                ], $selectedFees));



                //Insert Transaction Data
                $transaction = Transaction::create([
                    'transaction_type' => 'monthly_fee',
                    'trans_type_id' => $student_fee->id,
                    'transaction_date' => date('Y-m-d'),
                    'total_amount'     => ($total_amount),
                    'remarks'          => "Fee Generate",
                ]);

                //Debit balance on student
                Transaction_detail::create([
                    'transaction_id'   => $transaction->id,
                    'coa_id'           =>  $std->head_code,
                    'transaction_type' => 'monthly_fee',
                    'credit'           => 0,
                    'debit'            => ($total_amount ?? 0),
                ]);

                //Credit balance from income through head code is 20400
                Transaction_detail::create([
                    'transaction_id'   => $transaction->id,
                    'coa_id'           => '20400',
                    'transaction_type' => 'monthly_fee',
                    'credit'           => ($total_amount ?? 0),
                    'debit'            => 0,
                ]);

                // Do work for remaining rupees of all students. we manage
                // accounts for it is receivable
                // head code for receivable is 20600
                Transaction_detail::create([
                    'transaction_id'   => $transaction->id,
                    'coa_id'           => '20600',
                    'transaction_type' => 'monthly_fee',
                    'credit'           => 0,
                    'debit'            => ($total_amount ?? 0),
                ]);

                DB::commit();

                // Sample Data (Replace with dynamic data)
                $data = [
                    'school_name' => School_setting::where('setting_key', 'school_name')->first()->setting_value,
                    'school_address' => School_setting::where('setting_key', 'school_address')->first()->setting_value,
                    'student_name' => $request->student_name,
                    'academic_year' => School_setting::where('setting_key', 'academic_year')->first()->setting_value,
                    'class' =>   $request->student_class_name,
                    'section' => $request->student_section_name,
                    'billing_month' => $request->month . ' ' . $request->year,
                    'due_date' => ($request->dueDate),
                    'receipt_no' => 'REC-'.date('Y').'-'.date('m').'-'.Str::random(5),
                    'date' => now()->format('M d, Y'),
                    'fees' => $fees,
                ];
                // Generate PDF
                $pdf = Pdf::loadView('stdFeeRecipt.feeRecipt', compact('data'));

                return $pdf->download('fee_receipt.pdf');
            }
            if ($request->feeMode == 'class') {

                $students = Student::with(['latestAdmission'])
                    ->where('status', 'active')
                    ->whereHas('latestAdmission', function ($query) use ($request) {
                        $query->where('class_id', $request->class)
                            ->where('section_id', $request->section);
                    })->get();

                $countStudent = 0;

                foreach ($request->fees as $feeId => $data) {
                    if (isset($data['active']) && isset($data['type'])) {
                       echo $selectedColumns[] = $data['type'];
                    }
                }

 
                foreach ($students as $student) {
                    $fee = DB::table('student_assign_fees')
                        ->where('student_id', $student->id)
                        ->first();

                    if (!$fee) {
                        continue; // Skip student if no fee record
                    }

                    $feeArray = collect((array) $fee)
                        ->except(['id', 'student_id', 'created_at', 'updated_at']) // Exclude unnecessary/unsafe fields
                        ->only($selectedColumns)
                        ->toArray();

                    $totalFee = collect($feeArray)->only($selectedColumns)->sum();            



                    $countStudent++;
                    $academicYear = School_setting::where('setting_key', 'academic_year')->first()->setting_value;

                    // Create Student Fee Entry
                    $student_fee = Student_fee::create([
                        'student_id'   => $student->id,
                        'head_code'    => $student->head_code,
                        'reg_no'       => $student->reg_no,
                        'class_id'     =>  $request->class,
                        'section_id'   =>  $request->section,
                        'description'  => 'Monthly fee generate slip',
                        'status'       => 'unpaid',
                        'discount'     => NULL,
                        'total_amount' => $totalFee,
                        'date'         => date('Y-m-d'),
                        'billing_month' => $billingMonth,
                    ]);

                    // Insert detail row with all fee columns
                    Student_fee_detail::create(array_merge([
                        'student_id'    => $student->id,
                        'head_code'     => $student->head_code,
                        'reg_no'        => $student->reg_no,
                        'class_id'      => $request->class,
                        'std_fee_id'    => $student_fee->id,
                        'academic_year' => $academicYear,
                        'billing_month' => $billingMonth,
                    ], $feeArray));


                    $academicYear = School_setting::where('setting_key', 'academic_year')->first()->setting_value;

                    // Insert Transaction
                    $transaction = Transaction::create([
                        'transaction_type' => 'monthly_fee',
                        'trans_type_id' => $student_fee->id,
                        'transaction_date' => date('Y-m-d'),
                        'total_amount'     => $totalFee,
                        'remarks'          => "Fee Generate",
                    ]);

                    // Debit on student
                    Transaction_detail::create([
                        'transaction_id'   => $transaction->id,
                        'coa_id'           => $student->head_code,
                        'transaction_type' => 'monthly_fee',
                        'credit'           => 0,
                        'debit'            => $totalFee ?? 0,
                    ]);


                    //Credit balance from income through head code is 20400
                    Transaction_detail::create([
                        'transaction_id'   => $transaction->id,
                        'coa_id'           => '20400',
                        'transaction_type' => 'monthly_fee',
                        'credit'           => $totalFee ?? 0,
                        'debit'            => 0,
                    ]);

                    // Do work for remaining rupees of all students. we manage
                    // accounts for it is receivable
                    // head code for receivable is 20600
                    Transaction_detail::create([
                        'transaction_id'   => $transaction->id,
                        'coa_id'           => '20600',
                        'transaction_type' => 'monthly_fee',
                        'credit'           => 0,
                        'debit'            => ($totalFee ?? 0),
                    ]);
                }
            }

            DB::commit();
            return redirect()->back()->with('success', 'Total ' . $countStudent . ' Student Fee Generated successfully!');
        } catch (\Exception $e) {
            DB::rollBack();

            Log::error('Student Fee Generation Failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return redirect()->back()->with('error', 'Failed to generate student fee: ' . $e->getMessage());
        }
    }
}
