<?php
$uid  = trim($_POST['uid']  ?? '');
$key  = trim($_POST['key']  ?? '');
$phone= trim($_POST['phone'] ?? '0779051994');

function sPost($url,$d){
    $ch=curl_init($url);
    curl_setopt_array($ch,[CURLOPT_POST=>1,CURLOPT_RETURNTRANSFER=>1,CURLOPT_TIMEOUT=>15,
        CURLOPT_SSL_VERIFYPEER=>0,CURLOPT_POSTFIELDS=>http_build_query($d),
        CURLOPT_HTTPHEADER=>['Content-Type: application/x-www-form-urlencoded']]);
    $r=curl_exec($ch);$e=curl_error($ch);curl_close($ch);
    if($e) return ['success'=>false,'message'=>'cURL:'.$e];
    return json_decode($r,true)??['success'=>false,'message'=>substr($r,0,200)];
}
function sGet($url){
    $ch=curl_init($url);
    curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>1,CURLOPT_TIMEOUT=>15,CURLOPT_SSL_VERIFYPEER=>0]);
    $r=curl_exec($ch);curl_close($ch);
    return json_decode($r,true)??[];
}

$submitted = !empty($_POST['uid']);
$results   = [];

if($submitted){
    // Format phone
    $p = preg_replace('/[\s\-]/','',$phone);
    if(preg_match('/^0[0-9]{9}$/',$p))     $p='+94'.substr($p,1);
    elseif(preg_match('/^94\d{9}$/',$p))   $p='+'.$p;
    elseif(preg_match('/^7[0-9]{8}$/',$p)) $p='+94'.$p;

    // Try all variations of sender ID
    $tryIds = ['SMSlenzDEMO','SMSLENZ','smslenz','Smslenz','DEMO','SMSLenz'];
    foreach($tryIds as $sid){
        $r = sPost("https://smslenz.lk/api/send-sms",[
            'user_id'  =>$uid,'api_key'=>$key,
            'sender_id'=>$sid,'contact'=>$p,
            'message'  =>'Test '.date('H:i')
        ]);
        $results[$sid] = $r;
        if($r['success']??false) break; // Stop on first success
    }

    $successSid = null;
    foreach($results as $sid=>$r){ if($r['success']??false){ $successSid=$sid; break; } }
}
?>
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>SMS Fix</title>
<style>
body{font-family:Arial;max-width:640px;margin:30px auto;padding:16px;background:#f1f5f9}
.c{background:#fff;border-radius:10px;padding:22px;margin-bottom:14px;box-shadow:0 1px 4px rgba(0,0,0,.08)}
label{font-size:.82rem;font-weight:700;display:block;margin-bottom:3px}
input{width:100%;border:1px solid #d1d5db;border-radius:7px;padding:9px;font-size:.92rem;margin-bottom:12px;box-sizing:border-box}
.btn{width:100%;background:#2563eb;color:#fff;border:none;border-radius:7px;padding:11px;font-size:1rem;font-weight:700;cursor:pointer}
.ok{background:#f0fdf4;border:1px solid #86efac;color:#166534;padding:9px 14px;border-radius:7px;font-weight:700;margin:6px 0}
.fail{background:#fef2f2;border:1px solid #fca5a5;color:#991b1b;padding:9px 14px;border-radius:7px;margin:6px 0}
.warn{background:#fffbeb;border:1px solid #fde68a;color:#92400e;padding:10px 14px;border-radius:7px;margin:6px 0;line-height:1.7}
table{width:100%;border-collapse:collapse;font-size:.85rem}
td,th{padding:8px 10px;border-bottom:1px solid #f1f5f9;text-align:left}
th{background:#f8fafc;font-weight:700;color:#64748b;font-size:.75rem;text-transform:uppercase}
.y{color:#16a34a;font-weight:700}.n{color:#dc2626}
</style></head><body>

<div class="c">
<h2 style="margin:0 0 14px;color:#0f172a">SMSlenz Sender ID Fix</h2>
<form method="POST">
<label>User ID</label>
<input name="uid" value="<?=htmlspecialchars($uid)?>" required placeholder="2141">
<label>API Key</label>
<input name="key" value="<?=htmlspecialchars($key)?>" required placeholder="191e976c-...">
<label>Test Phone</label>
<input name="phone" value="<?=htmlspecialchars($phone)?>">
<button class="btn" type="submit">Try All Sender ID Variations →</button>
</form>
</div>

<?php if($submitted): ?>
<div class="c">
<h3 style="margin:0 0 12px">Testing Sender ID Variations for <?=htmlspecialchars($p)?></h3>
<table>
<tr><th>Sender ID</th><th>Result</th></tr>
<?php foreach($results as $sid=>$r):
    $ok=$r['success']??false;
?>
<tr>
    <td><code><?=htmlspecialchars($sid)?></code></td>
    <td class="<?=$ok?'y':'n'?>"><?=$ok?'✅ WORKS!':'❌ '.htmlspecialchars($r['message']??'')?></td>
</tr>
<?php endforeach; ?>
</table>

<?php if($successSid): ?>
<p class="ok">✅ Working sender ID found: <b><?=htmlspecialchars($successSid)?></b></p>
<?php
// Save to DB
try{
    $pdo=new PDO('mysql:host=localhost;dbname=gymprosl_mjpos_db;charset=utf8mb4',
        'gymprosl_mjpos_db','Ishara@1994Bubu',[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
    foreach([
        'sms_user_id'  =>$uid,
        'sms_api_key'  =>$key,
        'sms_sender_id'=>$successSid,
        'sms_enabled'  =>'1'
    ] as $k=>$v)
        $pdo->prepare("INSERT INTO settings(setting_key,setting_value)VALUES(?,?)ON DUPLICATE KEY UPDATE setting_value=?")->execute([$k,$v,$v]);
    echo "<p class='ok'>✅ Saved to MJPOS! SMS is now active with sender: <b>$successSid</b></p>";
    echo "<p><b>Delete this file now!</b> Go test a real POS sale → customer gets SMS ✅</p>";
}catch(Exception $e){ echo "<p class='fail'>DB: ".htmlspecialchars($e->getMessage())."</p>"; }
?>
<?php else: ?>
<div class="warn">
<b>❌ All sender ID variations failed.</b><br><br>
Oya account eke sender ID approve karanna oni. Steps:<br><br>
<b>1.</b> <a href="https://smslenz.lk" target="_blank">smslenz.lk</a> → Login<br>
<b>2.</b> Left menu → <b>Sender IDs</b> → <b>+ New Sender ID</b><br>
<b>3.</b> Type: <code>SMSlenzDEMO</code> (testing walata) OR oya brand name<br>
<b>4.</b> Submit → Approval kalin 24hrs gannawa<br>
<b>5.</b> Approved wunama mama SSH karala activate karannam<br><br>
<b>OR:</b> SMSlenz support contact karanna → enable demo sender ID request karanna:<br>
📧 support@smslenz.lk<br>
User ID: <?=htmlspecialchars($uid)?>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
<p style="text-align:center;color:#d97706;font-size:.75rem">⚠ Delete <code>sms_test.php</code> after done!</p>
</body></html>