<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Models\Studentdetails;
use App\Models\Sponsor;
use App\Models\Payment;
use Dompdf\Dompdf;



class PaymentController extends Controller
{
   public function showPaymentForm()
{
    $sponsors = Sponsor::with('students')->get();
    $students = Studentdetails::all();

    return view('payment.create', compact('sponsors', 'students'));
}


// public function showPaymentForm()
// {
//     $sponsors = Sponsor::all();

//     // Initialize an array to store sponsor details along with associated students
//     $sponsorDetails = [];

//     // Loop through each sponsor
//     foreach ($sponsors as $sponsor) {
//         $sponsorData = $sponsor->toArray();

//         // Decode the JSON string stored in the sponsor's student_id field
//         $studentIds = json_decode($sponsor->student_id);

//         // Check if $studentIds is an array
//         if (is_array($studentIds)) {
//             // Retrieve student details based on the student IDs
//             $students = Studentdetails::whereIn('id', $studentIds)->get();
//             // Append the associated student details to the sponsor data
//             $sponsorData['students'] = $students;
//         } else {
//             // If $studentIds is not an array, set an empty array for students
//             $sponsorData['students'] = [];
//         }

//         // Add the sponsor data to the array
//         $sponsorDetails[] = $sponsorData;
//        // dd( $sponsorDetails);
//     }

//     // Pass the sponsor details array to the view
//     return view('payment.create', compact('sponsorDetails'));
// }


//     public function processPayment(Request $request)
// {
//     dd($request->all());
   
//     $validator = Validator::make($request->all(), [
//         'sponsor' => 'required',
//         'student' => 'required',
//         'method' => 'required',
//         'amount' => 'required|numeric',
        
//     ]);

    
//     if ($validator->fails()) {
        
//         return redirect()->back()->withErrors($validator)->withInput();
//     }

   
//     $validatedData = $validator->validated();
    
//     $payment = Payment::create([
//         'sponsor_id' => $validatedData['sponsor'],
//         'student_id' => $validatedData['student'],
//         'method' => $validatedData['method'],
//         'amount' => $validatedData['amount'],
        
//     ]);

   
//     return redirect()->route('payment.list')->with('success', 'Payment processed successfully!');
// }
// public function processPayment(Request $request)
// {
//      dd($request->all());
//     $validator = Validator::make($request->all(), [
//         'sponsor' => 'required',
//         'selected_students' => 'required|array',
//         //'selected_students.*' => 'exists:students,id', // Assuming 'students' is the table name for students
//         'method' => 'required',
//         'amount' => 'required|numeric',
//     ]);

//     if ($validator->fails()) {
//         return redirect()->back()->withErrors($validator)->withInput();
//     }

//     $validatedData = $validator->validated();

//     // Concatenate selected student IDs into a comma-separated string
//     $studentIds = implode(',', $validatedData['selected_students']);

//     $payment = Payment::create([
//         'sponsor_id' => $validatedData['sponsor'],
//         'student_ids' => $studentIds,
//         'method' => $validatedData['method'],
//         'amount' => $validatedData['amount'],
//     ]);

//     return redirect()->route('payment.list')->with('success', 'Payment processed successfully!');
// }

public function processPayment(Request $request)
{
    
$validator = Validator::make($request->all(), [
    'sponsor' => 'required',
    'student_id' => 'required',
    
    'method' => 'required',
    'amount' => 'required|numeric',
    'studentAmount' => 'required',
]);
//dd($validator);

if ($validator->fails()) {
   // dd(2);
    return redirect()->back()->withErrors($validator)->withInput();
}

// Get validated data
$validatedData = $validator->validated();
//dd($validatedData);

$balanceAmount = $validatedData['studentAmount']; 

// Store the payment data in the database
$payment = Payment::create([
    'sponsor_id' => $validatedData['sponsor'],
    'student_id' => $validatedData['student_id'], // Assign the comma-separated string directly
    'method' => $validatedData['method'],
    'amount' => $validatedData['amount'],
    'balance_amount' => $balanceAmount, // Store 'studentAmount' in the 'balance_amount' column
]);
// Redirect with success message
return redirect()->route('payment.list')->with('success', 'Payment processed successfully!');

}


 public function list()
{
    
    $currentDate = now();

    // Determine the start and end dates of the current academic year
    if ($currentDate->month >= 6) {
        $startYear = $currentDate->year;
    } else {
        $startYear = $currentDate->year - 1;
    }

    $startDate = "{$startYear}-06-01";
    $endDate = ($startYear + 1) . "-05-31";

    // Query payments for the current academic year
    $payments = Payment::with('sponsor')
                        ->whereBetween('created_at', [$startDate, $endDate])
                        ->get();

    // Manually retrieve related Student models
    foreach ($payments as $payment) {
        $studentIds = explode(',', $payment->student_id);
        $students = [];
        foreach ($studentIds as $studentId) {
            // Find the corresponding Student model by ID
            $student = Studentdetails::find($studentId);
            if ($student) {
                $students[] = $student;
            }
        }
        // Attach the array of related Student models to each Payment model
        $payment->students = $students;
        //dd($payment);
    }

    return view('payment.list', compact('payments'));
}


     public function edit($id)
    {
        
        $payment = Payment::findOrFail($id);
        $sponsors = Sponsor::all();
        $students = Studentdetails::all();
        return view('payment.edit', compact('payment','sponsors', 'students'));
    }
//     public function update(Request $request, $id)
//     {
//       // dd($request->all());
//        $validator = Validator::make($request->all(), [
//         'sponsor_id' => 'required',
//         'student_id' => 'required',
//         'method' => 'required',
//         'amount' => 'required',
       
//     ]);
//   //  dd($validator);
   
//     if ($validator->fails()) {
     
//         return redirect()->back()->withErrors($validator)->withInput();
//     }

   
//     $validatedData = $validator->validated();
    
//     $payment = Payment::findOrFail($id);
//     $payment->update([
//         'sponsor_id' => $validatedData['sponsor_id'],
//         'student_id' => $validatedData['student_id'],
//         'method' => $validatedData['method'],
//         'amount' => $validatedData['amount'],
       
//     ]);
//         return redirect()->back()->with('success', 'Payment updated successfully.');
//     }


public function update(Request $request, $id)
{
    $validator = Validator::make($request->all(), [
        'sponsor' => 'required',
        'student_id' => 'required',
        'method' => 'required',
        'amount' => 'required|numeric',
        'studentAmount' => 'required',
    ]);

    if ($validator->fails()) {
        return redirect()->back()->withErrors($validator)->withInput();
    }

    // Get validated data
    $validatedData = $validator->validated();

    $balanceAmount = $validatedData['studentAmount'];

    // Find the payment record by ID
    $payment = Payment::findOrFail($id);

    // Update the payment data
    $payment->sponsor_id = $validatedData['sponsor'];
    $payment->student_id = $validatedData['student_id'];
    $payment->method = $validatedData['method'];
    $payment->amount = $validatedData['amount'];
    $payment->balance_amount = $balanceAmount;

    // Save the updated payment
    $payment->save();

    // Redirect with success message
    return redirect()->route('payment.list')->with('success', 'Payment updated successfully!');
}

    public function destroy($id)
    {
       
        $payment = Payment::findOrFail($id);
        $payment->delete();
        return redirect()->back()->with('success', 'Payment deleted successfully.');
    }

    public function unmatchedStudents()
    {
        // Get unmatched student IDs
        $unmatchedStudentIds = Studentdetails::whereNotIn('id', function($query) {
                                    $query->select('student_id')
                                          ->from('payments');
                                })->pluck('id');
         $sponsors = Sponsor::all();
        $students = Studentdetails::all();
        
        return view('students.nosponserstudent', compact('unmatchedStudentIds','sponsors', 'students'));
        
        
    }

    public function getPaymentsById($id)
    {
       $payments = Payment::where('sponsor_id', $id)
                            ->with(['sponsor', 'student'])
                            ->get();
        //return response()->json($payments);
        return view('sponsor.paymentlist', compact('payments'));
    }
    
    public function invoiceview($id)
    {
        //dd(2);
       $payments = Payment::where('id', $id)
                            ->with(['sponsor', 'student'])
                            ->get();
        //dd($payments);
        return view('sponsor.invoice', compact('payments'));
    }
   
    

  public function downloadPdf($paymentId)
    {
       
        $payment = Payment::with(['sponsor', 'student'])
                  ->findOrFail($paymentId);


        // Instantiate Dompdf
        $pdf = new Dompdf();

        // Load HTML content (invoice view) into Dompdf
        $html = view('sponsor.invoices', ['payment' => $payment])->render();
        $pdf->loadHtml($html);

        // (Optional) Set paper size and orientation
        $pdf->setPaper('A4', 'portrait');

        // Render PDF
        $pdf->render();

        // Output PDF directly to the browser
        return $pdf->stream('school_fees_invoice.pdf');
    }

}
