@extends('layouts.header')

@section('content')
<main class="container">
    <div class="row justify-content-center">
        <div class="col-lg-6">
            <div class="card shadow">
                <div class="card-body">
                    <h2 class="card-title text-center mb-4">Edit Payment</h2>
                    <form action="{{ route('payment.update', $payment->id) }}" method="POST" id="paymentForm">
                        @csrf
                        @method('PUT')
                        <!-- Hidden input field for sponsor ID -->
                        <input type="hidden" id="sponsorId" name="sponsor_id" value="{{ $payment->sponsor_id }}">
                        
                        <!-- Sponsor Details Section -->
                        <fieldset>
                            <legend class="fw-bold">Sponsor Details</legend>
                            <div class="mb-3">
                                <label for="sponsor" class="form-label">Select Sponsor:</label>
                                <select class="form-select" name="sponsor" id="sponsor">
                                    <option value="" selected disabled>Select Sponsor</option>
                                    @foreach($sponsors as $sponsor)
                                        <?php
                                        // Convert $sponsor->student_id to an array if it's a string
                                        $student_ids = is_array($sponsor->student_id) ? $sponsor->student_id : explode(',', $sponsor->student_id);

                                        // Initialize an empty array to store student names and fees
                                        $student_details = [];

                                        // Loop through each student ID
                                        foreach ($student_ids as $student_id) {
                                            // Fetch the student details based on student ID
                                            $student = \App\Models\Studentdetails::find($student_id);
                                            if ($student) {
                                                // If student details are found, add student name, fees, and ID to the array
                                                $student_details[] = $student->student_name . ' - ' . $student->school_fees . ' - ' . $student->id;
                                            } else {
                                                // Log the student ID that couldn't be found
                                                error_log("Student with ID $student_id not found for sponsor with ID $sponsor->id");
                                            }
                                        }

                                        // Convert the array of student names, fees, and IDs to a comma-separated string
                                        $student_details_str = implode(', ', $student_details);
                                        ?>

                                        <!-- Set the data-student attribute with the comma-separated list of student names, fees, and IDs -->
                                        <option value="{{ $sponsor->id }}"
                                                data-email="{{ $sponsor->email }}"
                                                data-phone="{{ $sponsor->phone }}"
                                                data-pan="{{ $sponsor->pan }}"
                                                data-student="{{ $student_details_str }}"
                                                data-student-id="{{ $sponsor->student_id }}"
                                                {{ old('sponsor_id', $payment->sponsor->id) == $sponsor->id ? 'selected' : '' }}> <!-- Add student_id here -->
                                            {{ $sponsor->fullName }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="email" class="form-label">Email:</label>
                                <input type="text" class="form-control" id="email" name="email" value="{{ old('email', $payment->sponsor->email) }}" readonly>
                            </div>
                            <div class="mb-3">
                                <label for="phone" class="form-label">Phone:</label>
                                <input type="text" class="form-control" id="phone" name="phone" value="{{ old('phone', $payment->sponsor->phone) }}" readonly>
                            </div>
                            <div class="mb-3">
                                <label for="pan" class="form-label">PAN:</label>
                                <input type="text" class="form-control" id="pan" name="pan" value="{{ old('pan', $payment->sponsor->pan) }}" readonly>
                            </div>
                        </fieldset>



                        <!-- Student Name, Amount, and ID Section -->
                       <!-- Student Name, Amount, and ID Section -->
<fieldset>
    <legend class="fw-bold">Student Details</legend>
    <div class="mb-3">
        <label for="studentName" class="form-label">Student Name:</label>
        <input type="text" class="form-control" id="studentName" name="studentName" value="{{ old('studentName', $payment->student->student_name) }}">
    </div>
    <div class="mb-3">
        <label for="studentAmount" class="form-label">Amount:</label>
        <input type="text" class="form-control" id="studentAmount" name="studentAmount" value="{{ old('studentAmount', $payment->amount) }}">
    </div>
    <input type="hidden" id="studentIds" name="studentIds">
</fieldset>



                        <!-- Payment Method Section -->
                        <fieldset>
                            <legend class="fw-bold">Payment Method</legend>
                            <div class="mb-3">
                                <label for="method" class="form-label">Payment Method:</label>
                                <select class="form-select" name="method" id="method">
                                    <option value="credit_card" {{ $payment->method == 'credit_card' ? 'selected' : '' }}>Credit Card</option>
                                    <option value="paypal" {{ $payment->method == 'paypal' ? 'selected' : '' }}>PayPal</option>
                                    <!-- Add more payment methods if needed -->
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="amount" class="form-label">Amount:</label>
                                <input type="text" class="form-control" id="amount" name="amount" value="{{ $payment->amount }}" required>
                            </div>
                        </fieldset>

                        <div class="text-center">
                            <button type="submit" class="btn btn-primary btn-lg">Update Payment</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</main>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>

<!-- Custom JavaScript -->
<script>
    document.addEventListener("DOMContentLoaded", function () {
        // Get references to form elements
        const sponsorSelect = document.getElementById("sponsor");
        const emailInput = document.getElementById("email");
        const phoneInput = document.getElementById("phone");
        const panInput = document.getElementById("pan");
        const studentIdInput = document.getElementById("student_id");
        const sponsorIdInput = document.getElementById("sponsorId");
        const studentNameInput = document.getElementById("studentName");
        const studentAmountInput = document.getElementById("studentAmount");
        const studentIdsInput = document.getElementById("studentIds");
        const totalFeesInput = document.getElementById("total-fees");

        // Update sponsor details and total fees on sponsor or student selection change
        sponsorSelect.addEventListener("change", updateDetails);
        document.getElementById("student").addEventListener("change", updateDetails);

        // Function to update sponsor details and total fees
        function updateDetails() {
            const selectedSponsor = sponsorSelect.options[sponsorSelect.selectedIndex];
            emailInput.value = selectedSponsor.getAttribute("data-email");
            phoneInput.value = selectedSponsor.getAttribute("data-phone");
            panInput.value = selectedSponsor.getAttribute("data-pan");
            sponsorIdInput.value = selectedSponsor.value; // Update hidden input with sponsor ID
            studentIdInput.value = selectedSponsor.getAttribute("data-student-id"); // Set student_id input value

            // Extract student details
            const studentDetails = selectedSponsor.getAttribute("data-student").split(",");
            let studentNames = [];
            let studentIds = []; // Array to store student IDs
            let totalFees = 0;

            // Loop through each student detail
            for (let i = 0; i < studentDetails.length; i++) {
                const detail = studentDetails[i].trim().split(" - ");
                studentNames.push(detail[0]);
                studentIds.push(detail[2]); // Assuming student ID is the third part of the detail
                totalFees += parseInt(detail[1]);
            }

            // Display student names, IDs, and total fees
            studentNameInput.value = studentNames.join(", ");
            studentAmountInput.value = totalFees;
            totalFeesInput.value = totalFees;
            studentIdsInput.value = studentIds.join(", "); // Set the value of student IDs input
        }
    });
</script>
@endpush