@extends('layouts.simple.master')

@section('title', 'مدیریت پروژه‌ها')

@section('css')
<link rel="stylesheet" href="{{ asset('assets/css/vendors/select/bootstrap-select.min.css') }}">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" />
<link href="https://cdn.jsdelivr.net/npm/remixicon/fonts/remixicon.css" rel="stylesheet">
<style>
.sidebar-panel-main { display: none !important; }

/* ==================== Modern Tabs Styling ==================== */
.modern-tabs {
    display: flex;
    gap: 8px;
    padding: 8px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 12px;
    margin-bottom: 24px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}

.modern-tabs .nav-item {
    flex: 1;
}

.modern-tabs .nav-link {
    width: 100%;
    padding: 12px 20px;
    background: transparent;
    border: none;
    border-radius: 8px;
    color: #6c757d;
    font-weight: 600;
    font-size: 14px;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    cursor: pointer;
}

.modern-tabs .nav-link i {
    font-size: 18px;
}

.modern-tabs .nav-link:hover {
    background: rgba(255,255,255,0.5);
    color: #495057;
    transform: translateY(-2px);
}

.modern-tabs .nav-link.active {
    background: linear-gradient(135deg, #7366ff 0%, #5e50ee 100%);
    color: #fff;
    box-shadow: 0 4px 12px rgba(115, 102, 255, 0.3);
}

/* ==================== Project Cards ==================== */
.project-card {
    transition: all 0.3s ease;
}

.project-card:hover {
    transform: translateY(-5px);
}

.project-card .card {
    border: 2px solid #f1f3f5;
    border-radius: 16px;
    overflow: hidden;
    transition: all 0.3s ease;
    background: #fff;
    height: 100%;
}

.project-card .card:hover {
    border-color: #7366ff;
    box-shadow: 0 8px 24px rgba(115, 102, 255, 0.15);
}

.project-card .card-body {
    position: relative;
    padding: 24px;
}

/* Action Buttons */
.project-action-btns {
    position: absolute;
    top: 16px;
    left: 16px;
    display: flex;
    gap: 6px;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.project-card:hover .project-action-btns {
    opacity: 1;
}

.project-action-btns button {
    width: 32px;
    height: 32px;
    border: none;
    background: rgba(255,255,255,0.9);
    border-radius: 8px;
    cursor: pointer;
    font-size: 16px;
    color: #6c757d;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.project-action-btns button:hover {
    background: #fff;
    transform: scale(1.1);
}

.project-action-btns button:first-child:hover {
    color: #7366ff;
}

.project-action-btns button:last-child:hover {
    color: #dc3545;
}

/* Project Content */
.project-content {
    cursor: pointer;
    padding-right: 48px;
}

.project-id {
    display: inline-block;
    padding: 2px 8px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 6px;
    font-size: 11px;
    font-weight: 700;
    color: #6c757d;
    margin-left: 8px;
}

.project-name {
    font-size: 16px;
    font-weight: 700;
    color: #2b2f4a;
    margin-bottom: 8px;
    line-height: 1.4;
}

.project-date {
    font-size: 13px;
    color: #8898aa;
    margin-bottom: 16px;
}

.project-date strong {
    color: #495057;
}

/* Project Stats */
.project-stats {
    display: flex;
    gap: 8px;
    margin-top: 16px;
}

.stat-badge {
    flex: 1;
    padding: 8px 12px;
    border-radius: 8px;
    font-size: 12px;
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    transition: all 0.3s ease;
}

.stat-badge i {
    font-size: 14px;
}

.stat-badge.servers {
    background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
    color: #1976d2;
}

.stat-badge.ips {
    background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
    color: #388e3c;
}

.stat-badge:hover {
    transform: scale(1.05);
}

/* Add Project Card */
#add-project-card .card {
    border: 2px dashed #dee2e6;
    background: linear-gradient(135deg, #fafbfc 0%, #f8f9fa 100%);
    cursor: pointer;
    transition: all 0.3s ease;
    min-height: 180px;
}

#add-project-card .card:hover {
    border-color: #7366ff;
    background: linear-gradient(135deg, #f8f9ff 0%, #f0f0ff 100%);
    transform: translateY(-5px);
    box-shadow: 0 8px 24px rgba(115, 102, 255, 0.15);
}

.add-project-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 12px;
    padding: 32px;
}

.add-project-icon {
    width: 64px;
    height: 64px;
    background: linear-gradient(135deg, #7366ff 0%, #5e50ee 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28px;
    color: #fff;
    transition: all 0.3s ease;
}

#add-project-card:hover .add-project-icon {
    transform: rotate(90deg) scale(1.1);
}

.add-project-text {
    font-size: 16px;
    font-weight: 700;
    color: #7366ff;
    margin: 0;
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 80px 20px;
}

.empty-state-icon {
    font-size: 80px;
    color: #dee2e6;
    margin-bottom: 24px;
}

.empty-state h3 {
    font-size: 24px;
    font-weight: 700;
    color: #2b2f4a;
    margin-bottom: 12px;
}

.empty-state p {
    font-size: 16px;
    color: #8898aa;
    margin-bottom: 24px;
}

/* Modal Styling */
.modal-content {
    border-radius: 16px;
    border: none;
    box-shadow: 0 12px 48px rgba(0,0,0,0.15);
}

.modal-header {
    background: linear-gradient(135deg, #7366ff 0%, #5e50ee 100%);
    color: #fff;
    border-radius: 16px 16px 0 0;
    padding: 20px 24px;
}

.modal-header .btn-close {
    filter: brightness(0) invert(1);
}

.modal-title {
    font-weight: 700;
}

.modal-body {
    padding: 24px;
}

.form-label {
    font-weight: 600;
    color: #495057;
    margin-bottom: 8px;
}

.form-control {
    border-radius: 8px;
    border: 2px solid #e9ecef;
    padding: 10px 16px;
    transition: all 0.3s ease;
}

.form-control:focus {
    border-color: #7366ff;
    box-shadow: 0 0 0 4px rgba(115, 102, 255, 0.1);
}

/* Responsive */
@media (max-width: 768px) {
    .modern-tabs {
        flex-wrap: wrap;
    }
    
    .modern-tabs .nav-link {
        font-size: 12px;
        padding: 10px 12px;
    }
    
    .project-action-btns {
        opacity: 1;
    }
}
</style>
@endsection

@section('main_content')
<div class="container-fluid">
    <!-- Page Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="page-title-box d-flex align-items-center justify-content-between">
                <h4 class="mb-0">
                    <i class="ri-folder-3-line me-2"></i>
                    مدیریت پروژه‌ها
                </h4>
                <div class="page-title-right">
                    <ol class="breadcrumb m-0">
                        <li class="breadcrumb-item"><a href="/">داشبورد</a></li>
                        <li class="breadcrumb-item active">پروژه‌ها</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

 <!-- Modern Tabs -->
<ul class="nav modern-tabs">
    <li class="nav-item">
        <button class="nav-link active" data-tab="projects">
            <i class="ri-folder-3-line"></i>
            پروژه‌ها
        </button>
    </li>
    <li class="nav-item">
        <button class="nav-link" onclick="window.location='/wallet/charge'">
            <i class="ri-file-list-3-line"></i>
            صورت‌حساب‌ها
        </button>
    </li>
    <li class="nav-item">
        {{-- ✅ لینک به صفحه Primary IPs (نیاز به انتخاب یک پروژه) --}}
        @if($projects->count() > 0)
            <button class="nav-link" onclick="window.location='{{ route('projects.servers.primaryips.index', ['project' => $projects->first()->id]) }}'">
                <i class="ri-global-line"></i>
                مدیریت IP
            </button>
        @else
            <button class="nav-link" disabled title="ابتدا یک پروژه ایجاد کنید">
                <i class="ri-global-line"></i>
                مدیریت IP
            </button>
        @endif
    </li>
    <li class="nav-item">
        <button class="nav-link" onclick="window.location='/cloud/limits'">
            <i class="ri-shield-check-line"></i>
            محدودیت‌ها
        </button>
    </li>
    <li class="nav-item">
        <button class="nav-link" onclick="window.location='/'">
            <i class="ri-user-add-line"></i>
            ارجاع
        </button>
    </li>
</ul>

    <!-- Projects Grid -->
    <div class="row" id="projects-container">
        @forelse($projects as $project)
        <div class="col-xl-3 col-lg-4 col-md-6 mb-4 project-card" id="project-{{ $project->id }}">
            <div class="card">
                <div class="card-body">
                    <!-- Action Buttons -->
                    <div class="project-action-btns">
                        <button onclick="renameProject({{ $project->id }}, '{{ $project->name }}')" 
                                title="تغییر نام">
                            <i class="ri-pencil-line"></i>
                        </button>
                        <button onclick="deleteProject({{ $project->id }})" 
                                title="حذف">
                            <i class="ri-delete-bin-7-line"></i>
                        </button>
                    </div>

                    <!-- Project Content -->
                    <div class="project-content" onclick="window.location='{{ route('projects.servers', $project->id) }}'">
                        <div class="project-name">
                            <span class="project-id">#{{ $project->id }}</span>
                            {{ $project->name }}
                        </div>
                        <div class="project-date">
                            <i class="ri-time-line me-1"></i>
                            ایجاد شده: 
                            <strong>{{ $project->created_at->diffForHumans() }}</strong>
                        </div>

                        <!-- Project Stats -->
                        <div class="project-stats">
                            <div class="stat-badge servers">
                                <i class="ri-server-line"></i>
                                {{ $project->servers_count ?? 0 }} سرور
                            </div>
                            <div class="stat-badge ips">
                                <i class="ri-global-line"></i>
                                {{ $project->ips_count ?? 0 }} IP
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        @empty
        <div class="col-12">
            <div class="empty-state">
                <div class="empty-state-icon">
                    <i class="ri-folder-open-line"></i>
                </div>
                <h3>هنوز پروژه‌ای ندارید</h3>
                <p>برای شروع، اولین پروژه خود را ایجاد کنید</p>
                <button class="btn btn-primary btn-lg" onclick="showAddProjectModal()">
                    <i class="ri-add-line me-2"></i>
                    ایجاد پروژه جدید
                </button>
            </div>
        </div>
        @endforelse

        <!-- Add Project Card -->
        @if($projects->count() > 0)
        <div class="col-xl-3 col-lg-4 col-md-6 mb-4" id="add-project-card">
            <div class="card" onclick="showAddProjectModal()">
                <div class="card-body">
                    <div class="add-project-content">
                        <div class="add-project-icon">
                            <i class="ri-add-line"></i>
                        </div>
                        <h5 class="add-project-text">
                            پروژه جدید
                        </h5>
                    </div>
                </div>
            </div>
        </div>
        @endif
    </div>
</div>

<!-- Add Project Modal -->
<div class="modal fade" id="addProjectModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form id="addProjectForm">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="ri-folder-add-line me-2"></i>
                        افزودن پروژه جدید
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="ri-text me-1"></i>
                            نام پروژه
                        </label>
                        <input type="text" 
                               class="form-control" 
                               name="name" 
                               id="projectName" 
                               placeholder="مثال: پروژه وب سایت شرکتی"
                               required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">
                        <i class="ri-close-line me-1"></i>
                        بستن
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="ri-add-line me-1"></i>
                        افزودن پروژه
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Rename Project Modal -->
<div class="modal fade" id="renameProjectModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form id="renameProjectForm">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="ri-pencil-line me-2"></i>
                        تغییر نام پروژه
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">
                            <i class="ri-text me-1"></i>
                            نام جدید پروژه
                        </label>
                        <input type="text" 
                               class="form-control" 
                               id="newProjectName" 
                               required>
                        <input type="hidden" id="currentProjectId">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">
                        <i class="ri-close-line me-1"></i>
                        بستن
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="ri-check-line me-1"></i>
                        ذخیره تغییرات
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>

// ====== Show Modals ======
function showAddProjectModal(){
    new bootstrap.Modal(document.getElementById('addProjectModal')).show();
}

function renameProject(id, name){
    document.getElementById('currentProjectId').value = id;
    document.getElementById('newProjectName').value = name;
    new bootstrap.Modal(document.getElementById('renameProjectModal')).show();
}

// ====== Add Project ======
document.getElementById('addProjectForm').addEventListener('submit', function(e){
    e.preventDefault();
    let name = document.getElementById('projectName').value;

    fetch('{{ route("cloud.project-add") }}', {
        method: 'POST',
        headers: {
            'Content-Type':'application/json',
            'X-CSRF-TOKEN':'{{ csrf_token() }}'
        },
        body: JSON.stringify({name:name})
    })
    .then(res=>res.json())
    .then(data=>{
        if(data.status==='success'){
            Swal.fire({
                icon:'success',
                title:'موفق!',
                text:data.message,
                timer:2000,
                showConfirmButton:false
            });
            
            bootstrap.Modal.getInstance(document.getElementById('addProjectModal')).hide();
            document.getElementById('projectName').value='';
            
            // ✅ حذف empty state اگه وجود داره
            const emptyState = document.querySelector('.empty-state');
            if(emptyState) {
                emptyState.parentElement.remove();
            }
            
            // ✅ نمایش کارت "افزودن پروژه" اگه قبلاً نبود
            if(!document.getElementById('add-project-card')){
                const container = document.getElementById('projects-container');
                container.insertAdjacentHTML('beforeend', `
                    <div class="col-xl-3 col-lg-4 col-md-6 mb-4" id="add-project-card">
                        <div class="card" onclick="showAddProjectModal()">
                            <div class="card-body">
                                <div class="add-project-content">
                                    <div class="add-project-icon">
                                        <i class="ri-add-line"></i>
                                    </div>
                                    <h5 class="add-project-text">پروژه جدید</h5>
                                </div>
                            </div>
                        </div>
                    </div>
                `);
            }
            
            // ✅ اضافه کردن کارت جدید
            document.getElementById('add-project-card').insertAdjacentHTML('beforebegin', createProjectCard(data.project));
            
            // ✅ انیمیشن برای کارت جدید
            setTimeout(() => {
                document.getElementById('project-' + data.project.id).style.animation = 'fadeIn 0.5s';
            }, 10);
        }else{
            Swal.fire({
                icon:'error',
                title:'خطا!',
                text:data.message
            });
        }
    });
});


// ====== Delete Project ======
function deleteProject(id){
    Swal.fire({
        title:'حذف پروژه؟',
        text:'این عملیات قابل بازگشت نیست!',
        icon:'warning',
        showCancelButton:true,
        confirmButtonText:'بله، حذف کن',
        cancelButtonText:'لغو',
        confirmButtonColor:'#dc3545',
        cancelButtonColor:'#6c757d'
    }).then(result=>{
        if(result.isConfirmed){
            fetch('{{ route("cloud.project-delete") }}', {
                method:'POST',
                headers:{
                    'Content-Type':'application/json',
                    'X-CSRF-TOKEN':'{{ csrf_token() }}'
                },
                body:JSON.stringify({id:id})
            })
            .then(res=>res.json())
            .then(data=>{
                if(data.status==='success'){
                    Swal.fire({
                        icon:'success',
                        title:'حذف شد',
                        text:data.message,
                        timer:1500,
                        showConfirmButton:false
                    });
                    document.getElementById('project-'+id).remove();
                    
                    // چک کن اگه هیچ پروژه‌ای نمونده، empty state نمایش بده
                    if(document.querySelectorAll('.project-card').length === 0) {
                        location.reload();
                    }
                }else{
                    Swal.fire({
                        icon:'error',
                        title:'خطا!',
                        text:data.message
                    });
                }
            });
        }
    });
}

// ====== Rename Project ======
document.getElementById('renameProjectForm').addEventListener('submit', function(e){
    e.preventDefault();
    let id = document.getElementById('currentProjectId').value;
    let newName = document.getElementById('newProjectName').value;

    fetch('{{ route("cloud.project-rename") }}', {
        method:'POST',
        headers:{
            'Content-Type':'application/json',
            'X-CSRF-TOKEN':'{{ csrf_token() }}'
        },
        body:JSON.stringify({id:id, name:newName})
    })
    .then(res=>res.json())
    .then(data=>{
        if(data.status==='success'){
            Swal.fire({
                icon:'success',
                title:'موفق!',
                text:data.message,
                timer:2000,
                showConfirmButton:false
            });
            document.querySelector(`#project-${id} .project-name`).innerHTML = 
                `<span class="project-id">#${id}</span>${newName}`;
            bootstrap.Modal.getInstance(document.getElementById('renameProjectModal')).hide();
        }else{
            Swal.fire({
                icon:'error',
                title:'خطا!',
                text:data.message
            });
        }
    });
});

// ====== Helper: Create Project Card ======
function createProjectCard(project){
    return `
        <div class="col-xl-3 col-lg-4 col-md-6 mb-4 project-card" id="project-${project.id}">
            <div class="card">
                <div class="card-body">
                    <div class="project-action-btns">
                        <button onclick="renameProject(${project.id}, '${project.name}')" title="تغییر نام">
                            <i class="ri-pencil-line"></i>
                        </button>
                        <button onclick="deleteProject(${project.id})" title="حذف">
                            <i class="ri-delete-bin-7-line"></i>
                        </button>
                    </div>
                    <div class="project-content" onclick="window.location='${project.servers_route}'">
                        <div class="project-name">
                            <span class="project-id">#${project.id}</span>
                            ${project.name}
                        </div>
                        <div class="project-date">
                            <i class="ri-time-line me-1"></i>
                            ایجاد شده: <strong>همین الان</strong>
                        </div>
                        <div class="project-stats">
                            <div class="stat-badge servers">
                                <i class="ri-server-line"></i>
                                0 سرور
                            </div>
                            <div class="stat-badge ips">
                                <i class="ri-global-line"></i>
                                0 IP
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>`;
}
</script>
@endsection