<?php $__env->startSection('title', 'TMDB Bulk Import'); ?>
<?php $__env->startSection('heading', 'TMDB Bulk Import'); ?>
<?php $__env->startSection('content'); ?>
<div class="premium-page-head">
    <div><span class="eyebrow">CONTENT IMPORTER</span><h1>TMDB Bulk Import</h1><p>Import Movies and TV Shows safely. TV Shows automatically fetch every TMDB season and episode in separate requests.</p></div>
</div>

<div class="tmdb-bulk-card tmdb-bulk-page" id="tmdbBulkCard"
 data-discover-url="<?php echo e(route('admin.tmdb-bulk.discover')); ?>"
 data-import-url="<?php echo e(route('admin.tmdb-bulk.import-one')); ?>"
 data-season-url="<?php echo e(route('admin.tmdb-bulk.import-season')); ?>">
 <div class="tmdb-bulk-copy">
  <span class="eyebrow">SAFE BATCH IMPORT</span><h2>Choose what you want to import</h2>
  <p>For 100–200 titles, the browser imports one title at a time. Each TV season and its episodes are then fetched automatically, one season at a time.</p>
 </div>
 <div class="tmdb-filter-grid">
  <label><span>Content Type</span><select id="bulkKind"><option value="movie">Movies</option><option value="show">TV Shows</option></select></label>
  <label><span>Source</span><select id="bulkSource">
   <option value="new_releases">New Releases</option><option value="upcoming">Upcoming</option><option value="popular">Popular</option>
   <option value="trending">Trending This Week</option><option value="top_rated">Top Rated</option><option value="discover">Discover / Filter</option><option value="random">Random Pages</option>
  </select></label>
  <label><span>Amount</span><select id="bulkAmount"><option>20</option><option>50</option><option selected>100</option><option>200</option></select></label>
  <label><span>Start Page</span><input id="bulkStartPage" type="number" min="1" max="500" value="1"></label>
  <label><span>Year (optional)</span><input id="bulkYear" type="number" min="1900" max="<?php echo e(date('Y') + 5); ?>" placeholder="e.g. <?php echo e(date('Y')); ?>"></label>
  <label><span>Genre</span><select id="bulkGenre"><option value="">All Genres</option><?php $__currentLoopData = $genres; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $genre): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($genre['id']); ?>" data-type="<?php echo e($genre['type']); ?>"><?php echo e($genre['name']); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select></label>
  <label><span>Original Language</span><select id="bulkLanguage"><option value="">Any Language</option><?php $__currentLoopData = $languages; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $language): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($language['code']); ?>"><?php echo e($language['label']); ?> (<?php echo e($language['code']); ?>)</option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select></label>
  <label><span>Minimum Rating</span><select id="bulkRating"><option value="0">Any Rating</option><option value="5">5+</option><option value="6">6+</option><option value="7">7+</option><option value="8">8+</option></select></label>
  <label><span>Minimum Votes</span><select id="bulkVotes"><option value="0">Any</option><option value="25">25+</option><option value="50">50+</option><option value="100">100+</option><option value="500">500+</option></select></label>
 </div>
 <div class="tmdb-bulk-controls">
  <button type="button" class="premium-btn premium-btn-primary" id="bulkStart"><i class="fa-solid fa-cloud-arrow-down"></i> Start Import</button>
  <button type="button" class="premium-btn premium-btn-muted" id="bulkStop" hidden><i class="fa-solid fa-stop"></i> Stop</button>
 </div>
 <div class="tmdb-bulk-progress" id="bulkProgress" hidden>
  <div class="tmdb-progress-top"><strong id="bulkStatus">Preparing…</strong><span id="bulkCount">0 / 0</span></div>
  <div class="tmdb-progress-track"><span id="bulkBar"></span></div>
  <div class="tmdb-progress-stats"><span class="success">Imported: <b id="bulkImported">0</b></span><span>Duplicates: <b id="bulkSkipped">0</b></span><span class="danger">Failed: <b id="bulkFailed">0</b></span></div>
  <div class="tmdb-import-log" id="bulkLog"></div>
 </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
(() => {
 const card=document.getElementById('tmdbBulkCard'); if(!card)return;
 const token=<?php echo json_encode(csrf_token(), 15, 512) ?>, start=document.getElementById('bulkStart'), stop=document.getElementById('bulkStop');
 const progress=document.getElementById('bulkProgress'), status=document.getElementById('bulkStatus'), count=document.getElementById('bulkCount'), bar=document.getElementById('bulkBar'), log=document.getElementById('bulkLog');
 const importedEl=document.getElementById('bulkImported'), skippedEl=document.getElementById('bulkSkipped'), failedEl=document.getElementById('bulkFailed'); let stopped=false;
 const sleep=ms=>new Promise(r=>setTimeout(r,ms));
 async function post(url,body,retries=1,timeout=75000){const c=new AbortController(),t=setTimeout(()=>c.abort(),timeout);try{const r=await fetch(url,{method:'POST',headers:{'Content-Type':'application/json','Accept':'application/json','X-CSRF-TOKEN':token,'X-Requested-With':'XMLHttpRequest'},body:JSON.stringify(body),signal:c.signal});const d=await r.json().catch(()=>({}));if(!r.ok||d.ok===false)throw new Error(d.message||'Request failed');return d}catch(e){if(retries>0&&(e.name==='AbortError'||e instanceof TypeError)){await sleep(1200);return post(url,body,retries-1)}throw new Error(e.name==='AbortError'?'This item timed out and was skipped.':e.message)}finally{clearTimeout(t)}}
 function addLog(m,type=''){const x=document.createElement('div');x.className=type;x.textContent=m;log.prepend(x);while(log.children.length>25)log.lastElementChild.remove()}
 function setProgress(d,t){count.textContent=`${d} / ${t}`;bar.style.width=`${t?Math.round(d/t*100):0}%`}
 function filterGenres(){const kind=document.getElementById('bulkKind').value;[...document.querySelectorAll('#bulkGenre option[data-type]')].forEach(o=>{o.hidden=o.dataset.type!==kind;if(o.hidden&&o.selected)document.getElementById('bulkGenre').value=''})}
 document.getElementById('bulkKind').addEventListener('change',filterGenres);filterGenres();
 stop.onclick=()=>{stopped=true;status.textContent='Stopping after current title…';stop.disabled=true};
 start.onclick=async()=>{
  const kind=document.getElementById('bulkKind').value,source=document.getElementById('bulkSource').value,amount=+document.getElementById('bulkAmount').value;
  const startPage=Math.max(1,+document.getElementById('bulkStartPage').value||1), year=document.getElementById('bulkYear').value,genre=document.getElementById('bulkGenre').value,language=document.getElementById('bulkLanguage').value,rating=+document.getElementById('bulkRating').value,votes=+document.getElementById('bulkVotes').value;
  let ids=[],done=0,imported=0,skipped=0,failed=0,page=source==='random'?Math.floor(Math.random()*Math.max(1,500-startPage+1))+startPage:startPage,totalPages=500,visited=new Set();stopped=false;
  start.disabled=true;stop.hidden=false;stop.disabled=false;progress.hidden=false;log.innerHTML=''; importedEl.textContent=skippedEl.textContent=failedEl.textContent='0';setProgress(0,amount);
  try{
   status.textContent='Finding unique titles from TMDB…';let scans=0;
   while(ids.length<amount&&scans<500&&!stopped){if(visited.has(page)){page=page%500+1;continue}visited.add(page);scans++;
    const r=await post(card.dataset.discoverUrl,{kind,source,page,year:year||null,genre_id:genre||null,language:language||null,min_rating:rating,min_votes:votes});totalPages=Math.min(+r.total_pages||1,500);ids=[...new Set([...ids,...r.ids])].slice(0,amount);skipped+=+r.duplicate_count||0;skippedEl.textContent=skipped;addLog(`Page ${page}: ${r.ids.length} new, ${r.duplicate_count||0} duplicates.`);page=source==='random'?Math.floor(Math.random()*Math.max(1,totalPages))+1:page+1;if(source!=='random'&&page>totalPages)break;await sleep(350)}
   if(!ids.length)throw new Error('No new titles matched these filters. Change page or filters.'); status.textContent=`Importing ${ids.length} titles one by one…`;setProgress(0,ids.length);
   for(const id of ids){if(stopped)break;try{const r=await post(card.dataset.importUrl,{kind,tmdb_id:id});if(r.status==='skipped'){skipped++;addLog(`Duplicate skipped: ${r.title||'#'+id}`,'updated')}else{imported++;addLog(`Imported: ${r.title}`,'success')}if(kind==='show'&&r.show_id&&Array.isArray(r.season_numbers)){for(const seasonNumber of r.season_numbers){if(stopped)break;status.textContent=`${r.title}: importing Season ${seasonNumber}…`;try{const sr=await post(card.dataset.seasonUrl,{show_id:r.show_id,season_number:seasonNumber},1,180000);addLog(`${r.title} — ${sr.season_title}: ${sr.episode_count} episodes imported`,'success')}catch(e){failed++;addLog(`${r.title} — Season ${seasonNumber}: ${e.message}`,'danger');failedEl.textContent=failed}await sleep(500)}}}catch(e){failed++;addLog(`#${id}: ${e.message}`,'danger')}done++;importedEl.textContent=imported;skippedEl.textContent=skipped;failedEl.textContent=failed;setProgress(done,ids.length);status.textContent=`Processing ${done} of ${ids.length}…`;await sleep(500)}
   status.textContent=stopped?'Import stopped. You can start again anytime.':`Completed — ${imported} imported, ${skipped} duplicates, ${failed} failed.`;
  }catch(e){status.textContent=e.message;addLog(e.message,'danger')}finally{start.disabled=false;stop.hidden=true;stop.disabled=false}
 };
})();
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('admin.layout', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/megashopltd/moviedocks.com/resources/views/admin/tmdb-bulk.blade.php ENDPATH**/ ?>