<?php
/**
 * Addon: Canva Creative — مصمم إعلانات احترافي
 * Version: 2.0.0
 * Type: enterprise
 */
namespace DZQCOD\Addons;
if (!defined('ABSPATH')) exit;
if (!\DZQCOD\Modules::is_on('canva')) return;

class CanvaCreative {
    public static function init():void{
        add_action('wp_ajax_dzqcod_canva_generate',[self::class,'generate']);
        add_action('wp_ajax_dzqcod_canva_products',[self::class,'get_products']);
        add_action('wp_ajax_dzqcod_canva_save',[self::class,'save_design']);
        add_action('dzqcod_admin_page_canva',[self::class,'admin_page']);
    }

    public static function get_products():void{
        check_ajax_referer('dzqcod_admin','nonce');
        $q=sanitize_text_field($_POST['q']??'');$args=['status'=>'publish','limit'=>30,'orderby'=>'date','order'=>'DESC'];
        if($q)$args['s']=$q;$out=[];
        foreach(wc_get_products($args) as $p){
            $img_id=$p->get_image_id();$img=$img_id?wp_get_attachment_image_url($img_id,'medium'):'';
            $out[]=['id'=>$p->get_id(),'name'=>$p->get_name(),'price'=>(float)$p->get_price(),
                'sale'=>(float)$p->get_sale_price(),'regular'=>(float)$p->get_regular_price(),
                'img'=>$img,'sku'=>$p->get_sku(),'short_desc'=>wp_strip_all_tags($p->get_short_description())];
        }
        wp_send_json_success($out);
    }

    public static function generate():void{
        check_ajax_referer('dzqcod_admin','nonce');
        // Just return product data - the actual rendering happens in HTML5 Canvas on frontend
        $pid=absint($_POST['product_id']??0);$p=$pid?wc_get_product($pid):null;
        $data=['name'=>$p?$p->get_name():sanitize_text_field($_POST['custom_name']??'منتج'),
            'price'=>$p?(float)$p->get_price():0,'sale'=>$p?(float)$p->get_sale_price():0,
            'regular'=>$p?(float)$p->get_regular_price():0,'img'=>'','cur'=>\DZQCOD\Core::opt('currency_symbol','دج'),
            'desc'=>$p?wp_strip_all_tags($p->get_short_description()):'','store'=>get_bloginfo('name'),
            'store_url'=>home_url(),'phone'=>\DZQCOD\Core::opt('store_phone','')];
        if($p){$img_id=$p->get_image_id();if($img_id)$data['img']=wp_get_attachment_image_url($img_id,'large');}
        wp_send_json_success($data);
    }

    public static function save_design():void{
        check_ajax_referer('dzqcod_admin','nonce');
        $img_data=$_POST['image_data']??'';if(!$img_data)wp_send_json_error(['message'=>'لا توجد بيانات']);
        $img_data=str_replace('data:image/png;base64,','',$img_data);$img_data=base64_decode($img_data);
        if(!$img_data)wp_send_json_error(['message'=>'بيانات غير صالحة']);
        $upload=wp_upload_dir();$fn='dzqcod-design-'.time().'.png';
        $path=$upload['basedir'].'/'.$fn;
        if(@file_put_contents($path,$img_data)===false)wp_send_json_error(['message'=>'خطأ في الحفظ']);
        $url=$upload['baseurl'].'/'.$fn;
        $attach_id=wp_insert_attachment(['post_title'=>$fn,'post_mime_type'=>'image/png','post_status'=>'inherit'],$path);
        if($attach_id)require_once(ABSPATH.'wp-admin/includes/image.php');
        if($attach_id)wp_update_attachment_metadata($attach_id,wp_generate_attachment_metadata($attach_id,$path));
        wp_send_json_success(['url'=>$url,'id'=>$attach_id]);
    }

    public static function admin_page():void{
        $cur=\DZQCOD\Core::opt('currency_symbol','دج');
        ?>
<div class="dza-wrap" style="direction:rtl;font-family:Tajawal,sans-serif">
<h2 style="font-size:22px;margin-bottom:16px">🎨 Canva Creative — مصمم إعلانات احترافي</h2>
<div style="display:grid;grid-template-columns:320px 1fr;gap:16px;align-items:start">

<!-- CONTROLS -->
<div style="background:#fff;border-radius:12px;padding:16px;box-shadow:0 2px 8px rgba(0,0,0,.06);max-height:85vh;overflow-y:auto">

<div style="margin-bottom:10px"><label style="font-weight:700;font-size:12px">📦 المنتج</label>
<input id="cv-search" placeholder="🔍 بحث عن منتج..." style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px;margin-bottom:4px">
<select id="cv-product" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px" onchange="cvLoadProduct()"><option value="0">— تحميل المنتجات... —</option></select></div>

<div style="margin-bottom:10px"><label style="font-weight:700;font-size:12px">📐 القالب</label>
<select id="cv-tpl" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px" onchange="cvRedraw()">
<option value="banner" data-w="1200" data-h="628">بانر إعلاني (1200×628)</option>
<option value="story" data-w="1080" data-h="1920">ستوري (1080×1920)</option>
<option value="square" data-w="1080" data-h="1080">مربع انستاقرام (1080×1080)</option>
<option value="fb_cover" data-w="1640" data-h="624">غلاف فيسبوك (1640×624)</option>
<option value="wide" data-w="1920" data-h="1080">عريض (1920×1080)</option>
</select></div>

<div style="margin-bottom:10px"><label style="font-weight:700;font-size:12px">🎨 الخلفية</label>
<div style="display:flex;gap:4px;flex-wrap:wrap" id="cv-gradients"></div></div>

<div style="margin-bottom:10px"><label style="font-weight:700;font-size:12px">✏️ النص الرئيسي</label>
<input id="cv-title" value="" placeholder="اسم المنتج" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px" oninput="cvRedraw()"></div>

<div style="margin-bottom:10px"><label style="font-weight:700;font-size:12px">💰 السعر</label>
<div style="display:flex;gap:6px"><input id="cv-price" type="number" value="0" style="flex:1;padding:8px;border:1px solid #ddd;border-radius:6px" oninput="cvRedraw()">
<input id="cv-old-price" type="number" value="0" placeholder="القديم" style="width:80px;padding:8px;border:1px solid #ddd;border-radius:6px" oninput="cvRedraw()"></div></div>

<div style="margin-bottom:10px"><label style="font-weight:700;font-size:12px">📝 وصف قصير</label>
<input id="cv-desc" placeholder="وصف سطر واحد" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px" oninput="cvRedraw()"></div>

<div style="margin-bottom:10px"><label style="font-weight:700;font-size:12px">🏷️ شارة</label>
<select id="cv-badge" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px" onchange="cvRedraw()">
<option value="">بدون</option><option value="🔥 عرض خاص">🔥 عرض خاص</option><option value="⭐ الأكثر مبيعاً">⭐ الأكثر مبيعاً</option>
<option value="🆕 جديد">🆕 جديد</option><option value="💎 حصري">💎 حصري</option><option value="⏰ محدود">⏰ محدود</option><option value="🚚 توصيل مجاني">🚚 توصيل مجاني</option>
</select></div>

<div style="margin-bottom:10px"><label style="font-weight:700;font-size:12px">📱 زر CTA</label>
<select id="cv-cta" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px" onchange="cvRedraw()">
<option>اطلب الآن</option><option>اشترِ الآن</option><option>احجز الآن</option><option>تواصل معنا</option><option>استفد من العرض</option><option>سارع قبل النفاد</option>
</select></div>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:6px;margin-bottom:10px">
<div><label style="font-size:11px;font-weight:700">لون النص</label><input type="color" id="cv-text-color" value="#ffffff" onchange="cvRedraw()" style="width:100%;height:32px;border:none;cursor:pointer"></div>
<div><label style="font-size:11px;font-weight:700">لون CTA</label><input type="color" id="cv-cta-color" value="#ff4757" onchange="cvRedraw()" style="width:100%;height:32px;border:none;cursor:pointer"></div>
</div>

<div style="margin-bottom:10px"><label style="font-weight:700;font-size:12px">🖼️ صورة المنتج</label>
<div id="cv-img-preview" style="width:100%;height:100px;background:#f1f5f9;border-radius:8px;display:flex;align-items:center;justify-content:center;color:#aaa;font-size:12px;overflow:hidden">لا توجد صورة</div></div>

<div style="display:flex;gap:6px">
<button onclick="cvDownload()" style="flex:1;padding:10px;background:#10B981;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:800;font-size:13px">📥 تحميل PNG</button>
<button onclick="cvSaveToMedia()" style="padding:10px 14px;background:#6366F1;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:800;font-size:13px">💾</button>
</div>
</div>

<!-- CANVAS PREVIEW -->
<div style="background:#1e293b;border-radius:12px;padding:16px;text-align:center;overflow:auto">
<canvas id="cv-canvas" style="max-width:100%;border-radius:8px;box-shadow:0 8px 32px rgba(0,0,0,.3)"></canvas>
</div>
</div></div>

<script>
var cvCanvas,cvCtx,cvW=1200,cvH=628,cvProductImg=null,cvGrad=0,cvCur='<?php echo esc_js($cur);?>';
var cvGrads=[
    ['#667eea','#764ba2'],['#ff4757','#ff6b81'],['#0f0c29','#302b63'],['#11998e','#38ef7d'],
    ['#fc466b','#3f5efb'],['#1a1a2e','#16213e'],['#f12711','#f5af19'],['#000428','#004e92'],
    ['#2c3e50','#3498db'],['#8e2de2','#4a00e0'],['#ff9a9e','#fad0c4'],['#00b09b','#96c93d'],
    ['#1f1c2c','#928dab'],['#ee0979','#ff6a00'],['#0f2027','#2c5364'],['#e44d26','#f16529']
];

jQuery(function($){
    cvCanvas=document.getElementById('cv-canvas');cvCtx=cvCanvas.getContext('2d');
    // Gradient picker
    var gh='';cvGrads.forEach(function(g,i){gh+='<div onclick="cvGrad='+i+';cvRedraw();jQuery(\'.cv-gsel\').css(\'border\',\'2px solid transparent\');jQuery(this).css(\'border\',\'2px solid #fff\')" class="cv-gsel" style="width:28px;height:28px;border-radius:6px;cursor:pointer;background:linear-gradient(135deg,'+g[0]+','+g[1]+');border:2px solid '+(i===0?'#fff':'transparent')+'"></div>'});
    $('#cv-gradients').html(gh);
    // Load products
    $.post(dza.ajax,{action:'dzqcod_canva_products',nonce:dza.nonce},function(r){
        if(!r.success)return;var o='<option value="0">— اختر منتج —</option>';
        (r.data||[]).forEach(function(p){o+='<option value="'+p.id+'" data-price="'+p.price+'" data-sale="'+p.sale+'" data-regular="'+p.regular+'" data-img="'+(p.img||'')+'" data-name="'+p.name+'" data-desc="'+p.short_desc+'">'+p.name+' — '+Number(p.price).toLocaleString()+' '+cvCur+'</option>'});
        $('#cv-product').html(o);
    });
    // Search filter
    $('#cv-search').on('input',function(){var q=this.value.toLowerCase();$('#cv-product option').each(function(){var t=$(this).text().toLowerCase();$(this).toggle(t.indexOf(q)>-1||!q)})});
    cvRedraw();
});

function cvLoadProduct(){
    var $o=jQuery('#cv-product option:selected');if(!$o.val()||$o.val()==='0')return;
    jQuery('#cv-title').val($o.data('name')||'');jQuery('#cv-price').val($o.data('price')||0);
    jQuery('#cv-old-price').val($o.data('regular')>$o.data('price')?$o.data('regular'):0);
    jQuery('#cv-desc').val($o.data('desc')||'');
    var img=$o.data('img');
    if(img){cvProductImg=new Image();cvProductImg.crossOrigin='anonymous';cvProductImg.onload=function(){
        jQuery('#cv-img-preview').html('<img src="'+img+'" style="width:100%;height:100%;object-fit:cover">');cvRedraw()};cvProductImg.src=img}
    else{cvProductImg=null;jQuery('#cv-img-preview').html('لا توجد صورة');cvRedraw()}
}

function cvRedraw(){
    var $tpl=jQuery('#cv-tpl option:selected');cvW=parseInt($tpl.data('w'))||1200;cvH=parseInt($tpl.data('h'))||628;
    cvCanvas.width=cvW;cvCanvas.height=cvH;var c=cvCtx;
    var g=cvGrads[cvGrad]||cvGrads[0];
    // Background gradient
    var grad=c.createLinearGradient(0,0,cvW,cvH);grad.addColorStop(0,g[0]);grad.addColorStop(1,g[1]);c.fillStyle=grad;c.fillRect(0,0,cvW,cvH);
    // Overlay pattern
    c.fillStyle='rgba(255,255,255,0.03)';for(var i=0;i<cvW;i+=40){c.fillRect(i,0,1,cvH)}for(var i=0;i<cvH;i+=40){c.fillRect(0,i,cvW,1)}

    var tc=jQuery('#cv-text-color').val()||'#ffffff';var isVert=cvH>cvW;// story format
    var title=jQuery('#cv-title').val()||'اسم المنتج';var price=jQuery('#cv-price').val()||'';var oldP=jQuery('#cv-old-price').val()||'';
    var desc=jQuery('#cv-desc').val()||'';var badge=jQuery('#cv-badge').val()||'';var cta=jQuery('#cv-cta').val()||'اطلب الآن';
    var ctaC=jQuery('#cv-cta-color').val()||'#ff4757';

    if(isVert){
        // STORY layout - image top, text bottom
        if(cvProductImg){c.drawImage(cvProductImg,cvW*0.1,cvH*0.05,cvW*0.8,cvH*0.4)}
        // Title
        c.font='900 '+Math.min(64,cvW/12)+'px Tajawal,Arial';c.fillStyle=tc;c.textAlign='center';c.direction='rtl';
        c.fillText(title,cvW/2,cvH*0.55);
        // Price
        if(price>0){c.font='900 '+Math.min(80,cvW/8)+'px Arial';c.fillText(Number(price).toLocaleString()+' '+cvCur,cvW/2,cvH*0.65);
            if(oldP>0){c.font='400 '+Math.min(36,cvW/20)+'px Arial';c.fillStyle='rgba(255,255,255,0.5)';var tw=c.measureText(Number(oldP).toLocaleString()+' '+cvCur);c.fillText(Number(oldP).toLocaleString()+' '+cvCur,cvW/2,cvH*0.72);c.strokeStyle='rgba(255,255,255,0.7)';c.lineWidth=2;c.beginPath();c.moveTo(cvW/2-tw.width/2,cvH*0.72-6);c.lineTo(cvW/2+tw.width/2,cvH*0.72-6);c.stroke();c.fillStyle=tc}}
        // CTA
        var cw=280,ch=60,cx=cvW/2-cw/2,cy=cvH*0.8;c.fillStyle=ctaC;cvRoundRect(c,cx,cy,cw,ch,30);c.fill();
        c.font='800 24px Tajawal,Arial';c.fillStyle='#fff';c.fillText(cta,cvW/2,cy+38);
    } else {
        // BANNER layout - image right, text left (RTL)
        if(cvProductImg){
            // Product image on right side with soft circle bg
            var imgSize=Math.min(cvH*0.7,cvW*0.3);var imgX=cvW*0.12;var imgY=(cvH-imgSize)/2;
            c.save();c.beginPath();c.arc(imgX+imgSize/2,imgY+imgSize/2,imgSize/2+10,0,Math.PI*2);c.fillStyle='rgba(255,255,255,0.1)';c.fill();c.restore();
            c.save();c.beginPath();c.arc(imgX+imgSize/2,imgY+imgSize/2,imgSize/2,0,Math.PI*2);c.clip();
            c.drawImage(cvProductImg,imgX,imgY,imgSize,imgSize);c.restore();
        }
        // Text area on right
        var tx=cvW*0.75;c.textAlign='center';c.direction='rtl';
        // Badge
        if(badge){c.font='700 '+Math.min(22,cvW/50)+'px Tajawal,Arial';c.fillStyle=ctaC;
            cvRoundRect(c,tx-100,cvH*0.1,200,32,16);c.fill();c.fillStyle='#fff';c.fillText(badge,tx,cvH*0.1+22)}
        // Title
        c.font='900 '+Math.min(52,cvW/18)+'px Tajawal,Arial';c.fillStyle=tc;
        var lines=cvWrapText(title,cvW*0.4);var ty=cvH*0.28;
        lines.forEach(function(l){c.fillText(l,tx,ty);ty+=Math.min(60,cvW/16)});
        // Desc
        if(desc){c.font='400 '+Math.min(22,cvW/45)+'px Tajawal,Arial';c.fillStyle='rgba(255,255,255,0.7)';c.fillText(desc.substring(0,50),tx,ty+10);ty+=30}
        // Price
        if(price>0){c.font='900 '+Math.min(56,cvW/15)+'px Arial';c.fillStyle=tc;
            c.fillText(Number(price).toLocaleString()+' '+cvCur,tx,ty+40);
            if(oldP>0&&oldP>price){c.font='400 '+Math.min(26,cvW/35)+'px Arial';c.fillStyle='rgba(255,255,255,0.4)';
                var ot=Number(oldP).toLocaleString()+' '+cvCur;var ow=c.measureText(ot);c.fillText(ot,tx,ty+70);
                c.strokeStyle='rgba(255,255,255,0.5)';c.lineWidth=2;c.beginPath();c.moveTo(tx-ow.width/2,ty+64);c.lineTo(tx+ow.width/2,ty+64);c.stroke()}}
        // CTA button
        var cw=Math.min(260,cvW*0.2),ch=50,cx=tx-cw/2,cy=cvH*0.82;
        c.fillStyle=ctaC;cvRoundRect(c,cx,cy,cw,ch,25);c.fill();c.shadowColor='transparent';
        c.font='800 '+Math.min(20,cvW/50)+'px Tajawal,Arial';c.fillStyle='#fff';c.fillText(cta,tx,cy+33);
    }
    // Watermark
    c.font='600 11px Arial';c.fillStyle='rgba(255,255,255,0.2)';c.textAlign='left';c.fillText('DZQCOD.com',10,cvH-10);
}

function cvWrapText(text,maxW){if(!text)return[''];cvCtx.font='900 '+Math.min(52,cvW/18)+'px Tajawal,Arial';if(cvCtx.measureText(text).width<=maxW)return[text];var words=text.split(' '),lines=[],cur='';words.forEach(function(w){var test=cur?cur+' '+w:w;if(cvCtx.measureText(test).width>maxW){if(cur)lines.push(cur);cur=w}else cur=test});if(cur)lines.push(cur);return lines.slice(0,3)}
function cvRoundRect(c,x,y,w,h,r){c.beginPath();c.moveTo(x+r,y);c.lineTo(x+w-r,y);c.quadraticCurveTo(x+w,y,x+w,y+r);c.lineTo(x+w,y+h-r);c.quadraticCurveTo(x+w,y+h,x+w-r,y+h);c.lineTo(x+r,y+h);c.quadraticCurveTo(x,y+h,x,y+h-r);c.lineTo(x,y+r);c.quadraticCurveTo(x,y,x+r,y);c.closePath()}
function cvDownload(){var a=document.createElement('a');a.download='design-'+Date.now()+'.png';a.href=cvCanvas.toDataURL('image/png');a.click()}
function cvSaveToMedia(){var d=cvCanvas.toDataURL('image/png');jQuery.post(dza.ajax,{action:'dzqcod_canva_save',nonce:dza.nonce,image_data:d},function(r){alert(r.success?'✅ تم الحفظ في مكتبة الوسائط':'❌ '+(r.data&&r.data.message?r.data.message:'خطأ'))})}
</script>
<?php
    }
}
CanvaCreative::init();
