@extends('layouts.app')
@section('content')
    @include('admin.topmenu')
    @include('admin.sidebar')
    <div class="main-panel">
        <div class="content">
            <div class="page-inner">
                <div class="mt-2 mb-4">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h1 class="title1">Investment ROI Management</h1>
                            <p class="text-muted">Monitor and manage ROI calculations for all investment plans</p>
                        </div>
                        <div>
                            <button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#processROIModal">
                                <i class="fa fa-cogs"></i> Process ROI Now
                            </button>
                            <a href="{{ route('plans') }}" class="btn btn-sm btn-primary">
                                <i class="fa fa-arrow-left"></i> Back to Plans
                            </a>
                        </div>
                    </div>
                </div>

                <x-danger-alert />
                <x-success-alert />

                <!-- ROI Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card card-stats card-primary">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-5">
                                        <div class="icon-big text-center">
                                            <i class="fas fa-chart-line"></i>
                                        </div>
                                    </div>
                                    <div class="col-7 col-stats">
                                        <div class="numbers">
                                            <p class="card-category">Active Investments</p>
                                            <h4 class="card-title">{{ $stats['active_investments'] }}</h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card card-stats card-success">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-5">
                                        <div class="icon-big text-center">
                                            <i class="fas fa-dollar-sign"></i>
                                        </div>
                                    </div>
                                    <div class="col-7 col-stats">
                                        <div class="numbers">
                                            <p class="card-category">Total ROI Paid</p>
                                            <h4 class="card-title">{{ $settings->currency }}{{ number_format($stats['total_roi_paid'], 2) }}</h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card card-stats card-info">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-5">
                                        <div class="icon-big text-center">
                                            <i class="fas fa-coins"></i>
                                        </div>
                                    </div>
                                    <div class="col-7 col-stats">
                                        <div class="numbers">
                                            <p class="card-category">Total Invested</p>
                                            <h4 class="card-title">{{ $settings->currency }}{{ number_format($stats['total_invested'], 2) }}</h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card card-stats card-warning">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-5">
                                        <div class="icon-big text-center">
                                            <i class="fas fa-clock"></i>
                                        </div>
                                    </div>
                                    <div class="col-7 col-stats">
                                        <div class="numbers">
                                            <p class="card-category">Expiring Soon</p>
                                            <h4 class="card-title">{{ $stats['expiring_soon'] }}</h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Investment Plans Performance -->
                <div class="row mb-4">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Investment Plans Performance</h4>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Plan Name</th>
                                                <th>Active Investments</th>
                                                <th>Total Invested</th>
                                                <th>Total ROI Paid</th>
                                                <th>ROI Rate</th>
                                                <th>Performance</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach($planStats as $planStat)
                                                <tr>
                                                    <td>
                                                        <strong>{{ $planStat->name }}</strong>
                                                        @if($planStat->tag)
                                                            <span class="badge badge-info ml-2">{{ $planStat->tag }}</span>
                                                        @endif
                                                    </td>
                                                    <td>{{ $planStat->active_investments }}</td>
                                                    <td>{{ $settings->currency }}{{ number_format($planStat->total_invested, 2) }}</td>
                                                    <td>{{ $settings->currency }}{{ number_format($planStat->total_roi_paid, 2) }}</td>
                                                    <td>{{ $planStat->increment_amount }}% {{ $planStat->increment_interval }}</td>
                                                    <td>
                                                        @php
                                                            $performance = $planStat->total_invested > 0 ? ($planStat->total_roi_paid / $planStat->total_invested) * 100 : 0;
                                                        @endphp
                                                        <div class="progress">
                                                            <div class="progress-bar" style="width: {{ min($performance, 100) }}%">
                                                                {{ number_format($performance, 1) }}%
                                                            </div>
                                                        </div>
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Active Investments List -->
                <div class="row">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-header">
                                <div class="d-flex justify-content-between align-items-center">
                                    <h4 class="card-title">Active Investments</h4>
                                    <div class="btn-group">
                                        <button type="button" class="btn btn-sm btn-outline-secondary dropdown-toggle" data-toggle="dropdown">
                                            Filter <span class="caret"></span>
                                        </button>
                                        <div class="dropdown-menu">
                                            <a class="dropdown-item" href="?filter=all">All Investments</a>
                                            <a class="dropdown-item" href="?filter=due_roi">Due for ROI</a>
                                            <a class="dropdown-item" href="?filter=expiring">Expiring Soon</a>
                                            <a class="dropdown-item" href="?filter=high_profit">High Profit</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table id="investmentTable" class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Investor</th>
                                                <th>Plan</th>
                                                <th>Amount</th>
                                                <th>Profit Earned</th>
                                                <th>Last ROI</th>
                                                <th>Next ROI</th>
                                                <th>Expires</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach($investments as $investment)
                                                <tr>
                                                    <td>#{{ $investment->id }}</td>
                                                    <td>
                                                        @if($investment->puser)
                                                            <div class="d-flex align-items-center">
                                                                <div class="avatar avatar-sm mr-2">
                                                                    <span class="avatar-title bg-primary rounded-circle">
                                                                        {{ substr($investment->puser->name, 0, 1) }}
                                                                    </span>
                                                                </div>
                                                                <div>
                                                                    <strong>{{ $investment->puser->name }}</strong><br>
                                                                    <small class="text-muted">{{ $investment->puser->email }}</small>
                                                                </div>
                                                            </div>
                                                        @else
                                                            <span class="text-muted">User Deleted</span>
                                                        @endif
                                                    </td>
                                                    <td>
                                                        @if($investment->uplan)
                                                            <strong>{{ $investment->uplan->name }}</strong><br>
                                                            <small class="text-muted">{{ $investment->uplan->increment_amount }}% {{ $investment->uplan->increment_interval }}</small>
                                                        @else
                                                            <span class="text-muted">Plan Deleted</span>
                                                        @endif
                                                    </td>
                                                    <td>{{ $settings->currency }}{{ number_format($investment->amount, 2) }}</td>
                                                    <td>
                                                        <span class="text-success">
                                                            {{ $settings->currency }}{{ number_format($investment->profit_earned ?? 0, 2) }}
                                                        </span>
                                                    </td>
                                                    <td>
                                                        @if($investment->last_growth)
                                                            {{ $investment->last_growth->format('M j, Y H:i') }}
                                                        @else
                                                            <span class="text-muted">Never</span>
                                                        @endif
                                                    </td>
                                                    <td>
                                                        @if($investment->uplan && $investment->last_growth)
                                                            @php
                                                                $nextROI = match($investment->uplan->increment_interval) {
                                                                    'Monthly' => $investment->last_growth->addDays(30),
                                                                    'Weekly' => $investment->last_growth->addWeek(),
                                                                    'Daily' => $investment->last_growth->addDay(),
                                                                    'Hourly' => $investment->last_growth->addHour(),
                                                                    'Every 30 Minutes' => $investment->last_growth->addMinutes(30),
                                                                    'Every 10 Minutes' => $investment->last_growth->addMinutes(10),
                                                                    default => $investment->last_growth->addDay(),
                                                                };
                                                            @endphp
                                                            <span class="{{ $nextROI->isPast() ? 'text-warning' : 'text-info' }}">
                                                                {{ $nextROI->format('M j, Y H:i') }}
                                                            </span>
                                                            @if($nextROI->isPast())
                                                                <br><small class="text-warning">Due Now!</small>
                                                            @endif
                                                        @else
                                                            <span class="text-muted">N/A</span>
                                                        @endif
                                                    </td>
                                                    <td>
                                                        <span class="{{ $investment->expire_date->isPast() ? 'text-danger' : 'text-info' }}">
                                                            {{ $investment->expire_date->format('M j, Y H:i') }}
                                                        </span>
                                                        @if($investment->expire_date->diffInDays() <= 3 && !$investment->expire_date->isPast())
                                                            <br><small class="text-warning">Expiring Soon</small>
                                                        @elseif($investment->expire_date->isPast())
                                                            <br><small class="text-danger">Expired</small>
                                                        @endif
                                                    </td>
                                                    <td>
                                                        @if($investment->active == 'yes')
                                                            <span class="badge badge-success">Active</span>
                                                        @elseif($investment->active == 'expired')
                                                            <span class="badge badge-danger">Expired</span>
                                                        @else
                                                            <span class="badge badge-secondary">{{ ucfirst($investment->active) }}</span>
                                                        @endif
                                                    </td>
                                                    <td>
                                                        <div class="btn-group">
                                                            <button type="button" class="btn btn-sm btn-outline-primary dropdown-toggle" data-toggle="dropdown">
                                                                Actions
                                                            </button>
                                                            <div class="dropdown-menu">
                                                                @if($investment->active == 'yes')
                                                                    <a class="dropdown-item" href="#" onclick="processROI({{ $investment->id }})">
                                                                        <i class="fas fa-play"></i> Process ROI Now
                                                                    </a>
                                                                    <a class="dropdown-item" href="{{ route('markas', ['id' => $investment->id, 'status' => 'expired']) }}">
                                                                        <i class="fas fa-stop"></i> Mark as Expired
                                                                    </a>
                                                                @endif
                                                                @if($investment->puser)
                                                                    <a class="dropdown-item text-info" href="{{ route('user.plans', $investment->puser->id) }}">
                                                                        <i class="fas fa-eye"></i> View User Plans
                                                                    </a>
                                                                @endif
                                                                <div class="dropdown-divider"></div>
                                                                <a class="dropdown-item text-danger" href="{{ route('deleteinvestment', $investment->id) }}" onclick="return confirm('Are you sure you want to delete this investment? The capital will be refunded to the user.')">
                                                                    <i class="fas fa-trash"></i> Delete Investment
                                                                </a>
                                                            </div>
                                                        </div>
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>

                                <!-- Pagination -->
                                <div class="d-flex justify-content-center">
                                    {{ $investments->links() }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Process ROI Modal -->
    <div class="modal fade" id="processROIModal" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Process ROI</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <form action="{{ route('admin.process.roi') }}" method="POST">
                    @csrf
                    <div class="modal-body">
                        <div class="form-group">
                            <label>Processing Type</label>
                            <select name="type" class="form-control" required>
                                <option value="all">Process All Active Investments</option>
                                <option value="due">Process Only Due ROI</option>
                                <option value="specific">Process Specific Investment</option>
                            </select>
                        </div>
                        <div class="form-group" id="specificInvestmentGroup" style="display: none;">
                            <label>Investment ID</label>
                            <input type="number" name="investment_id" class="form-control" placeholder="Enter Investment ID">
                        </div>
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i>
                            <strong>Note:</strong> This will process ROI calculations immediately. Make sure the system settings are correct before proceeding.
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">Process ROI</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // Show/hide specific investment field
        document.querySelector('select[name="type"]').addEventListener('change', function() {
            const specificGroup = document.getElementById('specificInvestmentGroup');
            if (this.value === 'specific') {
                specificGroup.style.display = 'block';
                document.querySelector('input[name="investment_id"]').required = true;
            } else {
                specificGroup.style.display = 'none';
                document.querySelector('input[name="investment_id"]').required = false;
            }
        });

        // Process ROI for specific investment
        function processROI(investmentId) {
            if (confirm('Are you sure you want to process ROI for this investment now?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '{{ route("admin.process.roi") }}';

                const csrfToken = document.createElement('input');
                csrfToken.type = 'hidden';
                csrfToken.name = '_token';
                csrfToken.value = '{{ csrf_token() }}';

                const typeInput = document.createElement('input');
                typeInput.type = 'hidden';
                typeInput.name = 'type';
                typeInput.value = 'specific';

                const idInput = document.createElement('input');
                idInput.type = 'hidden';
                idInput.name = 'investment_id';
                idInput.value = investmentId;

                form.appendChild(csrfToken);
                form.appendChild(typeInput);
                form.appendChild(idInput);

                document.body.appendChild(form);
                form.submit();
            }
        }

        // Initialize DataTable
        $(document).ready(function() {
            $('#investmentTable').DataTable({
                order: [[0, 'desc']],
                pageLength: 25,
                responsive: true
            });
        });
    </script>
@endsection
