<?php
defined('ABSPATH') || exit;
if(!current_user_can('manage_options')){echo '<p>صلاحيات غير كافية</p>';return;}

// Handle page creation
if(!empty($_POST['dzqcod_create_pages']) && wp_verify_nonce($_POST['_wpnonce']??'','dzqcod_gen_pages') && current_user_can('manage_options')){
    $selected = array_map('sanitize_key', (array)($_POST['pages']??[]));
    $created = 0; $errors = [];
    foreach($selected as $slug){
        $page = \DZQCOD\PageGenerator::PAGES[$slug] ?? null;
        if(!$page) continue;
        // Check if page already exists
        $existing = get_posts(['post_type'=>'page','meta_key'=>'_dzqcod_page','meta_value'=>$slug,'posts_per_page'=>1]);
        if(!empty($existing)){$errors[] = $page['title'].' (موجودة مسبقاً)'; continue;}
        $pid = wp_insert_post([
            'post_title'   => $page['title'],
            'post_content' => $page['shortcode'],
            'post_status'  => 'publish',
            'post_type'    => 'page',
            'meta_input'   => ['_dzqcod_page'=>$slug],
        ]);
        if($pid && !is_wp_error($pid)) $created++;
        else $errors[] = $page['title'].' (خطأ)';
    }
}

$pages = \DZQCOD\PageGenerator::PAGES;
// Check which pages already exist
$existing_pages = [];
$existing_posts = get_posts(['post_type'=>'page','meta_key'=>'_dzqcod_page','posts_per_page'=>100]);
foreach($existing_posts as $ep) $existing_pages[get_post_meta($ep->ID,'_dzqcod_page',true)] = $ep;
?>
<div class="dza-header">
<h1>📄 مولّد الصفحات</h1>
<p style="font-size:12px;color:#64748b;margin-top:4px">أنشئ صفحات متجرك الجاهزة بنقرة واحدة — كل صفحة مصممة لزيادة المبيعات والثقة</p>
</div>
<?php include __DIR__.'/nav.php'; ?>
<div class="dza-content">

<?php if(!empty($created)): ?>
<div style="background:#f0fdf4;border:1px solid #86efac;border-radius:12px;padding:14px;margin-bottom:16px;font-size:13px;color:#166534">
✅ تم إنشاء <strong><?php echo $created; ?></strong> صفحة بنجاح!
<?php if(!empty($errors)): ?><br>⚠️ تم تجاوز: <?php echo esc_html(implode('، ',$errors)); ?><?php endif; ?>
</div>
<?php endif; ?>

<!-- Quick Actions -->
<div style="display:flex;gap:10px;margin-bottom:20px;flex-wrap:wrap">
<form method="post" id="gen-all-form">
<?php wp_nonce_field('dzqcod_gen_pages'); ?>
<input type="hidden" name="dzqcod_create_pages" value="1">
<button type="button" onclick="selectAll()" class="dza-btn primary" style="padding:10px 24px;font-size:13px">✅ تحديد الكل</button>
<button type="button" onclick="selectNone()" class="dza-btn" style="padding:10px 24px;font-size:13px;background:#f1f5f9;color:#475569">❌ إلغاء الكل</button>
<button type="submit" class="dza-btn" style="padding:10px 24px;font-size:13px;background:#10b981;color:#fff">🚀 إنشاء الصفحات المحددة</button>
<span style="font-size:12px;color:#94a3b8;padding:12px">المحدد: <strong id="sel-count">0</strong> صفحة</span>
</form>
</div>

<!-- Pages Grid -->
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:12px">
<?php foreach($pages as $slug=>$page):
$exists = isset($existing_pages[$slug]);
$ep = $exists ? $existing_pages[$slug] : null;
$cat_colors = ['essential'=>'#10b981','marketing'=>'#6366f1','trust'=>'#f59e0b','support'=>'#3b82f6','commerce'=>'#ec4899','content'=>'#8b5cf6'];
$cat_c = $cat_colors[$page['category']] ?? '#64748b';
?>
<div class="dza-card" style="padding:16px;position:relative;border-right:4px solid <?php echo $exists?'#10b981':esc_attr($cat_c); ?>;transition:.2s<?php echo $exists?' ;opacity:.7':''; ?>">
<?php if($exists): ?>
<div style="position:absolute;top:10px;left:10px;background:#10b981;color:#fff;padding:2px 8px;border-radius:6px;font-size:9px;font-weight:700">✅ موجودة</div>
<?php endif; ?>

<div style="display:flex;align-items:flex-start;gap:12px">
<div style="font-size:28px;flex-shrink:0"><?php echo esc_html($page['icon']); ?></div>
<div style="flex:1">
<div style="font-weight:800;font-size:14px;margin-bottom:2px"><?php echo esc_html($page['title']); ?></div>
<div style="font-size:11px;color:#94a3b8;margin-bottom:6px"><?php echo esc_html($page['description']); ?></div>
<div style="display:flex;gap:4px;flex-wrap:wrap;margin-bottom:6px">
<span style="background:<?php echo esc_attr($cat_c); ?>20;color:<?php echo esc_attr($cat_c); ?>;padding:1px 8px;border-radius:6px;font-size:9px;font-weight:700"><?php echo esc_html($page['category_label']); ?></span>
<?php if(!empty($page['plan']) && $page['plan']!=='free'): ?>
<span style="background:<?php echo $page['plan']==='pro'?'#6c5ce720':'#fdcb6e20'; ?>;color:<?php echo $page['plan']==='pro'?'#6c5ce7':'#f59e0b'; ?>;padding:1px 8px;border-radius:6px;font-size:9px;font-weight:700"><?php echo strtoupper($page['plan']); ?></span>
<?php endif; ?>
</div>
<div style="font-size:10px;color:#64748b;background:#f8fafc;padding:4px 8px;border-radius:4px;font-family:monospace;direction:ltr"><?php echo esc_html($page['shortcode']); ?></div>
</div>
<?php if(!$exists): ?>
<label style="flex-shrink:0;cursor:pointer">
<input type="checkbox" name="pages[]" value="<?php echo esc_attr($slug); ?>" form="gen-all-form" class="page-cb" onchange="updateCount()" style="width:20px;height:20px;accent-color:<?php echo esc_attr($cat_c); ?>">
</label>
<?php else: ?>
<div style="flex-shrink:0;display:flex;flex-direction:column;gap:4px">
<a href="<?php echo esc_url(get_permalink($ep->ID)); ?>" target="_blank" style="font-size:10px;color:#3b82f6;text-decoration:none">👁️ عرض</a>
<a href="<?php echo esc_url(get_edit_post_link($ep->ID)); ?>" style="font-size:10px;color:#f59e0b;text-decoration:none">✏️ تعديل</a>
</div>
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
</div>

<!-- Shortcode Reference -->
<div style="margin-top:24px;background:#1e293b;border-radius:12px;padding:20px">
<h3 style="color:#fff;font-size:16px;margin:0 0 12px">📋 مرجع الأكواد المختصرة</h3>
<p style="font-size:11px;color:#94a3b8;margin-bottom:12px">يمكنك استخدام هذه الأكواد في أي صفحة أو مقال أو ويدجت</p>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:6px">
<?php foreach($pages as $slug=>$page): ?>
<div style="display:flex;justify-content:space-between;align-items:center;background:#0f172a;border-radius:6px;padding:6px 10px">
<span style="font-size:11px;color:#94a3b8"><?php echo esc_html($page['icon'].' '.$page['title']); ?></span>
<code style="font-size:10px;color:#a5b4fc;background:#1e293b;padding:2px 6px;border-radius:3px;cursor:pointer" onclick="navigator.clipboard.writeText(this.textContent);this.style.color='#10b981'"><?php echo esc_html($page['shortcode']); ?></code>
</div>
<?php endforeach; ?>
</div>
</div>

</div>

<script>
function selectAll(){document.querySelectorAll('.page-cb').forEach(function(c){c.checked=true});updateCount()}
function selectNone(){document.querySelectorAll('.page-cb').forEach(function(c){c.checked=false});updateCount()}
function updateCount(){document.getElementById('sel-count').textContent=document.querySelectorAll('.page-cb:checked').length}
</script>
