<?php $__env->startSection('title', 'Project Payments'); ?>

<?php $__env->startSection('content'); ?>
<div class="bg-white shadow-md rounded-lg p-6 mb-6 flex justify-between items-center">
    <div class="flex items-center space-x-3">
        <label for="entriesPerPage" class="text-sm font-medium text-gray-600">Show</label>
        <select id="entriesPerPage" class="border border-gray-300 rounded-md px-3 py-1.5 focus:ring focus:border-blue-500 text-sm">
            <option value="10" selected>10</option>
            <option value="25">25</option>
            <option value="50">50</option>
            <option value="100">100</option>
        </select>
        <span class="text-sm font-medium text-gray-600">entries</span>
    </div>
    <input type="text" id="searchInput" placeholder="Search payments..." 
        class="border border-gray-300 rounded-md px-4 py-2 w-72 focus:ring focus:border-blue-500 shadow-md text-gray-700 transition">
</div>

<div class="bg-white shadow-md rounded-lg p-6">
    <div class="flex justify-between items-center mb-5">
        <h2 class="text-2xl font-semibold text-gray-800">Project Payments</h2>
        <button onclick="openModal('addModal')" class="bg-blue-600 text-white px-5 py-2 rounded-md shadow hover:bg-blue-700 transition duration-200">
            + Add Payment
        </button>
    </div>

    <div class="overflow-x-auto">
        <table class="w-full border-collapse bg-white shadow-md rounded-lg text-left" id="paymentsTable">
        <thead>
    <tr>
        <th>Amount</th>
        <th>Commission</th>
        <th>Month-Year</th>
        <th>Account</th>
        <th>Added By</th>
        <th>Added On</th>
        <th>Action</th>
    </tr>
</thead>
            <tbody>
            <?php $__currentLoopData = $payments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $payment): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
    <tr id="payment-<?php echo e($payment->id); ?>" class="hover:bg-gray-100 transition">
        <td class="border px-5 py-3 text-gray-700">$<?php echo e(number_format($payment->payment_amount, 2)); ?></td>
        <td class="border px-5 py-3 text-gray-700"><?php echo e($payment->commission_amount); ?>%</td>
        <td class="border px-5 py-3 text-gray-700"><?php echo e(\Carbon\Carbon::parse($payment->month_year)->format('F Y')); ?></td>
        <td class="border px-5 py-3 text-gray-700"><?php echo e($payment->account->account_name ?? 'N/A'); ?> </td>
       
        <td class="border px-5 py-3 text-gray-700"><?php echo e($payment->creator->name ?? 'N/A'); ?></td>
        <td class="border px-5 py-3 text-gray-700"><?php echo e($payment->created_at->format('d M Y')); ?></td>
        <td class="border px-5 py-3 flex justify-center space-x-2">
            
            <button onclick="deletePayment(this)" data-id="<?php echo e($payment->id); ?>"
                class="bg-red-500 text-white px-3 py-1.5 rounded-md shadow hover:bg-red-600 transition">
                Delete
            </button>
        </td>
    </tr>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

            </tbody>
        </table>
    </div>

    <div class="mt-6 flex justify-end">
        <?php echo e($payments->links()); ?>

    </div>
</div>

<!-- Add/Edit Modal -->
<!-- Add/Edit Modal -->
<div id="addModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center z-50 overflow-auto">
    <div class="bg-white p-8 rounded-lg w-full max-w-xl mx-auto shadow-lg relative border-4 max-h-[90vh] overflow-y-auto"
        style="border-image-source: linear-gradient(to right, #0178bc, #00bdda);
               border-image-slice: 1;">

        <!-- Close Button -->
        <button onclick="closeModal('addModal')" class="absolute top-3 right-3 text-2xl text-gray-500 hover:text-black">&times;</button>

        <h2 class="text-2xl font-semibold mb-6 text-gray-800" id="modalTitle">Add Payment</h2>

        <form id="paymentForm" method="POST" enctype="multipart/form-data">
            <?php echo csrf_field(); ?>
            <input type="hidden" id="paymentId">
            <input type="hidden" name="project_id" value="<?php echo e($project->id); ?>">


            <!-- Amount -->
            <div class="mb-4">
                <label for="payment_amount" class="block text-sm font-medium text-gray-700"> Payment Amount (USD)</label>
                <input type="number" step="0.01" id="payment_amount	" name="payment_amount"
                    class="w-full px-4 py-2 border rounded-md focus:ring focus:border-blue-500 text-gray-900 shadow-sm">
                <span id="amountError" class="text-red-500 text-sm"></span>
            </div>

            <!-- Paid On -->
            <div class="mb-4">
                <label for="paid_on" class="block text-sm font-medium text-gray-700">Payment for Month</label>
                <input type="date" id="payment_month" name="payment_month"
                    class="w-full px-4 py-2 border rounded-md focus:ring focus:border-blue-500 text-gray-900 shadow-sm">
                <span id="paidOnError" class="text-red-500 text-sm"></span>
            </div>

            
            <!-- Commission Amount -->
            <div class="mb-4">
                <label for="commission_amount" class="block text-sm font-medium text-gray-700">Commission Amount</label>
                <input type="number" step="0.01" id="commission_amount" name="commission_amount"
                    class="w-full px-4 py-2 border rounded-md text-gray-900 shadow-sm focus:ring focus:border-blue-500">
            </div>

          

            <!-- Payment Details -->
            <div class="mb-4">
                <label for="payment_details" class="block text-sm font-medium text-gray-700">Payment Details</label>
                <textarea id="payment_details" name="payment_details" rows="3"
                    class="w-full px-4 py-2 border rounded-md text-gray-900 shadow-sm focus:ring focus:border-blue-500"></textarea>
            </div>

            <!-- Account where payment received -->
            <div class="mb-4">
                <label for="account_id" class="block text-sm font-medium text-gray-700">Account where payment received</label>
                <select id="account_id" name="account_id"
                    class="w-full px-4 py-2 border rounded-md text-gray-900 shadow-sm focus:ring focus:border-blue-500">
                    <option value="">-- Select Account --</option>
                    <?php $__currentLoopData = $accounts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $account): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($account->id); ?>"><?php echo e($account->account_name); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </select>
            </div>

            <!-- Payment Screenshot -->
            <div class="mb-4">
                <label for="payment_screenshot" class="block text-sm font-medium text-gray-700">Payment Screenshot</label>
                <input type="file" id="payment_screenshot" name="payment_screenshot"
                    accept=".jpg,.jpeg,.png,.gif,.pdf"
                    class="w-full px-4 py-2 border rounded-md focus:ring focus:border-blue-500 text-gray-900 shadow-sm">
            </div>

            <!-- Buttons -->
            <div class="flex justify-end space-x-3 mt-6">
                <button type="button" onclick="closeModal('addModal')" 
                    class="px-4 py-2 bg-gray-500 text-white rounded-md shadow hover:bg-gray-600 transition">
                    Cancel
                </button>
                <button type="submit" 
                    class="px-4 py-2 bg-blue-600 text-white rounded-md shadow hover:bg-blue-700 transition">
                    Save
                </button>
            </div>
        </form>
    </div>
</div>


<!-- Success Modal -->
<div id="successModal" class="fixed inset-0 bg-gray-900 bg-opacity-50 hidden flex items-center justify-center">
    <div class="bg-white p-6 rounded-lg w-96 text-center">
        <h2 class="text-lg font-bold text-green-600">Success!</h2>
        <p id="successMessage" class="mt-2"></p>
        <button onclick="closeSuccessModal()" class="mt-4 px-4 py-2 bg-blue-500 text-white rounded">OK</button>
    </div>
</div>

<script>
document.getElementById('paymentForm').addEventListener('submit', function (event) {
    event.preventDefault();

    let formData = new FormData(this);
    let paymentId = document.getElementById('paymentId').value;

    if (paymentId) {
        formData.append('_method', 'PUT');
    }

    let url = paymentId ? `/project_payments/${paymentId}` : '/project_payments';

    fetch(url, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            'Accept': 'application/json'
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showSuccessModal(data.success);
        } else {
            displayErrors(data.errors);
        }
    })
    .catch(error => console.error('Error:', error));
});

function displayErrors(errors) {
    document.getElementById('projectNameError').innerText = errors.project_name ? errors.project_name[0] : '';
    document.getElementById('amountError').innerText = errors.amount ? errors.amount[0] : '';
    document.getElementById('paidOnError').innerText = errors.paid_on ? errors.paid_on[0] : '';
}

function openModal(id) {
    document.getElementById(id).classList.remove('hidden');
}

function closeModal(id) {
    document.getElementById(id).classList.add('hidden');
}

function showSuccessModal(message) {
    document.getElementById("successMessage").innerText = message;
    document.getElementById("successModal").classList.remove("hidden");
}

function closeSuccessModal() {
    document.getElementById("successModal").classList.add("hidden");
    location.reload(); 
}

function editPayment(id) {
    fetch(`/project_payments/${id}/edit`)
        .then(res => res.json())
        .then(data => {
            document.getElementById('modalTitle').innerText = 'Edit Payment';
            document.getElementById('paymentId').value = data.id;
            document.getElementById('project_name').value = data.project_name;
            document.getElementById('amount').value = data.amount;
            document.getElementById('paid_on').value = data.paid_on;
            openModal('addModal');
        });
}

function deletePayment(button) {
    let paymentId = button.getAttribute('data-id');

    if (!confirm('Are you sure you want to delete this payment?')) return;

    fetch(`/project_payments/${paymentId}`, {
        method: 'DELETE',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        }
    })
    .then(() => {
        document.getElementById(`payment-${paymentId}`).remove();
        alert('Payment deleted successfully!');
    });
}

document.addEventListener("DOMContentLoaded", function () {
    let searchInput = document.getElementById("searchInput");
    let entriesSelect = document.getElementById("entriesPerPage");
    let table = document.querySelector("table tbody");
    let rows = table.getElementsByTagName("tr");

    function filterTable() {
        let searchText = searchInput.value.toLowerCase();
        Array.from(rows).forEach(row => {
            let textContent = row.innerText.toLowerCase();
            row.style.display = textContent.includes(searchText) ? "" : "none";
        });
    }

    function updateEntriesPerPage() {
        let numEntries = parseInt(entriesSelect.value);
        let totalRows = rows.length;
        Array.from(rows).forEach((row, index) => {
            row.style.display = index < numEntries ? "" : "none";
        });
    }

    searchInput.addEventListener("keyup", filterTable);
    entriesSelect.addEventListener("change", updateEntriesPerPage);
    updateEntriesPerPage();
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.dashboard', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\xampp\htdocs\crm\resources\views/project_payments/index.blade.php ENDPATH**/ ?>