@extends('layouts.nav')
@section('title')
Ageing Analysis
@endsection
@section('content')

<style>
    .form-container {
        width: 80%;
        margin: 0 auto;
        padding: 20px;
        background: #ffffff;
        border-radius: 8px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
    .form-header {
        text-align: center;
        margin-bottom: 20px;
    }
    .form-header h2 {
    }
    .form-section {
        margin-bottom: 20px;
    }
    .form-section h3 {
        margin-bottom: 10px;
    }
    .form-group {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    .form-group label {
        margin-bottom: 5px;
        width: 10%;
    }
    .form-group input,
    .form-group select {
        width: 50%;
        padding: 3px;
        border: 1px solid #ddd;
        border-radius: 4px;
    }
    .form-group input[type="radio"] {
        width: auto;
    }
    .form-group .radio-label {
        display: inline-block;
        margin-right: 20px;
    }
    .dynamic-fields {
        margin-top: 10px;
    }
    .form-footer {
        text-align: center;
    }
    .btn {
        padding: 10px 20px;
        color: #fff;
        background: #007BFF;
        border: none;
        border-radius: 5px;
        cursor: pointer;
    }
    .btn:hover {
        background: #0056b3;
    }
    .table-container {
        margin-top: 20px;
    }
    .table-container table {
        width: 100%;
        border-collapse: collapse;
    }
    .table-container th,
    .table-container td {
        padding: 10px;
        border: 1px solid #ddd;
        text-align: left;
    }
    .btn-circle {
    width: 30px;
    height: 30px;
    padding: 6px 0;
    border-radius: 50%;
    text-align: center;
    font-size: 12px;
    line-height: 1.42857;
    display: inline-flex;
    justify-content: center;
    align-items: center;
}

.btn-edit {
    background: #450DD4FF;
    color: #fff;
    border: none;
    cursor: pointer;
}

.btn-edit:hover {
    background: #1E09DEFF;
}

.btn-delete {
    background: #dc3545;
    color: #fff;
    border: none;
    cursor: pointer;
}

.btn-delete:hover {
    background: #c82333;
}
/* Modal Styles */
/* Modal Styles */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1000; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto; /* Enable scroll if needed */
    background-color: rgba(0, 0, 0, 0.5); /* Black background with opacity */
}

.modal-content {
    background-color: #fff;
    margin: 5% auto; /* 5% from the top and centered */
    padding: 20px;
    border: 1px solid #888;
    border-radius: 8px;
    width: 90%; /* Increase width to 90% of the parent container */
    max-width: 1000px; /* Increase max-width to 1000px */
    height: 90vh; /* Set height to 90% of the viewport height */
    max-height: 90vh; /* Ensure the modal doesn't exceed 90% of the viewport height */
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    overflow-y: auto; /* Enable vertical scrolling if needed */
    position: relative; /* Required for positioning the close button */
}
.close {
    position: absolute; /* Position the button absolutely within the modal */
    right: 10px; /* Move to the right side */
    top: 10px; /* Position at the top */
    background-color: #dc3545; /* Red background color */
    color: #fff; /* White text color */
    border: none; /* Remove border */
    border-radius: 20%; /* Make it circular */
    width: 40px; /* Set width */
    height: 30px; /* Set height */
    font-size: 27px; /* Adjust font size */
    font-weight: bold; /* Make the X bold */
    cursor: pointer; /* Add pointer cursor */
    display: flex; /* Center the X icon */
    align-items: center;
    justify-content: center;
    padding: 0; /* Remove padding */
}

.close:hover {
    color: #000;
}
</style>

<div class="form-container">
    <div class="form-header">
        <h3> Ageing Analysis Form</h3>
    </div>

    <form id="ageingForm" method="POST" action="{{ route('ageing.add') }}">
        @csrf
        <!-- Age Code and Description -->
        <div class="form-section">
            <h4>Age Code and Description</h4>
            <div class="form-group">
                <label for="ageCode">Age Code:</label>
                <input type="text" id="ageCode" name="ageCode" required>
            </div>
            <div class="form-group">
                <label for="description">Description:</label>
                <input type="text" id="description" name="description" required>
            </div>
        </div>

        <!-- Ageing Group Descriptions -->
        <div style="display: flex; flex-direction: row; justify-content: space-between;">
            <div class="form-section">
                <h3>Ageing Group Descriptions</h3>
                <div class="form-group">
                    <label class="radio-label">
                        <input type="radio" name="ageingGroup" value="monthly" checked> Monthly
                    </label>
                    <label class="radio-label">
                        <input type="radio" name="ageingGroup" value="daily"> Daily
                    </label>
                    <label class="radio-label">
                        <input type="radio" name="ageingGroup" value="custom"> Custom
                    </label>
                </div>
                <div class="dynamic-fields" id="ageingGroupFields"></div>
            </div>

            <!-- Ageing Intervals -->
            <div class="form-section">
                <h3>Ageing Intervals</h3>
                <div class="form-group">
                    <label class="radio-label">
                        <input type="radio" name="intervalType" value="invoiceDate"> Date of Invoice
                    </label>
                    <label class="radio-label">
                        <input type="radio" name="intervalType" value="statementDate"> Date of Statement
                    </label>
                </div>
                <div class="form-group">
                    <label class="radio-label">
                        <input type="radio" name="interval" value="30" checked> 30 Days Interval
                    </label>
                    <label class="radio-label">
                        <input type="radio" name="interval" value="7"> 7 Days Interval
                    </label>
                    <label class="radio-label">
                        <input type="radio" name="interval" value="customInterval"> Custom Interval
                    </label>
                </div>
                <div class="dynamic-fields" id="intervalFields"></div>
            </div>
        </div>

        <!-- Hidden Fields for Dynamic Data -->
        <input type="hidden" id="customAgeGroups" name="customAgeGroups">
        <input type="hidden" id="customIntervals" name="customIntervals">

        <div class="form-footer">
            <button type="submit" class="btn">Save Changes</button>
        </div>
    </form>
</div>

<!-- Table to display saved ages -->
<div class="table-container">
    <h3>Saved Ageing Analyses</h3>
    <table>
        <thead>
            <tr>
                <th>Age Code</th>
                <th>Description</th>
                <th>Ageing Group</th>
                <th>Interval Type</th>
                <th>Interval</th>
                <th>Custom Age Groups</th>
                <th>Custom Intervals</th>
                <th>Actions</th> <!-- New column for actions -->
            </tr>
        </thead>
        <tbody>
            @foreach($ageingAnalyses as $analysis)
                <tr>
                    <td>{{ $analysis->age_code }}</td>
                    <td>{{ $analysis->description }}</td>
                    <td>{{ $analysis->ageing_group }}</td>
                    <td>{{ $analysis->interval_type }}</td>
                    <td>{{ $analysis->interval }}</td>
                    <td>{{ json_encode($analysis->custom_age_groups) }}</td>
                    <td>{{ json_encode($analysis->custom_intervals) }}</td>
                    <td style="display: flex; justify-content: center; align-items: center; gap: 5px;">
                        <!-- Edit Button with Icon -->
                        <a href="{{ route('ageing.edit', $analysis->id) }}" class="btn btn-edit btn-circle">
                            <i class="fas fa-edit"></i>
                        </a>

                        <!-- Delete Button with Icon -->
                        <form action="{{ route('ageing.delete', $analysis->id) }}" method="POST" style="display: inline;">
                            @csrf
                            @method('DELETE')
                            <button type="submit" class="btn btn-delete btn-circle" onclick="return confirm('Are you sure you want to delete this record?')">
                                <i class="fas fa-trash"></i>
                            </button>
                        </form>
                    </td>
                                    </tr>
            @endforeach
        </tbody>
    </table>
</div>
    <!-- Modal Structure -->
    <div id="editModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span> <!-- Close button (X icon) -->
        <div id="modal-body">
            <!-- The edit form will be loaded here dynamically -->
        </div>
    </div>
</div>
<script>
    const ageingGroupFields = document.getElementById("ageingGroupFields");
    const intervalFields = document.getElementById("intervalFields");

    const renderAgeingGroupFields = (type) => {
        let fields;
        if (type === "monthly") {
            fields = ["Current", "30 Days", "60 Days", "90 Days", "120 Days", "150 Days", "180 Days"];
        } else if (type === "daily") {
            fields = ["Today", "1 Day", "2 Days", "3 Days", "4 Days", "5 Days", "6 Days"];
        } else {
            fields = Array.from({ length: 7 }, (_, i) => `Custom Age ${i + 1}`);
        }

        ageingGroupFields.innerHTML = fields
            .map(
                (field, index) =>
                    `<div>Age ${index + 1}: <input type="text" value="${field}" ${type === "custom" ? "" : "readonly"}></div>`
            )
            .join("");
        document.getElementById("customAgeGroups").value = JSON.stringify(fields);
    };

    const renderIntervalFields = (type) => {
        let intervals;
        if (type === "30") {
            intervals = ["30 Days", "60 Days", "90 Days", "120 Days", "150 Days", "180 Days"];
        } else if (type === "7") {
            intervals = ["7 Days", "14 Days", "21 Days", "28 Days", "35 Days", "42 Days"];
        } else {
            intervals = Array.from({ length: 6 }, (_, i) => `Custom Interval ${i + 1}`);
        }

        intervalFields.innerHTML = intervals
            .map(
                (interval, index) =>
                    `<div>Interval ${index + 1}: <input type="text" value="${interval}" ${type === "customInterval" ? "" : "readonly"}></div>`
            )
            .join("");
        document.getElementById("customIntervals").value = JSON.stringify(intervals);
    };

    // Initialize defaults
    renderAgeingGroupFields("monthly");
    renderIntervalFields("30");

    // Event listeners for dynamic changes
    document.querySelectorAll('input[name="ageingGroup"]').forEach((radio) => {
        radio.addEventListener("change", (e) => renderAgeingGroupFields(e.target.value));
    });

    document.querySelectorAll('input[name="interval"]').forEach((radio) => {
        radio.addEventListener("change", (e) => renderIntervalFields(e.target.value));
    });
</script>
<script>
    // Get the modal and close button
    const modal = document.getElementById("editModal");
    const closeBtn = document.querySelector(".close");

    // Function to open the modal and load the edit form
    function openEditModal(url) {
        fetch(url)
            .then(response => response.text())
            .then(data => {
                document.getElementById("modal-body").innerHTML = data;
                modal.style.display = "block";
            })
            .catch(error => console.error("Error loading edit form:", error));
    }

    // Function to close the modal
    function closeModal() {
        modal.style.display = "none";
    }

    // Event listener for the close button
    closeBtn.addEventListener("click", closeModal);

    // Close the modal when clicking outside of it
    window.addEventListener("click", (event) => {
        if (event.target === modal) {
            closeModal();
        }
    });

    // Attach the openEditModal function to all Edit buttons
    document.querySelectorAll(".btn-edit").forEach(button => {
        button.addEventListener("click", (event) => {
            event.preventDefault(); // Prevent the default link behavior
            const editUrl = button.getAttribute("href"); // Get the edit form URL
            openEditModal(editUrl); // Open the modal and load the form
        });
    });
</script>
@endsection
