<?php
/**
 * Web Importer (Shared Hosting friendly)
 * Run in browser:
 *   import_odoo_leads_web.php?token=YOUR_TOKEN&batch=100&cursor=0&dry=1
 * Parameters:
 *   token  : security token
 *   batch  : items per run (default 100)
 *   cursor : start index (default 0)
 *   dry    : 1 = dry-run (no write), 0 = real import
 *   since  : YYYY-MM-DD (optional) import only customers created on/after this date
 */

require_once __DIR__ . '/config.php';

/* ====== EDIT ME: Odoo & Security ====== */
$IMPORT_TOKEN   = 'SET_A_STRONG_SECRET_TOKEN';

$CUSTOMERS_DIR = __DIR__ . '/customers';
$CHATS_DIR     = __DIR__ . '/chats';
$LOOKBACK_DAYS = 30; // لمنع التكرار
/* ====================================== */

header('Content-Type: text/html; charset=utf-8');
if (!isset($_GET['token']) || $_GET['token'] !== $IMPORT_TOKEN) {
    http_response_code(403);
    echo "<h3>Forbidden</h3>"; exit;
}
$batch  = max(1, (int)($_GET['batch'] ?? 100));
$cursor = max(0, (int)($_GET['cursor'] ?? 0));
$dry    = isset($_GET['dry']) ? (int)$_GET['dry'] : 1;
$since  = isset($_GET['since']) ? $_GET['since'] : null;
$sinceTs = ($since && preg_match('/^\d{4}-\d{2}-\d{2}$/',$since)) ? strtotime("$since 00:00:00") : null;

@ini_set('max_execution_time', '25'); // shared hosting safety
ignore_user_abort(true);

/* ===== Minimal Odoo RPC helpers ===== */
function odooRpc($url,$service,$method,$args){
    $payload = json_encode(['jsonrpc'=>'2.0','method'=>'call','params'=>[
        'service'=>$service,'method'=>$method,'args'=>$args
    ],'id'=>mt_rand(1,999999)], JSON_UNESCAPED_UNICODE);
    $ch = curl_init(rtrim($url,'/').'/jsonrpc');
    curl_setopt_array($ch, [
        CURLOPT_POST=>true,
        CURLOPT_HTTPHEADER=>['Content-Type: application/json'],
        CURLOPT_POSTFIELDS=>$payload,
        CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_TIMEOUT=>25,
        CURLOPT_SSL_VERIFYPEER=>true
    ]);
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($resp===false){ $err=curl_error($ch); curl_close($ch); throw new Exception("cURL: $err"); }
    curl_close($ch);
    if ($code!==200){ throw new Exception("Odoo HTTP $code: $resp"); }
    $json = json_decode($resp, true);
    if (isset($json['error'])) throw new Exception("Odoo RPC Error: ".json_encode($json['error'], JSON_UNESCAPED_UNICODE));
    return $json['result'];
}
function odooAuthUid($o){ return odooRpc($o['url'],'common','authenticate',[$o['db'],$o['user'],$o['pass'],[]]); }
function odooSearchRead($o,$uid,$model,$domain,$fields=['id'],$limit=1){
    return odooRpc($o['url'],'object','execute_kw',[$o['db'],$uid,$o['pass'],$model,'search_read',[$domain],['fields'=>$fields,'limit'=>$limit]]);
}
function odooCreate($o,$uid,$model,$vals){
    return odooRpc($o['url'],'object','execute_kw',[$o['db'],$uid,$o['pass'],$model,'create',[$vals]]);
}
function odooWrite($o,$uid,$model,$ids,$vals){
    return odooRpc($o['url'],'object','execute_kw',[$o['db'],$uid,$o['pass'],$model,'write',[$ids,$vals]]);
}
function odooMessagePost($o,$uid,$model,$res_id,$body){
    return odooRpc($o['url'],'object','execute_kw',[$o['db'],$uid,$o['pass'],$model,'message_post',[$res_id],['body'=>$body,'message_type'=>'comment','subtype_xmlid'=>'mail.mt_note']]);
}
function odooGetOrCreateSourceId($o,$uid,$name){
    $r = odooSearchRead($o,$uid,'utm.source',[['name','=',$name]],['id','name'],1);
    return !empty($r) ? $r[0]['id'] : odooCreate($o,$uid,'utm.source',['name'=>$name]);
}
function odooFindRecentLeadByPhone($o,$uid,$phone,$days){
    if(!$phone) return null;
    $since = date('Y-m-d H:i:s', time()-$days*86400);
    $r = odooSearchRead($o,$uid,'crm.lead',
        [['type','=','lead'], ['phone','ilike',$phone], ['create_date','>=',$since]],
        ['id','name','phone'], 1);
    return $r[0]['id'] ?? null;
}
/* ==================================== */

function normalizePhone($p){
    $p = preg_replace('/\D+/', '', (string)$p);
    if (preg_match('/^0?1\d{9}$/', $p)) $p = '20'.ltrim($p,'0'); // مصر
    return $p;
}

$files = glob($CUSTOMERS_DIR.'/*.json');
natsort($files);
$files = array_values($files);
$total = count($files);

echo "<h3>Odoo Import (Web)</h3>";
echo "<p>Total customer files found: <b>$total</b></p>";
echo "<p>Cursor: <b>$cursor</b> | Batch: <b>$batch</b> | Dry-run: <b>".($dry? 'YES':'NO')."</b>".($since?" | Since: <b>$since</b>":"")."</p>";

if ($cursor >= $total) {
    echo "<p>✅ Done. No more files.</p>";
    exit;
}

try {
    $uid = odooAuthUid($odoo);
    if (!$uid) throw new Exception('Auth failed');
    $sourceId = odooGetOrCreateSourceId($odoo,$uid,$odoo['default_source']);
} catch (Throwable $e) {
    echo "<p style='color:red'>Odoo error: ".htmlspecialchars($e->getMessage(),ENT_QUOTES,'UTF-8')."</p>";
    exit;
}

$end = min($total, $cursor + $batch);
$created=0; $updated=0; $skipped=0; $errors=0;

echo "<table border='1' cellpadding='6' cellspacing='0'><tr><th>#</th><th>Phone</th><th>Action</th><th>Note</th></tr>";

for ($i=$cursor; $i<$end; $i++) {
    $file = $files[$i];
    $rowNum = $i+1;
    $note = '';
    try{
        $raw = @file_get_contents($file);
        if ($raw===false) { $errors++; $note='read error'; throw new Exception('read error'); }
        $cust = json_decode($raw,true);
        if (!is_array($cust)) { $errors++; $note='json error'; throw new Exception('json error'); }

        if ($sinceTs && !empty($cust['created_at']) && $cust['created_at'] < $sinceTs) {
            $skipped++; echo "<tr><td>$rowNum</td><td>-</td><td>skip</td><td>before since</td></tr>"; continue;
        }

        $phoneFile = basename($file,'.json');
        $phone = normalizePhone($cust['phone'] ?? $phoneFile);
        if (!$phone) { $skipped++; echo "<tr><td>$rowNum</td><td>-</td><td>skip</td><td>no phone</td></tr>"; continue; }

        // وصف من الشات
        $desc = '';
        $chatPath = $CHATS_DIR.'/'.basename($phoneFile).'.json';
        if (file_exists($chatPath)) {
            $chat = json_decode(@file_get_contents($chatPath), true) ?: [];
            $userMsgs = array_values(array_filter($chat, fn($m)=>($m['role']??'')==='user'));
            if (!empty($userMsgs)) {
                $first = $userMsgs[0]['content'] ?? '';
                $last  = end($userMsgs)['content'] ?? '';
                $desc = "أول رسالة:\n".mb_substr($first,0,400)."\n\nآخر رسالة:\n".mb_substr($last,0,400);
            }
        }
        if ($desc==='') {
            $lastNote = end($cust['notes'] ?? [])['msg'] ?? '';
            $desc = $lastNote ? ("ملاحظة سابقة:\n".mb_substr($lastNote,0,600)) : 'تم الاستيراد من بوت واتساب.';
        }

        $name  = $cust['name'] ?? ($cust['contact_name'] ?? null);
        $email = $cust['email'] ?? null;
        if (!$email && preg_match('/[A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,}/i', $desc, $m)) $email=$m[0];

        $vals = [
            'type'         => 'lead',
            'name'         => $name ?: 'WhatsApp Inquiry',
            'contact_name' => $name ?: null,
            'phone'        => $phone,
            'email_from'   => $email,
            'description'  => $desc,
            'source_id'    => $sourceId,
            'referred'     => 'WHATSAPP',
        ];

        if ($dry) {
            echo "<tr><td>$rowNum</td><td>$phone</td><td>DRY</td><td>will ".(odooFindRecentLeadByPhone($odoo,$uid,$phone,$LOOKBACK_DAYS)?'update':'create')."</td></tr>";
            continue;
        }

        $existingId = odooFindRecentLeadByPhone($odoo,$uid,$phone,$LOOKBACK_DAYS);
        if ($existingId) {
            odooWrite($odoo,$uid,'crm.lead',[$existingId],$vals);
            odooMessagePost($odoo,$uid,'crm.lead',$existingId,"<p><i>تحديث من استيراد البوت (ويب)</i></p>");
            $updated++; echo "<tr><td>$rowNum</td><td>$phone</td><td>update</td><td>ID $existingId</td></tr>";
        } else {
            $newId = odooCreate($odoo,$uid,'crm.lead',$vals);
            odooMessagePost($odoo,$uid,'crm.lead',$newId,"<p><i>تم الإنشاء من استيراد البوت (ويب)</i></p>");
            $created++; echo "<tr><td>$rowNum</td><td>$phone</td><td>create</td><td>ID $newId</td></tr>";
        }

    } catch (Throwable $e) {
        $errors++;
        $msg = htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
        echo "<tr><td>$rowNum</td><td>-</td><td style='color:red'>error</td><td>$msg</td></tr>";
    }
}
echo "</table>";

$next = $end;
echo "<p>Batch result: created=$created, updated=$updated, skipped=$skipped, errors=$errors</p>";

if ($next < $total) {
    $qs = http_build_query([
        'token'=>$IMPORT_TOKEN,
        'batch'=>$batch,
        'cursor'=>$next,
        'dry'=>$dry,
        'since'=>$since
    ]);
    echo "<p><a href='?{$qs}'>Continue &raquo;</a></p>";
    // أو Auto-continue كل 2 ثانية:
    echo "<script>setTimeout(function(){location.href='?{$qs}';}, 2000);</script>";
} else {
    echo "<p>✅ Completed all files.</p>";
}
