<?php
require_once '../includes/config.php';
require_once '../includes/ecare.php';
requireAdmin();
$db = getDB();

// Create api_logs table
try { $db->exec("CREATE TABLE IF NOT EXISTS api_logs (id INT AUTO_INCREMENT PRIMARY KEY, operator VARCHAR(50), request_data TEXT, response_data TEXT, status_code INT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"); } catch(Exception $e) {}

$msg = null;
if (isset($_GET['ok'])) $msg = ['ok'=>true,'text'=>'✅ Saved successfully!'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'save_creds') {
        $fields = ['ecare_username','ecare_password','ecare_mode','ecare_num_type'];
        foreach ($fields as $f) {
            $v = trim($_POST[$f] ?? '');
            $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute([$f,$v,$v]);
        }
        // Per-operator mode
        $ops = ['GP','BL','RB','AL','TT'];
        foreach ($ops as $op) {
            $v = $_POST['op_api_'.$op] ?? 'none';
            $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['ecare_op_'.$op, $v, $v]);
        }
        $msg = ['ok'=>true,'text'=>'✅ ECARE Settings saved!'];
        header('Location: ecare_settings.php?ok=1'); exit;
    }

    if ($action === 'test_balance') {
        $res = ecareBalance();
        if ($res['status'] === 'OK') {
            $msg = ['ok'=>true,'text'=>"✅ Connected! Main Balance: ৳{$res['main_balance']} | Stock: ৳{$res['stock_balance']} | Commission: {$res['commission_rate']}% ({$res['commission_type']})"];
            header('Location: ecare_settings.php?ok=1'); exit;
        } else {
            $msg = ['ok'=>false,'text'=>'❌ Failed: '.($res['message']??json_encode($res['raw']??$res))];
        }
    }

    if ($action === 'test_recharge') {
        $phone  = trim($_POST['test_phone'] ?? '');
        $amount = intval($_POST['test_amount'] ?? 0);
        $opCode = trim($_POST['test_op'] ?? 'GP');
        $numType= trim($_POST['test_numtype'] ?? 'prepaid');
        $refId  = 'TEST'.time();
        if (!$phone || !$amount) {
            $msg = ['ok'=>false,'text'=>'Enter phone and amount'];
        } else {
            $res = ecareRecharge($phone, $amount, $opCode, $numType, $refId);
            if ($res['result']) {
                $msg = ['ok'=>true,'text'=>"✅ Recharge Received! TrxID: {$res['trxid']} | {$res['message']}"];
                header('Location: ecare_settings.php?ok=1'); exit;
            } else {
                $msg = ['ok'=>false,'text'=>"❌ {$res['rc_status']}: {$res['message']} | Raw: ".json_encode($res['raw'])];
            }
        }
    }

    if ($action === 'test_status') {
        $refId = trim($_POST['status_ref'] ?? '');
        if (!$refId) { $msg = ['ok'=>false,'text'=>'Enter reference ID']; }
        else {
            $res = ecareStatus($refId);
            $msg = ['ok'=>$res['status']==='OK','text'=>"Status: {$res['status']} | RC: {$res['rc_status']} | TrxID: {$res['trxid']} | {$res['message']}"];
        }
    }

    if ($action === 'check_offers') {
        $opCode = trim($_POST['offer_op'] ?? '');
        $phone  = trim($_POST['offer_phone'] ?? '');
        $res    = ecareOfferPacks($opCode, $phone);
        $rawStr = json_encode($res, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
        $msg = ['ok'=>isset($res['STATUS']) && $res['STATUS']==='OK','text'=>'Response: '.$rawStr,'raw'=>true];
        header('Location: ecare_settings.php?ok=1'); exit;
    }
}

// Load settings
$ecareUser    = getSetting('ecare_username') ?: '';
$ecarePass    = getSetting('ecare_password') ?: '';
$ecareMode    = getSetting('ecare_mode') ?: 'manual';
$ecareNumType = getSetting('ecare_num_type') ?: '1';
$opApis = [];
foreach (['GP','BL','RB','AL','TT'] as $op) {
    $opApis[$op] = getSetting('ecare_op_'.$op) ?: 'none';
}

// Recent logs
try {
    $logs = $db->query("SELECT * FROM api_logs WHERE operator='ecare' ORDER BY created_at DESC LIMIT 10")->fetchAll();
} catch(Exception $e) { $logs = []; }

$opNames = ['GP'=>'Grameenphone (3/7)','BL'=>'Banglalink (4/9)','RB'=>'Robi (8)','AL'=>'Airtel (6)','TT'=>'Teletalk (5)'];
$opColors = ['GP'=>'#009B3A','BL'=>'#FF6B00','RB'=>'#E4001D','AL'=>'#F7941D','TT'=>'#1C3F7A'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>ECARE API Settings - Admin</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="../assets/css/admin.css">
<style>
.card{background:white;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,0.06);margin-bottom:16px;overflow:hidden}
.card-h{padding:14px 18px;border-bottom:1px solid #f5f5f5;font-size:14px;font-weight:700;display:flex;align-items:center;gap:8px;justify-content:space-between}
.card-b{padding:18px}
.alert{padding:11px 16px;border-radius:10px;font-size:13px;font-weight:600;margin-bottom:14px;word-break:break-all}
.alert-ok{background:#f0fff4;color:#276749;border:1px solid #c6f6d5}
.alert-err{background:#fff5f5;color:#c53030;border:1px solid #fed7d7}
.fg{display:flex;flex-direction:column;gap:4px;margin-bottom:12px}
.fg label{font-size:12px;font-weight:700;color:#555;text-transform:uppercase;letter-spacing:0.4px}
.fg input,.fg select{padding:10px 12px;border:2px solid #e8ecf4;border-radius:10px;font-size:13px;outline:none;width:100%}
.fg input:focus,.fg select:focus{border-color:var(--primary)}
.frow{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.btn{padding:10px 18px;border:none;border-radius:10px;font-size:13px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:6px}
.btn-primary{background:var(--primary);color:white}
.btn-green{background:#38a169;color:white}
.btn-orange{background:#d69e2e;color:white}
.btn-purple{background:#805ad5;color:white}
.btn-sm{padding:7px 13px;font-size:12px}
.op-row{display:flex;align-items:center;justify-content:space-between;padding:10px 0;border-bottom:1px solid #f5f5f5;gap:12px}
.op-row:last-child{border:none}
.op-label{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:700}
.op-dot{width:10px;height:10px;border-radius:50%;flex-shrink:0}
.api-select{padding:7px 10px;border:2px solid #e8ecf4;border-radius:9px;font-size:12px;font-weight:700;outline:none;min-width:140px}
.api-select:focus{border-color:var(--primary)}
.api-url-box{background:#1a1a2e;color:#00ff88;font-family:monospace;font-size:11px;padding:12px;border-radius:10px;word-break:break-all;line-height:1.7;margin-bottom:12px}
.api-url-box .hl{color:#ffd54f}
.resp-table{width:100%;border-collapse:collapse;font-size:12px;margin-top:8px}
.resp-table th{background:#f0f4ff;padding:7px 10px;text-align:left;font-weight:700;color:#555;border:1px solid #e8ecf4}
.resp-table td{padding:7px 10px;border:1px solid #f0f0f0;color:#333}
.resp-table tr:nth-child(even) td{background:#fafafa}
.status-ok{color:#38a169;font-weight:700}.status-fail{color:#e53e3e;font-weight:700}
.test-section{background:#f8fafc;border-radius:12px;padding:14px;margin-bottom:12px}
.test-section h4{font-size:13px;font-weight:700;color:#555;margin-bottom:10px;display:flex;align-items:center;gap:6px}
.log-item{background:#f8fafc;border-radius:8px;padding:10px 12px;margin-bottom:6px;font-family:monospace;font-size:11px;color:#555}
.log-time{color:#aaa;font-size:10px;margin-bottom:3px}
.tabs{display:flex;gap:6px;margin-bottom:16px;flex-wrap:wrap}
.tab-btn{padding:8px 16px;border:2px solid #e8ecf4;background:white;border-radius:9px;font-size:12px;font-weight:700;cursor:pointer;color:#666}
.tab-btn.active{background:var(--primary);color:white;border-color:var(--primary)}
.tab-content{display:none}
.tab-content.show{display:block}
</style>
</head>
<body>
<?php include '../includes/admin_sidebar.php'; ?>
<div class="main">
<div class="topbar">
    <div class="topbar-left">
        <button class="menu-toggle" onclick="openSidebar()"><i class="fas fa-bars"></i></button>
        <span class="topbar-title">⚡ ECARE API Settings</span>
    </div>
    <div class="topbar-right">
        <span style="background:<?= $ecareUser?'#f0fff4':'#fff5f5' ?>;color:<?= $ecareUser?'#276749':'#c53030' ?>;padding:5px 12px;border-radius:20px;font-size:12px;font-weight:700">
            <?= $ecareUser ? '✅ Configured' : '⚠️ Not Configured' ?>
        </span>
    </div>
</div>
<div class="content">

<?php if($msg): ?>
<div class="alert <?= $msg['ok']?'alert-ok':'alert-err' ?>">
    <?= $msg['ok']?'✅':'❌' ?>
    <?php if(isset($msg['raw'])): ?>
    <pre style="margin:0;white-space:pre-wrap;font-size:11px"><?= htmlspecialchars($msg['text']) ?></pre>
    <?php else: ?>
    <?= htmlspecialchars($msg['text']) ?>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- Tabs -->
<div class="tabs">
    <button class="tab-btn active" onclick="showTab('settings',this)"><i class="fas fa-cog"></i> Settings</button>
    <button class="tab-btn" onclick="showTab('test',this)"><i class="fas fa-flask"></i> Test API</button>
    <button class="tab-btn" onclick="showTab('docs',this)"><i class="fas fa-book"></i> API Docs</button>
    <button class="tab-btn" onclick="showTab('logs',this)"><i class="fas fa-history"></i> Logs</button>
</div>

<!-- ============ SETTINGS TAB ============ -->
<div class="tab-content show" id="tab-settings">
<form method="POST">
    <input type="hidden" name="action" value="save_creds">

    <!-- Credentials -->
    <div class="card">
        <div class="card-h"><span><i class="fas fa-key" style="color:#d69e2e"></i> API Credentials</span></div>
        <div class="card-b">
            <div class="api-url-box">
                <span class="hl">Base URL:</span> http://118.179.129.98/myportal/api/rechargeapi/recharge_api_thirdparty.php<br>
                <span class="hl">Version:</span> 2021.11.20.007
            </div>
            <div class="frow">
                <div class="fg">
                    <label>API Username (access_id)</label>
                    <input type="text" name="ecare_username" value="<?= htmlspecialchars($ecareUser) ?>" placeholder="Your API username" required>
                </div>
                <div class="fg">
                    <label>API Password (access_pass)</label>
                    <input type="password" name="ecare_password" id="ecarePass" value="<?= htmlspecialchars($ecarePass) ?>" placeholder="Your API password">
                </div>
            </div>
            <div class="frow">
                <div class="fg">
                    <label>Default Mode</label>
                    <select name="ecare_mode">
                        <option value="auto"   <?= $ecareMode==='auto'?'selected':''   ?>>⚡ Auto (instant recharge)</option>
                        <option value="manual" <?= $ecareMode==='manual'?'selected':'' ?>>🖐 Manual (admin approve)</option>
                    </select>
                </div>
                <div class="fg">
                    <label>Default Number Type</label>
                    <select name="ecare_num_type">
                        <option value="1" <?= $ecareNumType==='1'?'selected':'' ?>>Prepaid (1)</option>
                        <option value="2" <?= $ecareNumType==='2'?'selected':'' ?>>Postpaid (2)</option>
                        <option value="3" <?= $ecareNumType==='3'?'selected':'' ?>>Skitto (3)</option>
                        <option value="4" <?= $ecareNumType==='4'?'selected':'' ?>>PowerLoad/G.Store/Amar Offer (4)</option>
                    </select>
                </div>
            </div>
        </div>
    </div>

    <!-- Per-Operator API Selection -->
    <div class="card">
        <div class="card-h"><span><i class="fas fa-sim-card" style="color:#805ad5"></i> Operator-wise API Selection</span>
            <span style="font-size:11px;color:#aaa;font-weight:500">কোন operator এর জন্য কোন API ব্যবহার হবে</span>
        </div>
        <div class="card-b" style="padding:14px 18px">
            <?php foreach($opNames as $code=>$name): ?>
            <div class="op-row">
                <div class="op-label">
                    <div class="op-dot" style="background:<?= $opColors[$code] ?>"></div>
                    <span><?= $name ?></span>
                </div>
                <select name="op_api_<?= $code ?>" class="api-select">
                    <option value="none"        <?= $opApis[$code]==='none'?'selected':''        ?>>❌ Disabled</option>
                    <option value="successtopup" <?= $opApis[$code]==='successtopup'?'selected':'' ?>>🔄 SuccessTopUp</option>
                    <option value="ecare"        <?= $opApis[$code]==='ecare'?'selected':''        ?>>⚡ ECARE</option>
                    <option value="manual"       <?= $opApis[$code]==='manual'?'selected':''       ?>>🖐 Manual Only</option>
                </select>
            </div>
            <?php endforeach; ?>
            <div style="font-size:11px;color:#aaa;margin-top:10px">💡 Per-operator setting override করবে global mode কে</div>
        </div>
    </div>

    <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center">
        <i class="fas fa-save"></i> Save Settings
    </button>
</form>

<!-- Balance Check -->
<div style="margin-top:14px">
    <form method="POST" style="display:inline-block">
        <input type="hidden" name="action" value="test_balance">
        <button type="submit" class="btn btn-green"><i class="fas fa-wallet"></i> Check ECARE Balance</button>
    </form>
</div>
</div>

<!-- ============ TEST TAB ============ -->
<div class="tab-content" id="tab-test">

    <!-- Test Recharge -->
    <div class="card">
        <div class="card-h"><i class="fas fa-mobile-alt" style="color:#38a169"></i> Test Recharge (MRC)</div>
        <div class="card-b">
            <form method="POST">
                <input type="hidden" name="action" value="test_recharge">
                <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:10px;margin-bottom:12px">
                    <div class="fg" style="margin:0">
                        <label>Phone</label>
                        <input type="text" name="test_phone" placeholder="01700000000">
                    </div>
                    <div class="fg" style="margin:0">
                        <label>Amount (BDT)</label>
                        <input type="number" name="test_amount" placeholder="20" min="10">
                    </div>
                    <div class="fg" style="margin:0">
                        <label>Operator</label>
                        <select name="test_op">
                            <?php foreach($opNames as $c=>$n): ?>
                            <option value="<?= $c ?>"><?= $c ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="fg" style="margin:0">
                        <label>Number Type</label>
                        <select name="test_numtype">
                            <option value="prepaid">Prepaid</option>
                            <option value="postpaid">Postpaid</option>
                            <option value="skitto">Skitto</option>
                            <option value="powerload">PowerLoad</option>
                        </select>
                    </div>
                </div>
                <button type="submit" class="btn btn-green btn-sm" onclick="return confirm('Send real recharge request?')">
                    <i class="fas fa-bolt"></i> Send Test Recharge
                </button>
            </form>
        </div>
    </div>

    <!-- Status Check -->
    <div class="card">
        <div class="card-h"><i class="fas fa-search" style="color:#3182ce"></i> Check Recharge Status (MRCSTATUS)</div>
        <div class="card-b">
            <form method="POST">
                <input type="hidden" name="action" value="test_status">
                <div style="display:flex;gap:10px">
                    <div class="fg" style="flex:1;margin:0">
                        <label>Reference ID (refid)</label>
                        <input type="text" name="status_ref" placeholder="e.g. MTS2336355464">
                    </div>
                    <div style="display:flex;align-items:flex-end">
                        <button type="submit" class="btn btn-purple btn-sm"><i class="fas fa-search"></i> Check Status</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Offer Packs -->
    <div class="card">
        <div class="card-h"><i class="fas fa-list" style="color:#d69e2e"></i> Offer Pack List (OFFERPACK)</div>
        <div class="card-b">
            <form method="POST">
                <input type="hidden" name="action" value="check_offers">
                <div style="display:flex;gap:10px;align-items:flex-end">
                    <div class="fg" style="margin:0">
                        <label>Operator</label>
                        <select name="offer_op">
                            <option value="">All</option>
                            <?php foreach($opNames as $c=>$n): ?>
                            <option value="<?= $c ?>"><?= $c ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="fg" style="flex:1;margin:0">
                        <label>Phone (optional)</label>
                        <input type="text" name="offer_phone" placeholder="01700000000">
                    </div>
                    <div>
                        <button type="submit" class="btn btn-orange btn-sm"><i class="fas fa-download"></i> Get Offers</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ============ DOCS TAB ============ -->
<div class="tab-content" id="tab-docs">
<div class="card">
    <div class="card-h"><i class="fas fa-book" style="color:#805ad5"></i> ECARE API Documentation</div>
    <div class="card-b">

        <div style="font-weight:700;margin-bottom:8px;color:#555">📡 Recharge API (MRC)</div>
        <div class="api-url-box">http://118.179.129.98/myportal/api/rechargeapi/recharge_api_thirdparty.php<br>
?<span class="hl">access_id</span>=USERNAME&<span class="hl">access_pass</span>=PASSWORD<br>
&<span class="hl">service</span>=MRC&<span class="hl">operator</span>=7&<span class="hl">number_type</span>=1<br>
&<span class="hl">number</span>=01700000000&<span class="hl">amount</span>=20&<span class="hl">refid</span>=UNIQUE_REF</div>

        <div style="font-weight:700;margin:12px 0 8px;color:#555">📊 Operator Codes</div>
        <table class="resp-table">
            <tr><th>Operator</th><th>Code</th><th>Alt Code</th></tr>
            <tr><td>Grameenphone</td><td>7</td><td>3</td></tr>
            <tr><td>Banglalink</td><td>4</td><td>9</td></tr>
            <tr><td>Robi</td><td>8</td><td>—</td></tr>
            <tr><td>Airtel</td><td>6</td><td>—</td></tr>
            <tr><td>Teletalk</td><td>5</td><td>—</td></tr>
        </table>

        <div style="font-weight:700;margin:12px 0 8px;color:#555">📲 Number Types</div>
        <table class="resp-table">
            <tr><th>Type</th><th>Code</th></tr>
            <tr><td>Prepaid</td><td>1</td></tr>
            <tr><td>Postpaid</td><td>2</td></tr>
            <tr><td>Skitto</td><td>3</td></tr>
            <tr><td>PowerLoad / G.Store / Amar Offer</td><td>4</td></tr>
        </table>

        <div style="font-weight:700;margin:12px 0 8px;color:#555">📋 Recharge Response</div>
        <table class="resp-table">
            <tr><th>STATUS</th><th>RECHARGE_STATUS</th><th>Meaning</th></tr>
            <tr><td class="status-ok">OK</td><td>RECEIVED</td><td>✅ Request accepted</td></tr>
            <tr><td class="status-fail">FAILED</td><td>DUPLICATE</td><td>Duplicate ref/number</td></tr>
            <tr><td class="status-fail">FAILED</td><td>LOWBALANCE</td><td>Insufficient balance</td></tr>
            <tr><td class="status-fail">FAILED</td><td>FAILED</td><td>Request failed</td></tr>
            <tr><td class="status-fail">FAILED</td><td>REJECT</td><td>Invalid credentials</td></tr>
        </table>

        <div style="font-weight:700;margin:12px 0 8px;color:#555">🔍 Status Check (MRCSTATUS)</div>
        <div class="api-url-box">?<span class="hl">service</span>=MRCSTATUS&<span class="hl">refid</span>=YOUR_REF_ID</div>
        <table class="resp-table">
            <tr><th>RECHARGE_STATUS</th><th>Meaning</th></tr>
            <tr><td class="status-ok">SUCCESS</td><td>✅ Recharge done</td></tr>
            <tr><td style="color:#d69e2e;font-weight:700">PENDING</td><td>⏳ Processing</td></tr>
            <tr><td style="color:#3182ce;font-weight:700">PROCESSING</td><td>🔄 Being processed</td></tr>
            <tr><td class="status-fail">FAILED</td><td>❌ Failed</td></tr>
            <tr><td class="status-fail">INVALIDREF</td><td>❌ Wrong reference</td></tr>
        </table>

        <div style="font-weight:700;margin:12px 0 8px;color:#555">💰 Balance Check (BLCK)</div>
        <div class="api-url-box">?<span class="hl">service</span>=BLCK</div>

        <div style="font-weight:700;margin:12px 0 8px;color:#555">📦 Offer Packs (OFFERPACK)</div>
        <div class="api-url-box">?<span class="hl">service</span>=OFFERPACK&<span class="hl">operator</span>=7&<span class="hl">number</span>=01700000000</div>
    </div>
</div>
</div>

<!-- ============ LOGS TAB ============ -->
<div class="tab-content" id="tab-logs">
<div class="card">
    <div class="card-h"><i class="fas fa-history" style="color:#805ad5"></i> Recent API Logs (<?= count($logs) ?>)</div>
    <div class="card-b" style="padding:12px">
        <?php if(empty($logs)): ?>
        <div style="text-align:center;padding:30px;color:#aaa">No logs yet</div>
        <?php else: ?>
        <?php foreach($logs as $log): ?>
        <div class="log-item">
            <div class="log-time"><?= date('d M Y, h:i:s A',strtotime($log['created_at'])) ?></div>
            <div><strong>Request:</strong> <?= htmlspecialchars(substr($log['request_data'],0,150)) ?></div>
            <div style="margin-top:3px;color:#00aa66"><strong>Response:</strong> <?= htmlspecialchars(substr($log['response_data'],0,300)) ?></div>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>
</div>

</div>
</div>

<script>
function showTab(id, btn) {
    document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('show'));
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    document.getElementById('tab-'+id).classList.add('show');
    btn.classList.add('active');
}
</script>
</body>
</html>
