@extends('layouts.master')
@section('content')
<style>
    .form-container {
        width: 95%;
        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-section {
        margin-bottom: 20px;
    }
    .form-group {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 10px;
    }
    .form-group label {
        margin-bottom: 5px;
        width: 15%;
    }
    .form-group input,
    .form-group select {
        width: 50%;
        padding: 8px;
        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;
    }
    /* Success and Error Messages */
    .alert {
        padding: 15px;
        margin-bottom: 20px;
        border: 1px solid transparent;
        border-radius: 4px;
    }
    .alert-success {
        color: #3c763d;
        background-color: #dff0d8;
        border-color: #d6e9c6;
    }
    .alert-danger {
        color: #a94442;
        background-color: #f2dede;
        border-color: #ebccd1;
    }
    .card {
        border-radius: 8px;
        overflow: hidden;
        border: none;
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
    }
    .card-header {
        border-bottom: 1px solid rgba(0,0,0,0.1);
        padding: 12px 20px;
    }
    .table th {
        background-color: #f8f9fa;
    }
    .btn-back {
        text-decoration: none;
        color: #1AB9D9;
        font-weight: 500;
        display: inline-flex;
        align-items: center;
        padding: 5px 15px;
        border-radius: 4px;
        transition: all 0.3s;
    }
    .btn-back:hover {
        background-color: rgba(26, 185, 217, 0.1);
        text-decoration: none;
    }
</style>

<div class="container-fluid py-3">
    <!-- Display Success and Error Messages -->
    <div id="timeout">
        @if(session('success'))
            <div class="alert alert-success">
                {{ session('success') }}
            </div>
        @endif
        @if($errors->any())
            <div class="alert alert-danger">
                <ul>
                    @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
    </div>

    <!-- Back Link -->
    <div class="d-flex justify-content-end mb-3">
        <a href="{{ route('home') }}" class="btn-back">
            <i class="fas fa-arrow-left me-2"></i> Back to Dashboard
        </a>
    </div>

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

        <form id="ageingForm" method="POST" action="{{ route('customer_ageing.store') }}">
            @csrf
            <input type="hidden" name="id" id="ageAnalysisId" value="">
            
            <!-- 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="age_code" class="form-control" required value="{{ old('age_code') }}">
                </div>
                <div class="form-group">
                    <label for="description">Description:</label>
                    <input type="text" id="description" name="description" class="form-control" required value="{{ old('description') }}">
                </div>
            </div>

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

                <!-- Ageing Intervals -->
                <div class="form-section">
                    <h4>Ageing Intervals</h4>
                    <div class="form-group">
                        <label class="radio-label">
                            <input type="radio" name="interval_type" value="invoice_date"> Date of Invoice
                        </label>
                        <label class="radio-label">
                            <input type="radio" name="interval_type" value="statement_date" checked> 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="custom"> Custom Interval
                        </label>
                    </div>
                    <div class="dynamic-fields" id="intervalFields"></div>
                </div>
            </div>

            <div class="form-footer">
                <input type="submit" id="submitButton" class="btn btn-primary me-2" value="SUBMIT">
                <input type="reset" class="btn btn-outline-secondary" onclick="resetForm()" value="REFRESH">
            </div>
        </form>
    </div>

    <!-- Table to display saved ages -->
    <div class="table-container">
        <h3>Saved Customer Ageing Analyses</h3>
        <table class="table table-bordered table-hover">
            <thead class="table-light">
                <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 style="width:100px">Actions</th>
                </tr>
            </thead>
            <tbody>
                @foreach($ageings as $analysis)
                    <tr>
                        <td>{{ $analysis->age_code }}</td>
                        <td>{{ $analysis->description }}</td>
                        <td>{{ $analysis->group_type }}</td>
                        <td>{{ $analysis->interval_type }}</td>
                        <td>
                            @if($analysis->interval_30_days) 30 Days 
                            @elseif($analysis->interval_7_days) 7 Days 
                            @else Custom 
                            @endif
                        </td>
                        <td>
                            @php
                                $customAges = [];
                                for ($i = 1; $i <= 7; $i++) {
                                    $field = 'custom_age_' . $i;
                                    if (!empty($analysis->$field)) {
                                        $customAges[] = $analysis->$field;
                                    }
                                }
                                echo implode(', ', $customAges);
                            @endphp
                        </td>
                        <td>
                            @php
                                $customIntervals = [];
                                for ($i = 1; $i <= 6; $i++) {
                                    $field = 'custom_interval_' . $i;
                                    if (!empty($analysis->$field)) {
                                        $customIntervals[] = $analysis->$field;
                                    }
                                }
                                echo implode(', ', $customIntervals);
                            @endphp
                        </td>
                        <td class="text-center">
                            <a href="#" class="btn btn-sm btn-primary" onclick="editAgeing(event, {{ $analysis->id }})">
                                <i class="fas fa-edit"></i>
                            </a>
                            <a href="{{ route('customer_ageing.delete', ['id' => $analysis->id]) }}" class="btn btn-sm btn-danger deleteBtn">
                                <i class="fas fa-trash-alt"></i>
                            </a>
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>
    </div>
</div>

<!-- Delete Modal -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">Confirm Deletion</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                Are you sure you want to delete this ageing analysis?
            </div>
            <div class="modal-footer">
                <button id="cancelDeleteBtn" type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button id="confirmDeleteBtn" type="button" class="btn btn-danger">Delete</button>
            </div>
        </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 class="form-group">Age ${index + 1}: <input type="text" class="form-control" value="${field}" ${type === "custom" ? "" : "readonly"} name="custom_age_${index + 1}"></div>`
            )
            .join("");
    };

    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 class="form-group">Interval ${index + 1}: <input type="text" class="form-control" value="${interval}" ${type === "custom" ? "" : "readonly"} name="custom_interval_${index + 1}"></div>`
            )
            .join("");
    };

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

    // Event listeners for dynamic changes
    document.querySelectorAll('input[name="group_type"]').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));
    });

    function editAgeing(event, id) {
        event.preventDefault();
        
        // Fetch the ageing record via AJAX
        fetch(`/customer_ageing/edit/${id}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const ageing = data.data;
                    
                    // Fill the form with the ageing data
                    document.getElementById('ageAnalysisId').value = ageing.id;
                    document.getElementById('ageCode').value = ageing.age_code;
                    document.getElementById('description').value = ageing.description;
                    
                    // Set group type radio
                    document.querySelector(`input[name="group_type"][value="${ageing.group_type}"]`).checked = true;
                    renderAgeingGroupFields(ageing.group_type);
                    
                    // Set interval type radio
                    document.querySelector(`input[name="interval_type"][value="${ageing.interval_type}"]`).checked = true;
                    
                    // Set interval radio
                    let intervalValue = 'custom';
                    if (ageing.interval_30_days) intervalValue = '30';
                    else if (ageing.interval_7_days) intervalValue = '7';
                    
                    document.querySelector(`input[name="interval"][value="${intervalValue}"]`).checked = true;
                    renderIntervalFields(intervalValue);
                    
                    // Fill custom age fields
                    for (let i = 1; i <= 7; i++) {
                        const fieldName = `custom_age_${i}`;
                        const fieldValue = ageing[fieldName];
                        if (fieldValue) {
                            document.querySelector(`input[name="${fieldName}"]`).value = fieldValue;
                        }
                    }
                    
                    // Fill custom interval fields
                    for (let i = 1; i <= 6; i++) {
                        const fieldName = `custom_interval_${i}`;
                        const fieldValue = ageing[fieldName];
                        if (fieldValue) {
                            document.querySelector(`input[name="${fieldName}"]`).value = fieldValue;
                        }
                    }
                    
                    // Change form header and submit button
                    document.querySelector('.form-header h3').textContent = 'Edit Customer Ageing Analysis';
                    document.getElementById('submitButton').value = 'UPDATE';
                    document.getElementById('ageingForm').action = '{{ route("customer_ageing.update") }}';
                } else {
                    alert('Error loading ageing data');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error loading ageing data');
            });
    }

    function resetForm() {
        document.getElementById('ageAnalysisId').value = '';
        document.getElementById('ageCode').value = '';
        document.getElementById('description').value = '';
        
        // Reset radio buttons to defaults
        document.querySelector('input[name="group_type"][value="monthly"]').checked = true;
        renderAgeingGroupFields("monthly");
        
        document.querySelector('input[name="interval_type"][value="statement_date"]').checked = true;
        document.querySelector('input[name="interval"][value="30"]').checked = true;
        renderIntervalFields("30");
        
        // Reset form header and submit button
        document.querySelector('.form-header h3').textContent = 'Customer Ageing Analysis Form';
        document.getElementById('submitButton').value = 'SUBMIT';
        document.getElementById('ageingForm').action = '{{ route("customer_ageing.store") }}';
        document.getElementById('timeout').innerHTML = '';
    }

    // Delete confirmation modal logic
    document.addEventListener('DOMContentLoaded', function () {
        let deleteUrl = null;
        const modalEl = document.getElementById('deleteConfirmModal');
        const bsModal = new bootstrap.Modal(modalEl);

        // Show modal and store the delete URL
        document.querySelectorAll('.deleteBtn').forEach(btn => {
            btn.addEventListener('click', function (e) {
                e.preventDefault();
                deleteUrl = this.getAttribute('href');
                bsModal.show();
            });
        });

        // On confirm delete, redirect to delete URL
        document.getElementById('confirmDeleteBtn').addEventListener('click', function () {
            if (deleteUrl) {
                window.location.href = deleteUrl;
            }
        });

        // On cancel delete, just hide the modal
        document.getElementById('cancelDeleteBtn').addEventListener('click', function () {
            bsModal.hide();
        });
    });
</script>
@endsection