@extends('admin.layout.main')

@section('admin')
<div class="min-h-screen bg-gray-50 dark:bg-dark-primary">
    <!-- Main Content -->
    <div class="py-3">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Payment Form -->
            <div class="lg:col-span-2">
                <div class="bg-white dark:bg-dark-secondary rounded shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                    <div class="bg-gradient-to-r from-emerald-50 to-green-50 dark:from-emerald-900/20 dark:to-green-900/20 px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                        <h2 class="text-lg font-semibold text-gray-900 dark:text-white">Payment Information</h2>
                        <p class="text-sm text-gray-500 dark:text-gray-400">Add payment for the project</p>
                    </div>
                    <div class="p-6">
                        <form action="{{ route('admin.payments.store') }}" method="POST" id="paymentForm">
                            @csrf
                            <input type="hidden" name="project_id" value="{{ $project->id }}">

                            <!-- Payment Type Selection -->
                            <div class="mb-6">
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">Payment Type</label>
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <label class="relative flex cursor-pointer">
                                        <input type="radio" name="payment_type" value="full" class="sr-only" checked>
                                        <div class="payment-option flex-1 p-4 border-2 border-gray-200 dark:border-gray-600 rounded-lg transition-all duration-200 hover:border-emerald-500 dark:hover:border-emerald-500">
                                            <div class="flex items-center">
                                                <div class="flex-shrink-0 h-8 w-8 bg-emerald-500 rounded-full flex items-center justify-center mr-3">
                                                    <i class="fas fa-check text-white text-sm"></i>
                                                </div>
                                                <div>
                                                    <h3 class="text-sm font-semibold text-gray-900 dark:text-white">Full Payment</h3>
                                                    <p class="text-xs text-gray-500 dark:text-gray-400">Pay the full remaining amount</p>
                                                </div>
                                            </div>
                                        </div>
                                    </label>
                                    <label class="relative flex cursor-pointer">
                                        <input type="radio" name="payment_type" value="partial" class="sr-only">
                                        <div class="payment-option flex-1 p-4 border-2 border-gray-200 dark:border-gray-600 rounded-lg transition-all duration-200 hover:border-emerald-500 dark:hover:border-emerald-500">
                                            <div class="flex items-center">
                                                <div class="flex-shrink-0 h-8 w-8 bg-blue-500 rounded-full flex items-center justify-center mr-3">
                                                    <i class="fas fa-money-bill-wave text-white text-sm"></i>
                                                </div>
                                                <div>
                                                    <h3 class="text-sm font-semibold text-gray-900 dark:text-white">Partial Payment</h3>
                                                    <p class="text-xs text-gray-500 dark:text-gray-400">Pay a specific amount</p>
                                                </div>
                                            </div>
                                        </div>
                                    </label>
                                </div>
                            </div>

                            <!-- Amount Field -->
                            <div class="mb-6">
                                <label for="amount" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                    Amount
                                </label>
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <span class="text-gray-500 dark:text-gray-400">SR</span>
                                    </div>
                                    <input 
                                        type="number" 
                                        name="amount" 
                                        id="amount"
                                        step="0.01"
                                        min="0"
                                        max="{{ ($project->serviceRequest->total_price ?? 0) - ($project->amount_paid ?? 0) }}"
                                        class="pl-10 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-emerald-500 focus:border-emerald-500 dark:bg-gray-700 dark:text-white"
                                        placeholder="0.00"
                                        required
                                    >
                                </div>
                                <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                                    Maximum amount: <span id="maxAmount">{{ number_format(($project->serviceRequest->total_price ?? 0) - ($project->amount_paid ?? 0), 2) }} SR</span>
                                </p>
                            </div>
                            <!-- Notes -->
                            <div class="mb-6">
                                <label for="notes" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                    Notes (Optional)
                                </label>
                                <textarea 
                                    name="notes" 
                                    id="notes"
                                    rows="3"
                                    class="block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-emerald-500 focus:border-emerald-500 dark:bg-gray-700 dark:text-white"
                                    placeholder="Add any additional notes about this payment"
                                ></textarea>
                            </div>

                            <!-- Submit Button -->
                            <div class="flex justify-end space-x-3">
                                <a href="{{ route('admin.project.show.index', $project->id) }}" 
                                   class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-dark-secondary hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors">
                                    Cancel
                                </a>
                                <button 
                                    type="submit"
                                    class="px-6 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-gradient-to-r from-emerald-500 to-green-600 hover:from-emerald-600 hover:to-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500 transition-all flex items-center"
                                >
                                    <i class="fas fa-check-circle mr-2"></i>
                                    Create Payment & Generate Invoice
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Project Summary -->
            <div class="space-y-6">
                <!-- Financial Summary -->
                <div class="bg-white dark:bg-dark-secondary rounded shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                    <div class="bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-900/20 dark:to-indigo-900/20 px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                        <h2 class="text-lg font-semibold text-gray-900 dark:text-white">Financial Summary</h2>
                    </div>
                    <div class="p-6">
                        <div class="space-y-4">
                            <div class="flex justify-between items-center">
                                <span class="text-sm font-medium text-gray-500 dark:text-gray-400">Total Amount:</span>
                                <span class="text-sm font-bold text-gray-900 dark:text-white">
                                    {{ number_format($project->serviceRequest->total_price ?? 0, 2) }} SR
                                </span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="text-sm font-medium text-gray-500 dark:text-gray-400">Paid Amount:</span>
                                <span class="text-sm font-bold text-green-600 dark:text-green-400">
                                    {{ number_format($project->amount_paid ?? 0, 2) }} SR
                                </span>
                            </div>
                            <div class="flex justify-between items-center pt-3 border-t border-gray-200 dark:border-gray-600">
                                <span class="text-sm font-medium text-gray-500 dark:text-gray-400">Pending Amount:</span>
                                <span class="text-sm font-bold text-orange-600 dark:text-orange-400">
                                    {{ number_format(($project->serviceRequest->total_price ?? 0) - ($project->amount_paid ?? 0), 2) }} SR
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Client Information -->
                <div class="bg-white dark:bg-dark-secondary rounded shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                    <div class="bg-gradient-to-r from-orange-50 to-amber-50 dark:from-orange-900/20 dark:to-amber-900/20 px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                        <h2 class="text-lg font-semibold text-gray-900 dark:text-white">Client Information</h2>
                    </div>
                    <div class="p-6">
                        @php
                            $contactInfo = is_array($project->serviceRequest->contact_info)
                                ? $project->serviceRequest->contact_info
                                : json_decode($project->serviceRequest->contact_info, true) ?? [];
                        @endphp
                        <div class="space-y-3">
                            <div>
                                <p class="text-sm font-medium text-gray-900 dark:text-white">
                                    {{ $contactInfo['name'] ?? ($project->user->name ?? 'N/A') }}
                                </p>
                                <p class="text-xs text-gray-500 dark:text-gray-400">
                                    {{ $contactInfo['company'] ?? 'No Company' }}
                                </p>
                            </div>
                            <div class="text-xs text-gray-500 dark:text-gray-400">
                                <p>{{ $contactInfo['email'] ?? ($project->user->email ?? 'N/A') }}</p>
                                <p>{{ $contactInfo['phone'] ?? 'N/A' }}</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Invoice Preview -->
                <div class="bg-white dark:bg-dark-secondary rounded shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                    <div class="bg-gradient-to-r from-purple-50 to-indigo-50 dark:from-purple-900/20 dark:to-indigo-900/20 px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                        <h2 class="text-lg font-semibold text-gray-900 dark:text-white">Invoice Preview</h2>
                    </div>
                    <div class="p-6">
                        <div class="text-center">
                            <i class="fas fa-receipt text-4xl text-gray-300 dark:text-gray-600 mb-3"></i>
                            <p class="text-sm text-gray-500 dark:text-gray-400">
                                Invoice will be generated automatically after payment creation
                            </p>
                            <div class="mt-3 text-xs text-gray-400 dark:text-gray-500">
                                <p>Invoice #: <span id="invoicePreview">PAY-{{ $project->id }}-{{ time() }}</span></p>
                                <p>Date: {{ date('M d, Y') }}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    .payment-option {
        transition: all 0.2s ease-in-out;
    }
    
    input[type="radio"]:checked + .payment-option {
        border-color: #10B981;
        background-color: #ECFDF5;
    }
    
    .dark input[type="radio"]:checked + .payment-option {
        border-color: #10B981;
        background-color: #064E3B20;
    }
</style>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const paymentTypeRadios = document.querySelectorAll('input[name="payment_type"]');
        const amountInput = document.getElementById('amount');
        const maxAmountSpan = document.getElementById('maxAmount');
        
        const totalAmount = {{ $project->serviceRequest->total_price ?? 0 }};
        const paidAmount = {{ $project->amount_paid ?? 0 }};
        const pendingAmount = totalAmount - paidAmount;

        // Set full payment amount when full payment is selected
        paymentTypeRadios.forEach(radio => {
            radio.addEventListener('change', function() {
                if (this.value === 'full') {
                    amountInput.value = pendingAmount.toFixed(2);
                    amountInput.readOnly = true;
                } else {
                    amountInput.value = '';
                    amountInput.readOnly = false;
                }
            });
        });

        // Initialize with full payment selected
        amountInput.value = pendingAmount.toFixed(2);
        amountInput.readOnly = true;

        // Validate amount doesn't exceed pending amount
        amountInput.addEventListener('input', function() {
            const enteredAmount = parseFloat(this.value) || 0;
            if (enteredAmount > pendingAmount) {
                this.value = pendingAmount.toFixed(2);
                alert('Amount cannot exceed pending amount of SR' + pendingAmount.toFixed(2));
            }
        });

        // Form submission validation
        document.getElementById('paymentForm').addEventListener('submit', function(e) {
            const amount = parseFloat(amountInput.value) || 0;
            const paymentMethod = document.getElementById('payment_method').value;
            
            if (amount <= 0) {
                e.preventDefault();
                alert('Please enter a valid amount.');
                return;
            }
            
            if (!paymentMethod) {
                e.preventDefault();
                alert('Please select a payment method.');
                return;
            }
            
            if (amount > pendingAmount) {
                e.preventDefault();
                alert('Amount cannot exceed pending amount of SR' + pendingAmount.toFixed(2));
                return;
            }
        });
    });
</script>
@endsection