@extends('layouts.admin')

@section('contents')
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <div class="w-full p-3 md:p-5 mb-5 bg-black text-gray-200 rounded-lg shadow" id="shares">
        <h3 class="capitalize font-extrabold mb-4 text-lg md:text-xl">
            <span class="border-b-2 border-purple-500">Share Plans</span>
        </h3>

        <div id="errorBox" class="bg-red-800 text-red-200 p-4 rounded mb-4 hidden"></div>

        <!-- Form with improved responsive grid -->
        <form id="planForm" action="{{ route('admin.share.plan.store') }}" method="POST" enctype="multipart/form-data" class="gen-form grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3 md:gap-5">
            @csrf
            <input type="hidden" name="plan_id" id="plan_id" />

            <!-- Image upload - spans full width on all screens -->
            <div class="md:col-span-2 xl:col-span-3">
                <label for="image" class="text-gray-300 block mb-2 text-sm md:text-base">Investment Image</label>
                <input type="file" name="image" id="image" accept="image/png,image/jpeg,image/webp" class="w-full bg-gray-800 text-gray-100 theme1-text-input pl-3 text-sm md:text-base" />
                <p class="text-gray-500 text-xs mt-1">PNG, JPG, WEBP. Max 2MB.</p>
                <div class="mt-3">
                    <img id="image_preview" src="" alt="Preview" class="hidden w-full max-w-xs md:max-w-md rounded border border-gray-700" />
                </div>
            </div>

            <div>
                <label for="name" class="text-gray-300 block mb-2 text-sm md:text-base">Share Name</label>
                <input name="name" id="name" class="w-full bg-gray-800 text-gray-100 theme1-text-input pl-3 text-sm md:text-base" placeholder="Enter Share Name" required />
            </div>

            <div>
                <label for="category" class="text-gray-300 block mb-2 text-sm md:text-base">Category</label>
                <input name="category" id="category" class="w-full bg-gray-800 text-gray-100 theme1-text-input pl-3 text-sm md:text-base" placeholder="e.g., Tech, Real Estate" required />
            </div>

            <div>
                <label for="risk_level" class="text-gray-300 block mb-2 text-sm md:text-base">Risk Level</label>
                <select name="risk_level" id="risk_level" class="w-full bg-gray-800 text-gray-100 theme1-text-input pl-3 text-sm md:text-base" required>
                    <option value="">Select risk</option>
                    <option value="LOW">LOW</option>
                    <option value="MEDIUM">MEDIUM</option>
                    <option value="HIGH">HIGH</option>
                </select>
            </div>

            <div>
                <label for="frequency" class="text-gray-300 block mb-2 text-sm md:text-base">Payout Frequency</label>
                <select name="frequency" id="frequency" class="w-full bg-gray-800 text-gray-100 theme1-text-input pl-3 text-sm md:text-base" required>
                    <option value="">Select frequency</option>
                    <option value="MONTHLY">MONTHLY</option>
                    <option value="QUARTERLY">QUARTERLY</option>
                    <option value="BI-ANNUALLY">BI-ANNUALLY</option>
                    <option value="ANNUALLY">ANNUALLY</option>
                </select>
            </div>

            <div>
                <label for="share_price" class="text-gray-300 block mb-2 text-sm md:text-base">Share Price ($)</label>
                <input name="share_price" id="share_price" type="number" step="0.01" class="w-full bg-gray-800 text-gray-100 theme1-text-input pl-3 text-sm md:text-base" placeholder="e.g., 100" required />
            </div>

            <div>
                <label for="dividend_yield" class="text-gray-300 block mb-2 text-sm md:text-base">Dividend Yield (%)</label>
                <input name="dividend_yield" id="dividend_yield" type="number" step="0.01" class="w-full bg-gray-800 text-gray-100 theme1-text-input pl-3 text-sm md:text-base" placeholder="e.g., 5" required />
            </div>

            <div>
                <label for="min_investment" class="text-gray-300 block mb-2 text-sm md:text-base">Min Investment ($)</label>
                <input name="min_investment" id="min_investment" type="number" step="0.01" class="w-full bg-gray-800 text-gray-100 theme1-text-input pl-3 text-sm md:text-base" placeholder="e.g., 50" required />
            </div>

            <div>
                <label for="target_amount" class="text-gray-300 block mb-2 text-sm md:text-base">Target Amount ($)</label>
                <input name="target_amount" id="target_amount" type="number" step="0.01" class="w-full bg-gray-800 text-gray-100 theme1-text-input pl-3 text-sm md:text-base" placeholder="e.g., 100000" required />
            </div>

            <div>
                <label for="raised_amount" class="text-gray-300 block mb-2 text-sm md:text-base">Raised Amount ($)</label>
                <input name="raised_amount" id="raised_amount" type="number" step="0.01" class="w-full bg-gray-800 text-gray-100 theme1-text-input pl-3 text-sm md:text-base" placeholder="e.g., 25000" />
            </div>

            <div>
                <label for="funding_progress" class="text-gray-300 block mb-2 text-sm md:text-base">Funding Progress (%)</label>
                <input name="funding_progress" id="funding_progress" type="number" step="0.01" class="w-full bg-gray-800 text-gray-100 theme1-text-input pl-3 text-sm md:text-base" placeholder="e.g., 25" />
            </div>

            <div>
                <label for="investors_count" class="text-gray-300 block mb-2 text-sm md:text-base">Investors Count</label>
                <input name="investors_count" id="investors_count" type="number" step="1" class="w-full bg-gray-800 text-gray-100 theme1-text-input pl-3 text-sm md:text-base" placeholder="e.g., 120" />
            </div>

            <div>
                <label for="rating" class="text-gray-300 block mb-2 text-sm md:text-base">Rating (0 - 5)</label>
                <input name="rating" id="rating" type="number" step="0.1" min="0" max="5" class="w-full bg-gray-800 text-gray-100 theme1-text-input pl-3 text-sm md:text-base" placeholder="e.g., 4.5" />
            </div>

            <div>
                <label for="next_payout_date" class="text-gray-300 block mb-2 text-sm md:text-base">Next Payout Date</label>
                <input name="next_payout_date" id="next_payout_date" type="date" class="w-full bg-gray-800 text-gray-100 theme1-text-input pl-3 text-sm md:text-base" />
            </div>

            <div class="md:col-span-2 xl:col-span-3">
                <label for="description" class="text-gray-300 block mb-2 text-sm md:text-base">Description</label>
                <textarea name="description" id="description" class="w-full bg-gray-800 text-gray-100 theme1-text-input pl-3 text-sm md:text-base" placeholder="Enter Description" rows="3"></textarea>
            </div>

            <div class="md:col-span-2 xl:col-span-3 flex items-center space-x-3">
                <input type="hidden" name="is_active" value="0" />
                <input type="checkbox" id="is_active" name="is_active" value="1" class="h-4 w-4">
                <label for="is_active" class="text-gray-300 text-sm md:text-base">Active</label>
            </div>

            <div class="md:col-span-2 xl:col-span-3 flex flex-col sm:flex-row gap-3 sm:gap-4 mt-4">
                <button type="submit" id="submitBtn" style="background: purple" class="w-full sm:w-auto bg-[#ff6900] hover:bg-[#ff6900] text-white px-4 py-2 rounded-full text-sm md:text-base">
                    Save Share Plan
                </button>
                <button type="button" id="cancelBtn" style="background: red" onclick="resetForm()" class="hidden w-full sm:w-auto bg-red hover:bg-red text-white px-4 py-2 rounded-full text-sm md:text-base">
                    Cancel Edit
                </button>
            </div>
        </form>

        @if(isset($plans) && $plans->count())
            <!-- Mobile Cards View (visible on small screens) -->
            <div class="mt-6 block lg:hidden">
                <h4 class="text-lg font-semibold mb-4 text-gray-300">Share Plans</h4>
                @foreach($plans as $plan)
                    <div class="bg-gray-800 rounded-lg p-4 mb-4 border border-gray-700">
                        <!-- Image and Name Header -->
                        <div class="flex items-start space-x-3 mb-3">
                            @if($plan->image_path)
                                 <img src="{{ asset($plan->image_path) }}" class="h-12 w-20 object-cover rounded border border-gray-700" alt="image">
                            @else
                                <div class="h-16 w-20 bg-gray-700 rounded border border-gray-600 flex items-center justify-center flex-shrink-0">
                                    <span class="text-gray-500 text-xs">No img</span>
                                </div>
                            @endif
                            <div class="flex-1 min-w-0">
                                <h5 class="font-semibold text-white truncate">{{ $plan->name }}</h5>
                                <p class="text-sm text-gray-400">{{ $plan->category }}</p>
                                <div class="mt-1">
                                    @if(!empty($plan->is_active))
                                        <span class="bg-green-800 text-green-200 px-2 py-1 rounded-full text-xs">Active</span>
                                    @else
                                        <span class="bg-red-800 text-red-200 px-2 py-1 rounded-full text-xs">Inactive</span>
                                    @endif
                                </div>
                            </div>
                        </div>

                        <!-- Details Grid -->
                        <div class="grid grid-cols-2 gap-3 text-sm mb-4">
                            <div>
                                <span class="text-gray-400">Price:</span>
                                <p class="text-white font-medium">${{ number_format((float)$plan->share_price, 2) }}</p>
                            </div>
                            <div>
                                <span class="text-gray-400">Yield:</span>
                                <p class="text-white font-medium">{{ $plan->dividend_yield !== null ? number_format((float)$plan->dividend_yield, 2) . '%' : 'N/A' }}</p>
                            </div>
                            <div>
                                <span class="text-gray-400">Risk:</span>
                                <p class="text-white font-medium">{{ $plan->risk_level }}</p>
                            </div>
                            <div>
                                <span class="text-gray-400">Frequency:</span>
                                <p class="text-white font-medium text-xs">{{ $plan->frequency }}</p>
                            </div>
                            <div>
                                <span class="text-gray-400">Min Investment:</span>
                                <p class="text-white font-medium">${{ number_format((float)$plan->min_investment, 2) }}</p>
                            </div>
                            <div>
                                <span class="text-gray-400">Target:</span>
                                <p class="text-white font-medium">${{ number_format((float)$plan->target_amount, 2) }}</p>
                            </div>
                            <div>
                                <span class="text-gray-400">Raised:</span>
                                <p class="text-white font-medium">${{ $plan->raised_amount !== null ? number_format((float)$plan->raised_amount, 2) : '0.00' }}</p>
                            </div>
                            <div>
                                <span class="text-gray-400">Progress:</span>
                                <p class="text-white font-medium">{{ $plan->funding_progress !== null ? number_format((float)$plan->funding_progress, 2) . '%' : 'N/A' }}</p>
                            </div>
                            <div>
                                <span class="text-gray-400">Investors:</span>
                                <p class="text-white font-medium">{{ $plan->investors_count ?? 0 }}</p>
                            </div>
                            <div>
                                <span class="text-gray-400">Rating:</span>
                                <p class="text-white font-medium">{{ $plan->rating !== null ? number_format((float)$plan->rating, 1) : 'N/A' }}</p>
                            </div>
                        </div>

                        <div class="mb-3">
                            <span class="text-gray-400 text-sm">Next Payout:</span>
                            <p class="text-white text-sm">{{ $plan->next_payout_date ? \Carbon\Carbon::parse($plan->next_payout_date)->toFormattedDateString() : 'N/A' }}</p>
                        </div>

                        <!-- Actions -->
                        <div class="flex space-x-2">
                            <button 
                                onclick="editPlan(this)" 
                                class="flex-1 bg-blue-600 hover:bg-blue-700 text-white px-3 py-2 rounded text-sm"
                                data-id="{{ $plan->id }}"
                                data-name="{{ $plan->name }}"
                                data-category="{{ $plan->category }}"
                                data-risk_level="{{ $plan->risk_level }}"
                                data-description="{{ $plan->description }}"
                                data-share_price="{{ $plan->share_price }}"
                                data-dividend_yield="{{ $plan->dividend_yield }}"
                                data-frequency="{{ $plan->frequency }}"
                                data-min_investment="{{ $plan->min_investment }}"
                                data-target_amount="{{ $plan->target_amount }}"
                                data-raised_amount="{{ $plan->raised_amount }}"
                                data-funding_progress="{{ $plan->funding_progress }}"
                                data-investors_count="{{ $plan->investors_count }}"
                                data-rating="{{ $plan->rating }}"
                                data-next_payout_date="{{ $plan->next_payout_date }}"
                                data-is_active="{{ (int) $plan->is_active }}"
                                data-image="{{ $plan->image_path ? asset($plan->image_path) : '' }}"
                            >Edit</button>

                            <a href="{{ route('admin.share.plan.delete', ['id' => $plan->id]) }}"
                               class="flex-1 bg-red-700 hover:bg-red-800 text-white px-3 py-2 rounded text-sm text-center"
                               onclick="return confirm('Delete this share plan?');">
                               Delete
                            </a>
                        </div>
                    </div>
                @endforeach
            </div>

            <!-- Desktop Table View (hidden on small screens) -->
            <div class="mt-6 hidden lg:block">
                <div class="w-full overflow-x-auto rounded-lg">
                    <table class="min-w-full w-full bg-gray-800 text-gray-200 rounded-lg text-sm">
                        <thead class="bg-gray-700">
                            <tr>
                                <th class="py-3 px-3 text-left">Image</th>
                                <th class="py-3 px-3 text-left">Name</th>
                                <th class="py-3 px-3 text-left">Category</th>
                                <th class="py-3 px-3 text-left">Price ($)</th>
                                <th class="py-3 px-3 text-left">Yield (%)</th>
                                <th class="py-3 px-3 text-left">Frequency</th>
                                <th class="py-3 px-3 text-left">Risk</th>
                                <th class="py-3 px-3 text-left">Min Inv.</th>
                                <th class="py-3 px-3 text-left">Target</th>
                                <th class="py-3 px-3 text-left">Raised</th>
                                <th class="py-3 px-3 text-left">Progress</th>
                                <th class="py-3 px-3 text-left">Investors</th>
                                <th class="py-3 px-3 text-left">Rating</th>
                                <th class="py-3 px-3 text-left">Next Payout</th>
                                <th class="py-3 px-3 text-left">Status</th>
                                <th class="py-3 px-3 text-left">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($plans as $plan)
                                <tr class="border-b border-gray-700 hover:bg-gray-700">
                                    <td class="py-3 px-3">
                                        @if($plan->image_path)
                                            <img src="{{ asset('storage/'.$plan->image_path) }}" class="h-10 w-16 object-cover rounded border border-gray-700" alt="image">
                                        @else
                                            <span class="text-gray-500 text-xs">No image</span>
                                        @endif
                                    </td>
                                    <td class="py-3 px-3 font-semibold">{{ $plan->name }}</td>
                                    <td class="py-3 px-3">{{ $plan->category }}</td>
                                    <td class="py-3 px-3">${{ number_format((float)$plan->share_price, 2) }}</td>
                                    <td class="py-3 px-3">{{ $plan->dividend_yield !== null ? number_format((float)$plan->dividend_yield, 2) . '%' : 'N/A' }}</td>
                                    <td class="py-3 px-3">{{ $plan->frequency }}</td>
                                    <td class="py-3 px-3">{{ $plan->risk_level }}</td>
                                    <td class="py-3 px-3">${{ number_format((float)$plan->min_investment, 2) }}</td>
                                    <td class="py-3 px-3">${{ number_format((float)$plan->target_amount, 2) }}</td>
                                    <td class="py-3 px-3">${{ $plan->raised_amount !== null ? number_format((float)$plan->raised_amount, 2) : '0.00' }}</td>
                                    <td class="py-3 px-3">{{ $plan->funding_progress !== null ? number_format((float)$plan->funding_progress, 2) . '%' : 'N/A' }}</td>
                                    <td class="py-3 px-3">{{ $plan->investors_count ?? 0 }}</td>
                                    <td class="py-3 px-3">{{ $plan->rating !== null ? number_format((float)$plan->rating, 1) : 'N/A' }}</td>
                                    <td class="py-3 px-3">{{ $plan->next_payout_date ? \Carbon\Carbon::parse($plan->next_payout_date)->toFormattedDateString() : 'N/A' }}</td>
                                    <td class="py-3 px-3">
                                        @if(!empty($plan->is_active))
                                            <span class="bg-green-800 text-green-200 px-2 py-1 rounded-full text-xs">Active</span>
                                        @else
                                            <span class="bg-red-800 text-red-200 px-2 py-1 rounded-full text-xs">Inactive</span>
                                        @endif
                                    </td>
                                    <td class="py-3 px-3">
                                        <div class="flex space-x-1">
                                            <button 
                                                onclick="editPlan(this)" 
                                                class="bg-blue-600 hover:bg-blue-700 text-white px-2 py-1 rounded text-xs"
                                                data-id="{{ $plan->id }}"
                                                data-name="{{ $plan->name }}"
                                                data-category="{{ $plan->category }}"
                                                data-risk_level="{{ $plan->risk_level }}"
                                                data-description="{{ $plan->description }}"
                                                data-share_price="{{ $plan->share_price }}"
                                                data-dividend_yield="{{ $plan->dividend_yield }}"
                                                data-frequency="{{ $plan->frequency }}"
                                                data-min_investment="{{ $plan->min_investment }}"
                                                data-target_amount="{{ $plan->target_amount }}"
                                                data-raised_amount="{{ $plan->raised_amount }}"
                                                data-funding_progress="{{ $plan->funding_progress }}"
                                                data-investors_count="{{ $plan->investors_count }}"
                                                data-rating="{{ $plan->rating }}"
                                                data-next_payout_date="{{ $plan->next_payout_date }}"
                                                data-is_active="{{ (int) $plan->is_active }}"
                                                data-image="{{ $plan->image_path ? asset('storage/'.$plan->image_path) : '' }}"
                                            >Edit</button>

                                            <a href="{{ route('admin.share.plan.delete', ['id' => $plan->id]) }}"
                                               class="bg-red-700 hover:bg-red-800 text-white px-2 py-1 rounded text-xs"
                                               onclick="return confirm('Delete this share plan?');">
                                               Delete
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        @else
            <div class="text-center py-8">
                <div class="bg-gray-800 rounded-lg p-6">
                    <i class="las la-chart-line text-4xl text-gray-600 mb-2"></i>
                    <p class="text-gray-400">No share plans found. Add your first plan above.</p>
                </div>
            </div>
        @endif
    </div>

    <script>
        $.ajaxSetup({
            headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
        });

        // Preview selected image
        $('#image').on('change', function() {
            const [file] = this.files;
            if (file) {
                const url = URL.createObjectURL(file);
                $('#image_preview').attr('src', url).removeClass('hidden');
            }
        });

        $('#planForm').on('submit', function(e) {
            e.preventDefault();
            const form = this;
            const formData = new FormData(form);
            const url = form.action;

            const submitBtn = $('#submitBtn');
            const orig = submitBtn.text();
            submitBtn.text('Saving...').prop('disabled', true);

            $.ajax({
                url, method: 'POST', data: formData,
                contentType: false, processData: false,
                success: res => { try { if (res && res.message) alert(res.message); } catch(_) {} location.reload(); },
                error: xhr => {
                    let box = $('#errorBox').removeClass('hidden');
                    const json = xhr.responseJSON || {};
                    const errs = json.errors || { msg: json.message || 'An error occurred' };
                    const html = '<ul class="list-disc pl-5">' +
                        Object.values(errs).map(e => `<li>• ${(Array.isArray(e) ? e[0] : e) || e}</li>`).join('') +
                        '</ul>';
                    box.html(html);
                    box[0].scrollIntoView({ behavior: 'smooth' });
                },
                complete: () => submitBtn.text(orig).prop('disabled', false)
            });
        });

        function editPlan(btn) {
            $('#name').val(btn.dataset.name || '');
            $('#category').val(btn.dataset.category || '');
            $('#risk_level').val(btn.dataset.risk_level || '');
            $('#frequency').val(btn.dataset.frequency || '');
            $('#share_price').val(btn.dataset.share_price || '');
            $('#dividend_yield').val(btn.dataset.dividend_yield || '');
            $('#min_investment').val(btn.dataset.min_investment || '');
            $('#target_amount').val(btn.dataset.target_amount || '');
            $('#raised_amount').val(btn.dataset.raised_amount || '');
            $('#funding_progress').val(btn.dataset.funding_progress || '');
            $('#investors_count').val(btn.dataset.investors_count || '');
            $('#rating').val(btn.dataset.rating || '');
            $('#next_payout_date').val(btn.dataset.next_payout_date || '');
            $('#description').val(btn.dataset.description || '');
            $('#is_active').prop('checked', btn.dataset.is_active === '1' || btn.dataset.is_active === 'true');

            // preview current image (file input cannot be set programmatically)
            if (btn.dataset.image) {
                $('#image_preview').attr('src', btn.dataset.image).removeClass('hidden');
            } else {
                $('#image_preview').attr('src', '').addClass('hidden');
            }

            $('#plan_id').val(btn.dataset.id);

            // point to update route
            $('#planForm').attr('action', "{{ url('admin/update-share-plan') }}/" + btn.dataset.id);
            $('#submitBtn').text('Update Share Plan');
            $('#cancelBtn').removeClass('hidden');
            $('#errorBox').addClass('hidden').html('');
            document.getElementById('shares').scrollIntoView({ behavior: 'smooth' });
        }

        function resetForm() {
            $('#planForm')[0].reset();
            $('#plan_id').val('');
            $('#planForm').attr('action', "{{ route('admin.share.plan.store') }}");
            $('#submitBtn').text('Save Share Plan');
            $('#cancelBtn').addClass('hidden');
            $('#errorBox').addClass('hidden').html('');
            $('#image_preview').attr('src', '').addClass('hidden');
        }
    </script>
@endsection