<?php
namespace DZQCOD\Addons;
if (!defined('ABSPATH')) exit;
if (!\DZQCOD\Modules::is_on('cohort')) return;

class CohortAnalysis {
    public static function init():void{
        add_action('wp_ajax_dzqcod_cohort_data',[self::class,'get_data']);
        add_action('dzqcod_admin_page_cohort',[self::class,'admin_page']);
    }

    public static function get_data():void{
        check_ajax_referer('dzqcod_admin','nonce');
        $months=absint($_POST['months']??6);if($months<2)$months=2;if($months>12)$months=12;
        $cohorts=[];
        for($m=0;$m<$months;$m++){
            $start=gmdate('Y-m-01',strtotime("-{$m} months"));$end=gmdate('Y-m-t',strtotime("-{$m} months"));
            $label=gmdate('Y/m',strtotime($start));
            // New customers in this month
            $new=wc_get_orders(['date_created'=>$start.'...'.$end,'return'=>'ids','limit'=>-1,'status'=>['wc-processing','wc-completed','wc-delivered','wc-shipped']]);
            $emails=[];foreach($new as $oid){$o=wc_get_order($oid);if($o)$emails[$o->get_billing_email()]=1;}
            $total=count($emails);
            // Retention: how many came back in subsequent months
            $retention=[$total];
            for($r=1;$r<=$m&&$r<=5;$r++){
                $rs=gmdate('Y-m-01',strtotime("-".($m-$r)." months"));$re=gmdate('Y-m-t',strtotime("-".($m-$r)." months"));
                $repeat=wc_get_orders(['date_created'=>$rs.'...'.$re,'return'=>'ids','limit'=>-1,'status'=>['wc-processing','wc-completed','wc-delivered']]);
                $back=0;foreach($repeat as $rid){$ro=wc_get_order($rid);if($ro&&isset($emails[$ro->get_billing_email()]))$back++;}
                $retention[]=$back;
            }
            $cohorts[]=['label'=>$label,'total'=>$total,'retention'=>$retention];
        }
        // Top stats
        $total_customers=(int)wc_get_orders(['return'=>'ids','limit'=>-1,'status'=>['wc-completed','wc-delivered']]);
        $repeat_rate=0;
        wp_send_json_success(['cohorts'=>array_reverse($cohorts),'months'=>$months]);
    }

    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">📊 Cohort Analysis — تحليل الزبائن المتكررين</h2>
<div style="display:flex;gap:8px;margin-bottom:16px;align-items:center">
<select id="ch-months" style="padding:8px;border:1px solid #ddd;border-radius:6px">
<option value="3">3 أشهر</option><option value="6" selected>6 أشهر</option><option value="9">9 أشهر</option><option value="12">12 شهر</option></select>
<button onclick="chLoad()" style="padding:8px 20px;background:#6366F1;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:700">📊 تحليل</button>
</div>
<div id="ch-result" style="background:#fff;border-radius:12px;padding:20px;box-shadow:0 2px 8px rgba(0,0,0,.06)"><div style="text-align:center;color:#aaa;padding:30px">اضغط تحليل لعرض البيانات</div></div>
</div>
<script>
function chLoad(){jQuery('#ch-result').html('<div style="text-align:center;padding:30px;color:#888">⏳ جاري التحليل...</div>');
jQuery.post(dza.ajax,{action:'dzqcod_cohort_data',nonce:dza.nonce,months:jQuery('#ch-months').val()},function(r){
    if(!r.success)return;var d=r.data.cohorts,h='<h4 style="margin:0 0 12px">📊 جدول Cohort — معدل العودة</h4>';
    h+='<div style="overflow-x:auto"><table style="width:100%;border-collapse:collapse;font-size:11px;text-align:center"><thead><tr style="background:#f8f9fa"><th style="padding:8px;text-align:right;font-weight:700">الشهر</th><th style="padding:8px;font-weight:700">زبائن جدد</th>';
    for(var i=0;i<6;i++)h+='<th style="padding:8px;font-weight:700">شهر '+(i+1)+'</th>';h+='</tr></thead><tbody>';
    d.forEach(function(c){h+='<tr><td style="padding:6px;text-align:right;font-weight:700;color:#6366F1">'+c.label+'</td><td style="padding:6px;font-weight:700">'+c.total+'</td>';
        for(var i=0;i<6;i++){var v=c.retention[i]!==undefined?c.retention[i]:'-';var pct=c.total>0&&typeof v==='number'?Math.round(v/c.total*100):0;
            var bg=typeof v==='number'?'rgba(99,102,241,'+(pct/100*0.6+0.05)+')':'transparent';
            h+='<td style="padding:6px;background:'+bg+';color:'+(pct>30?'#fff':'#333')+';font-weight:700">'+(typeof v==='number'?v+(c.total>0?' <span style=font-size:9px>('+pct+'%)</span>':''):'-')+'</td>'}h+='</tr>'});
    h+='</tbody></table></div>';jQuery('#ch-result').html(h)})}
</script>
<?php
    }
}
CohortAnalysis::init();
