@extends('layouts.app')

@section('title', __('campaigns.campaign_details') . ': ' . $campaign->campaign_name)

@section('content')
<div class="container-fluid">
    <div class="d-flex align-items-center gap-3 mb-4">
        <div class="flex-grow-1">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-1">
                    <li class="breadcrumb-item"><a href="{{ route('operations') }}">{{ __('operations') }}</a></li>
                    <li class="breadcrumb-item active" aria-current="page">{{ __('campaigns.campaign_details') }}</li>
                </ol>
                <h4 class="fw-bold">{{ $campaign->campaign_name }}</h4>
                <div class="text-muted small">
                    ID: {{ $campaign->campaign_id ?? 'N/A' }} • Created: {{ $campaign->created_at->translatedFormat('Y-m-d h:i A') }}
                </div>
            </div>
        </div>
        <a href="{{ url()->previous() }}" class="btn btn-outline-secondary app-back-end">
            <i class="bi bi-arrow-{{ app()->getLocale() == 'ar' ? 'right' : 'left' }}"></i> {{ __('common.back') }}
        </a>
    </div>

    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white border-bottom-0 pt-4 px-4">
            <ul class="nav nav-tabs card-header-tabs" id="campaignTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="overview-tab" data-bs-toggle="tab" data-bs-target="#overview" type="button" role="tab" aria-controls="overview" aria-selected="true">
                        <i class="bi bi-info-circle me-1"></i> {{ __('campaigns.campaign_overview') }}
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="adsets-tab" data-bs-toggle="tab" data-bs-target="#adsets" type="button" role="tab" aria-controls="adsets" aria-selected="false">
                        <i class="bi bi-collection me-1"></i> {{ __('campaigns.ad_sets') }}
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="reports-tab" data-bs-toggle="tab" data-bs-target="#reports" type="button" role="tab" aria-controls="reports" aria-selected="false">
                        <i class="bi bi-bar-chart-fill me-1"></i> {{ __('campaigns.reports') }}
                    </button>
                </li>
            </ul>
        </div>
        <div class="card-body p-4">
            <div class="tab-content" id="campaignTabsContent">
                
                <!-- Overview Tab -->
                <div class="tab-pane fade show active" id="overview" role="tabpanel" aria-labelledby="overview-tab">
                    <div class="row g-4">
                        <div class="col-md-8">
                            <div class="card border-0 shadow-sm mb-4">
                                <div class="card-header bg-white py-3">
                                    <h6 class="mb-0 fw-bold">{{ __('campaigns.campaign_overview') }}</h6>
                                </div>
                                <div class="card-body">
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <label class="text-muted small">{{ __('campaigns.objective') }}</label>
                                            <div class="fw-bold">{{ __('campaigns.obj_' . $campaign->objective) }}</div>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="text-muted small">{{ __('campaigns.status') }}</label>
                                            <div>
                                                <span class="badge bg-{{ $campaign->status === 'active' ? 'success' : ($campaign->status === 'draft' ? 'secondary' : ($campaign->status === 'failed' ? 'danger' : 'warning')) }}">
                                                    {{ __('campaigns.status_' . $campaign->status) }}
                                                </span>
                                                @if($campaign->launch_status)
                                                    <span class="badge bg-info text-dark ms-2">{{ $campaign->launch_status }}</span>
                                                @endif
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="text-muted small">{{ __('campaigns.budget') }}</label>
                                            <div class="fw-bold">{{ number_format($campaign->budget_amount, 2) }} <span class="text-muted small">({{ __('campaigns.' . $campaign->budget_type . '_budget') }})</span></div>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="text-muted small">{{ __('campaigns.schedule') }}</label>
                                            <div>
                                                {{ \Carbon\Carbon::parse($campaign->start_date)->translatedFormat('Y-m-d h:i A') }}
                                                @if($campaign->end_date)
                                                    <span class="text-muted mx-1">-</span>
                                                    {{ \Carbon\Carbon::parse($campaign->end_date)->translatedFormat('Y-m-d h:i A') }}
                                                @endif
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            @if($campaign->sync_error)
                                <div class="card border-0 shadow-sm border-danger mb-4">
                                    <div class="card-header bg-danger text-white py-3">
                                        <h6 class="mb-0 fw-bold"><i class="bi bi-exclamation-triangle-fill me-2"></i> {{ __('campaigns.sync_error') }}</h6>
                                    </div>
                                    <div class="card-body text-danger">
                                        {{ $campaign->sync_error }}
                                    </div>
                                </div>
                            @endif
                        </div>
                    </div>
                </div>

                <!-- Ad Sets Tab -->
                <div class="tab-pane fade" id="adsets" role="tabpanel" aria-labelledby="adsets-tab">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="fw-bold mb-0">{{ __('campaigns.ad_sets') }}</h5>
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createAdSetModal">
                            <i class="bi bi-plus-lg me-1"></i> {{ __('campaigns.add_ad_set') }}
                        </button>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th>{{ __('campaigns.name') }}</th>
                                    <th>{{ __('campaigns.status') }}</th>
                                    <th>{{ __('campaigns.budget') }}</th>
                                    <th>{{ __('campaigns.schedule') }}</th>
                                    <th class="text-end">{{ __('common.actions') }}</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($campaign->adSets as $adSet)
                                    <tr>
                                        <td>
                                            <a href="{{ route('operations.campaigns.ad-sets.show', [$campaign->id, $adSet->id]) }}" class="text-decoration-none fw-bold">
                                                {{ $adSet->name }}
                                            </a>
                                        </td>
                                        <td><span class="badge bg-secondary">{{ $adSet->status }}</span></td>
                                        <td>{{ number_format($adSet->budget_amount, 2) }} ({{ $adSet->budget_type }})</td>
                                        <td>{{ $adSet->start_date->format('Y-m-d') }}</td>
                                        <td class="text-end">
                                            <a href="{{ route('operations.campaigns.ad-sets.show', [$campaign->id, $adSet->id]) }}" class="btn btn-sm btn-outline-primary">
                                                {{ __('common.details') }}
                                            </a>
                                        </td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="5" class="text-center py-4 text-muted">
                                            {{ __('campaigns.no_ad_sets') }}
                                        </td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Reports Tab -->
                <div class="tab-pane fade" id="reports" role="tabpanel" aria-labelledby="reports-tab">
                    <div class="alert alert-info">
                        {{ __('campaigns.reports_coming_soon') }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Create Ad Set Modal -->
<div class="modal fade" id="createAdSetModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form action="{{ route('operations.campaigns.ad-sets.store', $campaign->id) }}" method="POST">
            @csrf
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">{{ __('campaigns.new_ad_set') }}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-12">
                            <label class="form-label">{{ __('campaigns.ad_set_name') }}</label>
                            <input type="text" name="name" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('campaigns.budget_type') }}</label>
                            <select name="budget_type" class="form-select" required>
                                <option value="daily">{{ __('campaigns.daily_budget') }}</option>
                                <option value="lifetime">{{ __('campaigns.lifetime_budget') }}</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('campaigns.budget_amount') }}</label>
                            <input type="number" name="budget_amount" class="form-control" step="0.01" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('campaigns.start_date') }}</label>
                            <input type="datetime-local" name="start_date" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('campaigns.end_date') }}</label>
                            <input type="datetime-local" name="end_date" class="form-control">
                        </div>
                        
                        <h6 class="fw-bold mt-4 mb-2">{{ __('campaigns.audience') }}</h6>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('campaigns.country') }}</label>
                            <select name="country" class="form-select" id="countrySelect" required>
                                <option value="IQ">Iraq</option>
                                <option value="AE">UAE</option>
                                <option value="SA">Saudi Arabia</option>
                                <option value="US">United States</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('campaigns.gender') }}</label>
                            <select name="gender" class="form-select" required>
                                <option value="all">{{ __('campaigns.gender_all') }}</option>
                                <option value="male">{{ __('campaigns.gender_male') }}</option>
                                <option value="female">{{ __('campaigns.gender_female') }}</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">{{ __('campaigns.age_min') }}</label>
                            <input type="number" name="age_min" class="form-control" value="18" min="13" max="65" required>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">{{ __('campaigns.age_max') }}</label>
                            <input type="number" name="age_max" class="form-control" value="65" min="13" max="65" required>
                        </div>
                        
                        <div class="col-12">
                            <label class="form-label d-flex justify-content-between">
                                <span>{{ __('campaigns.interests') }}</span>
                                <button type="button" class="btn btn-sm btn-outline-primary" id="btnSuggestInterests">
                                    <i class="bi bi-magic me-1"></i> {{ __('campaigns.suggest_audience') }}
                                </button>
                            </label>
                            <div id="interestsSuggestions" class="mb-2 d-none">
                                <div class="d-flex flex-wrap gap-2" id="suggestionsList"></div>
                            </div>
                            <!-- Hidden inputs for interests will be added here -->
                            <select name="interests[]" class="form-select" multiple id="interestsSelect">
                                <!-- Options populated by JS or manual entry -->
                            </select>
                            <div class="form-text">{{ __('campaigns.hold_ctrl_select') }}</div>
                        </div>

                        <div class="col-12">
                            <label class="form-label">{{ __('campaigns.placements') }}</label>
                            <select name="placements_type" class="form-select" required>
                                <option value="automatic">{{ __('campaigns.placements_automatic') }}</option>
                                <option value="manual">{{ __('campaigns.placements_manual') }}</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ __('common.cancel') }}</button>
                    <button type="submit" class="btn btn-primary">{{ __('common.save') }}</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const btnSuggest = document.getElementById('btnSuggestInterests');
    const suggestionsDiv = document.getElementById('interestsSuggestions');
    const suggestionsList = document.getElementById('suggestionsList');
    const interestsSelect = document.getElementById('interestsSelect');
    
    btnSuggest.addEventListener('click', function() {
        // Assume we can get business type from subscription/service context or prompt user.
        // For now, let's prompt or pick a default based on previous context if available.
        // Or better, add a hidden field or just ask the user in a small prompt if needed.
        // Since we are in a modal, let's use a hardcoded value or grab from a 'business_type' if we added it.
        // But the Campaign doesn't have business_type explicitly stored as a field we can grab easily here without passing it.
        // Let's assume 'Retail' or grab from subscription service name.
        const businessType = "{{ $campaign->subscription->service->name ?? 'Business' }}";
        const location = document.getElementById('countrySelect').value;

        btnSuggest.disabled = true;
        btnSuggest.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Loading...';

        fetch("{{ route('operations.campaigns.suggest-interests') }}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({
                business_type: businessType,
                location: location
            })
        })
        .then(response => response.json())
        .then(data => {
            suggestionsList.innerHTML = '';
            if (data.interests && data.interests.length > 0) {
                data.interests.forEach(interest => {
                    const badge = document.createElement('span');
                    badge.className = 'badge bg-info text-dark border cursor-pointer';
                    badge.style.cursor = 'pointer';
                    badge.innerText = interest;
                    badge.onclick = function() {
                        const option = new Option(interest, interest, true, true);
                        interestsSelect.add(option);
                        badge.classList.remove('bg-info');
                        badge.classList.add('bg-success', 'text-white');
                    };
                    suggestionsList.appendChild(badge);
                });
                suggestionsDiv.classList.remove('d-none');
            }
        })
        .catch(error => console.error('Error:', error))
        .finally(() => {
            btnSuggest.disabled = false;
            btnSuggest.innerHTML = '<i class="bi bi-magic me-1"></i> {{ __('campaigns.suggest_audience') }}';
        });
    });
});
</script>
@endsection
