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

// Create tables
try {
    $db->exec("CREATE TABLE IF NOT EXISTS custom_apis (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        slug VARCHAR(50) NOT NULL UNIQUE,
        type ENUM('recharge','drive','both') DEFAULT 'both',
        http_method VARCHAR(10) DEFAULT 'POST',
        request_format VARCHAR(10) DEFAULT 'json',
        endpoint_recharge VARCHAR(300) DEFAULT NULL,
        endpoint_status VARCHAR(300) DEFAULT NULL,
        endpoint_balance VARCHAR(300) DEFAULT NULL,
        endpoint_drives VARCHAR(300) DEFAULT NULL,
        api_key VARCHAR(255) DEFAULT NULL,
        api_secret VARCHAR(255) DEFAULT NULL,
        auth_key_field VARCHAR(50) DEFAULT 'api_key',
        auth_secret_field VARCHAR(50) DEFAULT 'api_secret',
        field_map TEXT DEFAULT NULL,
        response_map TEXT DEFAULT NULL,
        operator_map TEXT DEFAULT NULL,
        is_active TINYINT(1) DEFAULT 1,
        notes TEXT DEFAULT NULL,
        last_balance VARCHAR(50) DEFAULT NULL,
        last_checked TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
} catch(Exception $e) {}

$msg = null;

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

    // Save ST credentials
    if ($action === 'save_st') {
        $key    = trim($_POST['st_key']    ?? '');
        $secret = trim($_POST['st_secret'] ?? '');
        $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['successtopup_key',$key,$key]);
        $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['successtopup_secret',$secret,$secret]);
        header('Location: api_manager.php?saved=st'); exit;
    }

    // Save ECARE credentials + URL
    if ($action === 'save_ecare') {
        $url  = trim($_POST['ecare_url']  ?? '');
        $user = trim($_POST['ecare_user'] ?? '');
        $pass = trim($_POST['ecare_pass'] ?? '');
        $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['ecare_url',$url,$url]);
        $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['ecare_username',$user,$user]);
        $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['ecare_password',$pass,$pass]);
        header('Location: api_manager.php?saved=ecare'); exit;
    }

    // Save/Edit custom API
    if (in_array($action, ['save_api','edit_api'])) {
        $id     = intval($_POST['api_id'] ?? 0);
        $name   = sanitize($_POST['api_name']   ?? '');
        $slug   = strtolower(preg_replace('/[^a-z0-9_]/', '_', $_POST['api_slug'] ?? $name));
        $type   = $_POST['api_type']   ?? 'both';
        $method = strtoupper($_POST['api_method'] ?? 'POST');
        $format = strtolower($_POST['api_format'] ?? 'json');
        $ep_r   = trim($_POST['ep_recharge'] ?? '');
        $ep_s   = trim($_POST['ep_status']   ?? '');
        $ep_b   = trim($_POST['ep_balance']  ?? '');
        $ep_d   = trim($_POST['ep_drives']   ?? '');
        $key    = trim($_POST['api_key']     ?? '');
        $secret = trim($_POST['api_secret']  ?? '');
        $akf    = trim($_POST['auth_key_field']    ?? 'api_key');
        $asf    = trim($_POST['auth_secret_field'] ?? 'api_secret');
        $notes  = sanitize($_POST['api_notes'] ?? '');
        $active = intval($_POST['api_active'] ?? 1);

        // Field map — phone, amount, operator, trxid → api field names
        $fm = [
            'phone'    => trim($_POST['fm_phone']    ?? 'number'),
            'amount'   => trim($_POST['fm_amount']   ?? 'amount'),
            'operator' => trim($_POST['fm_operator'] ?? 'operator'),
            'trxid'    => trim($_POST['fm_trxid']    ?? 'trxid'),
            'type'     => trim($_POST['fm_type']     ?? 'type'),
            'package'  => trim($_POST['fm_package']  ?? 'package_id'),
        ];

        // Response map — which keys mean success, trxid, balance
        $rm = [
            'success_key'   => trim($_POST['rm_success_key']   ?? 'result'),
            'success_value' => trim($_POST['rm_success_value'] ?? '1'),
            'trxid_key'     => trim($_POST['rm_trxid_key']     ?? 'trxid'),
            'balance_key'   => trim($_POST['rm_balance_key']   ?? 'balance'),
            'message_key'   => trim($_POST['rm_message_key']   ?? 'message'),
            'status_key'    => trim($_POST['rm_status_key']    ?? 'status'),
        ];

        // Operator map — our codes → API codes
        $om = [];
        foreach (['GP','BL','RB','AL','TT','SK'] as $oc) {
            $v = trim($_POST['om_'.$oc] ?? $oc);
            if ($v) $om[$oc] = $v;
        }

        $data = [$name,$slug,$type,$method,$format,$ep_r,$ep_s,$ep_b,$ep_d,$key,$secret,$akf,$asf,json_encode($fm),json_encode($rm),json_encode($om),$notes,$active];

        if ($id) {
            $db->prepare("UPDATE custom_apis SET name=?,slug=?,type=?,http_method=?,request_format=?,endpoint_recharge=?,endpoint_status=?,endpoint_balance=?,endpoint_drives=?,api_key=?,api_secret=?,auth_key_field=?,auth_secret_field=?,field_map=?,response_map=?,operator_map=?,notes=?,is_active=? WHERE id=?")
               ->execute(array_merge($data, [$id]));
            $msg=['ok'=>true,'text'=>'API updated!'];
        } else {
            try {
                $db->prepare("INSERT INTO custom_apis (name,slug,type,http_method,request_format,endpoint_recharge,endpoint_status,endpoint_balance,endpoint_drives,api_key,api_secret,auth_key_field,auth_secret_field,field_map,response_map,operator_map,notes,is_active) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
                   ->execute($data);
                $msg=['ok'=>true,'text'=>"✅ '$name' API added!"];
            } catch(Exception $e){ $msg=['ok'=>false,'text'=>'Slug already exists: '.$slug]; }
        }
        if(isset($_POST['stay'])) {} else { header('Location: api_manager.php?saved=api'); exit; }
    }

    if ($action === 'del_api') {
        $db->prepare("DELETE FROM custom_apis WHERE id=?")->execute([intval($_POST['api_id'])]);
        header('Location: api_manager.php?saved=del'); exit;
    }

    if ($action === 'toggle_api') {
        $db->prepare("UPDATE custom_apis SET is_active=1-is_active WHERE id=?")->execute([intval($_POST['api_id'])]);
        header('Location: api_manager.php'); exit;
    }

    // Operator save/add/delete
    if ($action === 'save_op') {
        $id=$intval($_POST['op_id']??0);
        $name=sanitize($_POST['op_name']??''); $code=strtoupper(sanitize($_POST['op_code']??'')); $status=$_POST['op_status']??'active';
        $db->prepare("UPDATE operators SET name=?,code=?,status=? WHERE id=?")->execute([$name,$code,$status,$id]);
        header('Location: api_manager.php?saved=op'); exit;
    }
    if ($action === 'add_op') {
        $name=sanitize($_POST['op_name']??''); $code=strtoupper(sanitize($_POST['op_code']??''));
        try { $db->prepare("INSERT INTO operators (name,code,status) VALUES (?,?,'active')")->execute([$name,$code]); } catch(Exception $e) {}
        header('Location: api_manager.php?saved=op'); exit;
    }
    if ($action === 'del_op') {
        $db->prepare("DELETE FROM operators WHERE id=?")->execute([intval($_POST['op_id'])]);
        header('Location: api_manager.php?saved=op'); exit;
    }

    // Balance check AJAX
    if ($action === 'check_bal') {
        header('Content-Type: application/json');
        $which = $_POST['which'] ?? '';
        if ($which === 'st') {
            $res = successTopupBalance();
            $bal = $res['balance'] ?? null;
            echo json_encode(['ok'=>!!$bal,'balance'=>$bal?'৳'.number_format(floatval($bal),2):'Error: '.($res['message']??'—'),'extra'=>'']);
        } elseif ($which === 'ecare') {
            $res = ecareBalance();
            $ok  = $res['status'] === 'OK';
            echo json_encode(['ok'=>$ok,'balance'=>$ok?'৳'.number_format(floatval(str_replace(',','',$res['main_balance'])),2):'Error: '.$res['message'],'extra'=>$ok?'Stock: ৳'.$res['stock_balance'].' | Comm: '.$res['commission_rate'].'%':'']);
        } elseif (is_numeric($which)) {
            // Custom API balance check
            require_once '../includes/custom_api.php';
            $res = customApiCall(intval($which), 'balance');
            $bal = $res['balance'] ? '৳'.number_format(floatval(str_replace(',','',$res['balance'])),2) : ($res['message']??'—');
            echo json_encode(['ok'=>$res['ok'],'balance'=>$bal,'extra'=>'']);
        }
        exit;
    }
}

$stKey    = getSetting('successtopup_key')    ?? '';
$stSecret = getSetting('successtopup_secret') ?? '';
$ecUrl    = getSetting('ecare_url')           ?? 'http://118.179.129.98/myportal/api/rechargeapi/recharge_api_thirdparty.php';
$ecUser   = getSetting('ecare_username')      ?? '';
$ecPass   = getSetting('ecare_password')      ?? '';
$operators  = $db->query("SELECT * FROM operators ORDER BY name")->fetchAll();
$customApis = $db->query("SELECT * FROM custom_apis ORDER BY created_at DESC")->fetchAll();
$saved = $_GET['saved'] ?? '';

// Parse field/response maps — keep both raw and parsed
foreach ($customApis as &$ca) {
    $ca['_fm'] = json_decode($ca['field_map']    ?? '{}', true) ?: (object)[];
    $ca['_rm'] = json_decode($ca['response_map'] ?? '{}', true) ?: (object)[];
    $ca['_om'] = json_decode($ca['operator_map'] ?? '{}', true) ?: (object)[];
    // Ensure objects not arrays for JS
    if(is_array($ca['_fm']) && empty($ca['_fm'])) $ca['_fm'] = new stdClass();
    if(is_array($ca['_rm']) && empty($ca['_rm'])) $ca['_rm'] = new stdClass();
    if(is_array($ca['_om']) && empty($ca['_om'])) $ca['_om'] = new stdClass();
}
unset($ca);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>API Manager</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="../assets/css/admin.css">
<style>
.card{background:white;border-radius:14px;box-shadow:0 2px 8px rgba(0,0,0,0.06);margin-bottom:20px;overflow:hidden}
.card-h{padding:15px 20px;font-size:14px;font-weight:800;border-bottom:1px solid #f5f5f5;display:flex;align-items:center;justify-content:space-between;gap:8px}
.card-b{padding:18px 20px}
.fg{margin-bottom:12px}
.fg label{display:block;font-size:11px;font-weight:700;color:#888;text-transform:uppercase;margin-bottom:5px}
.fg input,.fg select,.fg textarea{width:100%;padding:10px 12px;border:2px solid #e8ecf4;border-radius:10px;font-size:13px;outline:none;font-family:inherit;transition:border-color 0.2s}
.fg input:focus,.fg select:focus,.fg textarea:focus{border-color:var(--primary)}
.fg small{font-size:11px;color:#aaa;margin-top:4px;display:block}
.frow2{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.frow3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px}
.btn{padding:9px 16px;border:none;border-radius:9px;font-size:13px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:6px;text-decoration:none}
.btn-primary{background:var(--primary);color:white}
.btn-sm{padding:6px 10px;font-size:12px;border-radius:8px;border:none;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:4px}
.alert{padding:11px 16px;border-radius:10px;font-size:13px;font-weight:600;margin-bottom:14px}
.alert-ok{background:#f0fff4;color:#276749;border:1px solid #c6f6d5}
.alert-err{background:#fff5f5;color:#c53030;border:1px solid #fed7d7}
.key-wrap{display:flex;gap:6px}
.key-wrap input{flex:1}
.key-wrap button{padding:9px 12px;background:#f5f5f5;border:2px solid #e8ecf4;border-radius:10px;cursor:pointer;color:#666;flex-shrink:0}
.bal-box{background:#f8fafc;border-radius:10px;padding:12px 16px;display:flex;align-items:center;justify-content:space-between;margin-bottom:14px}
.bal-amt{font-size:17px;font-weight:800;color:var(--primary)}
.api-icon{width:42px;height:42px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:18px;flex-shrink:0}
.sep{font-size:11px;font-weight:800;color:#888;text-transform:uppercase;border-bottom:2px solid #f0f0f0;padding-bottom:6px;margin:16px 0 12px}
.op-row{display:flex;align-items:center;gap:10px;padding:10px 20px;border-bottom:1px solid #f5f5f5}
.op-row:last-child{border:none}
.op-code{background:var(--primary);color:white;font-size:11px;font-weight:800;padding:3px 9px;border-radius:8px}
.api-row{border-bottom:1px solid #f5f5f5}
.api-row:last-child{border:none}
.api-row-head{display:flex;align-items:center;gap:12px;padding:14px 18px;cursor:pointer;transition:background 0.15s}
.api-row-head:hover{background:#fafbff}
.api-row-info{min-width:0}
.api-row-name{font-size:14px;font-weight:800;color:#1a1a2e}
.api-row-url{font-size:11px;color:#aaa;margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:300px}
.api-row-body{display:none;padding:16px 18px;background:#fafbff;border-top:1px solid #f0f0f0}
.api-row-body.open{display:block}
.api-divider{height:1px;background:#f5f5f5}
.abadge{font-size:10px;font-weight:700;padding:3px 8px;border-radius:8px;white-space:nowrap}
.abadge-both{background:#ebf8ff;color:#2b6cb0}
.abadge-recharge{background:#f0fff4;color:#276749}
.abadge-drive{background:#fffbeb;color:#d69e2e}
.astatus{font-size:11px;font-weight:700;padding:3px 8px;border-radius:8px;white-space:nowrap}
.astatus-on{background:#f0fff4;color:#276749}
.astatus-off{background:#fff5f5;color:#e53e3e}
.afield-pills{display:flex;gap:4px;flex-wrap:wrap}
.apill{font-size:10px;background:#f0f4ff;color:var(--primary);padding:2px 8px;border-radius:8px;font-weight:600;white-space:nowrap}
.fields-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.field-block{}
.field-label{font-size:11px;font-weight:700;color:#888;text-transform:uppercase;margin-bottom:5px}
.field-block input{width:100%;padding:9px 12px;border:2px solid #e8ecf4;border-radius:9px;font-size:12px;outline:none}
.field-block input:focus{border-color:var(--primary)}
.field-block small{font-size:11px;color:#aaa;margin-top:3px;display:block}
.map-pill{font-size:12px;background:white;border:1px solid #e8ecf4;padding:4px 10px;border-radius:8px;color:#555}
.modal-bg{visibility:hidden;opacity:0;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:9999;display:flex;align-items:center;justify-content:center;padding:16px;transition:opacity 0.2s;pointer-events:none}
.modal-box{background:white;border-radius:16px;width:100%;max-width:560px;padding:22px;max-height:92vh;overflow-y:auto;transform:scale(0.95);transition:transform 0.2s}
.modal-bg.show{visibility:visible;opacity:1;pointer-events:auto}
.modal-bg.show .modal-box{transform:scale(1)}
.modal-title{font-size:15px;font-weight:800;margin-bottom:16px;display:flex;align-items:center;justify-content:space-between}
.close-btn{background:#f5f5f5;border:none;width:28px;height:28px;border-radius:50%;cursor:pointer}
</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">🔌 API Manager</span>
    </div>
    <div class="topbar-right">
        <button class="btn btn-primary" onclick="openAddApi()"><i class="fas fa-plus"></i> Add New API</button>
    </div>
</div>
<div class="content">

<?php if($msg): ?><div class="alert <?= $msg['ok']?'alert-ok':'alert-err' ?>"><?= $msg['ok']?'✅':'❌' ?> <?= htmlspecialchars($msg['text']) ?></div><?php endif; ?>
<?php if($saved && !$msg): ?><div class="alert alert-ok">✅ Saved successfully!</div><?php endif; ?>

<!-- All APIs Dashboard -->
<div class="card">
    <div class="card-h">
        <span>🔌 Available APIs (<?= 2 + count($customApis) ?>)</span>
        <button class="btn btn-primary btn-sm" onclick="openAddApi()"><i class="fas fa-plus"></i> Add New API</button>
    </div>

    <!-- SuccessTopUp -->
    <div class="api-row" id="row_st">
        <div class="api-row-head" onclick="toggleRow('st')">
            <div class="api-icon" style="background:#f0fff4;color:#276749">🔄</div>
            <div class="api-row-info">
                <div class="api-row-name">SuccessTopUp</div>
                <div class="api-row-url">api.successtopup.com</div>
            </div>
            <div style="display:flex;align-items:center;gap:8px;margin-left:auto">
                <span class="abadge abadge-both">Recharge + Drive</span>
                <span class="astatus astatus-on">✅ Active</span>
                <div class="afield-pills">
                    <span class="apill"><?= $stKey ? '🔑 Key: '.substr($stKey,0,8).'...' : '❌ No Key' ?></span>
                    <span class="apill"><?= $stSecret ? '🔐 Secret: ✓' : '❌ No Secret' ?></span>
                </div>
                <button class="btn-sm" style="background:#f0fff4;color:#276749" onclick="event.stopPropagation();checkBal('st',this)"><i class="fas fa-wallet"></i> Balance</button>
                <button class="btn-sm" style="background:#ebf8ff;color:var(--primary)" onclick="event.stopPropagation();toggleRow('st')"><i class="fas fa-edit"></i> Edit</button>
                <i class="fas fa-chevron-down" id="chev_st" style="color:#ddd;transition:0.2s"></i>
            </div>
        </div>
        <div class="api-row-body" id="body_st">
            <div class="bal-box" id="stBalBox" style="display:none">
                <div><div style="font-size:11px;color:#aaa">Balance</div><div class="bal-amt" id="stBal">—</div></div>
                <div id="stExtra" style="font-size:11px;color:#aaa"></div>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="save_st">
                <div class="fields-grid">
                    <div class="field-block"><div class="field-label">🔑 API Key</div>
                        <div class="key-wrap"><input type="text" name="st_key" id="stKey" value="<?= htmlspecialchars($stKey) ?>" placeholder="API Key"><button type="button" onclick="toggleVis('stKey')"><i class="fas fa-eye"></i></button></div>
                    </div>
                    <div class="field-block"><div class="field-label">🔐 API Secret</div>
                        <div class="key-wrap"><input type="password" name="st_secret" id="stSecret" value="<?= htmlspecialchars($stSecret) ?>" placeholder="API Secret"><button type="button" onclick="toggleVis('stSecret')"><i class="fas fa-eye"></i></button></div>
                    </div>
                    <div class="field-block"><div class="field-label">🔗 Recharge URL</div><input type="text" value="https://api.successtopup.com/api/recharge" readonly style="background:#f8fafc;color:#888"></div>
                    <div class="field-block"><div class="field-label">📊 Status URL</div><input type="text" value="https://api.successtopup.com/api/status" readonly style="background:#f8fafc;color:#888"></div>
                    <div class="field-block"><div class="field-label">💰 Balance URL</div><input type="text" value="https://api.successtopup.com/api/balance" readonly style="background:#f8fafc;color:#888"></div>
                    <div class="field-block"><div class="field-label">📦 Drives URL</div><input type="text" value="https://api.successtopup.com/api/drives" readonly style="background:#f8fafc;color:#888"></div>
                </div>
                <div style="margin-top:12px">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
                </div>
            </form>
        </div>
    </div>

    <div class="api-divider"></div>

    <!-- ECARE -->
    <div class="api-row" id="row_ecare">
        <div class="api-row-head" onclick="toggleRow('ecare')">
            <div class="api-icon" style="background:#fffbeb;color:#d69e2e">⚡</div>
            <div class="api-row-info">
                <div class="api-row-name">ECARE Technology</div>
                <div class="api-row-url"><?= htmlspecialchars(substr($ecUrl,0,45)) ?>...</div>
            </div>
            <div style="display:flex;align-items:center;gap:8px;margin-left:auto">
                <span class="abadge abadge-recharge">Recharge</span>
                <span class="astatus astatus-on">✅ Active</span>
                <div class="afield-pills">
                    <span class="apill"><?= $ecUser ? '👤 '.$ecUser : '❌ No User' ?></span>
                    <span class="apill"><?= $ecPass ? '🔐 Pass: ✓' : '❌ No Pass' ?></span>
                </div>
                <button class="btn-sm" style="background:#fffbeb;color:#d69e2e" onclick="event.stopPropagation();checkBal('ecare',this)"><i class="fas fa-wallet"></i> Balance</button>
                <button class="btn-sm" style="background:#ebf8ff;color:var(--primary)" onclick="event.stopPropagation();toggleRow('ecare')"><i class="fas fa-edit"></i> Edit</button>
                <i class="fas fa-chevron-down" id="chev_ecare" style="color:#ddd;transition:0.2s"></i>
            </div>
        </div>
        <div class="api-row-body" id="body_ecare">
            <div class="bal-box" id="ecBalBox" style="display:none">
                <div><div style="font-size:11px;color:#aaa">Balance</div><div class="bal-amt" id="ecBal">—</div></div>
                <div id="ecExtra" style="font-size:11px;color:#aaa"></div>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="save_ecare">
                <div class="fields-grid">
                    <div class="field-block" style="grid-column:1/-1"><div class="field-label">🔗 API URL</div>
                        <input type="url" name="ecare_url" value="<?= htmlspecialchars($ecUrl) ?>" placeholder="http://...">
                        <small>URL পরিবর্তন হলে এখানে update করুন</small>
                    </div>
                    <div class="field-block"><div class="field-label">👤 Username (access_id)</div>
                        <div class="key-wrap"><input type="text" name="ecare_user" id="ecUser" value="<?= htmlspecialchars($ecUser) ?>"><button type="button" onclick="toggleVis('ecUser')"><i class="fas fa-eye"></i></button></div>
                    </div>
                    <div class="field-block"><div class="field-label">🔐 Password (access_pass)</div>
                        <div class="key-wrap"><input type="password" name="ecare_pass" id="ecPass" value="<?= htmlspecialchars($ecPass) ?>"><button type="button" onclick="toggleVis('ecPass')"><i class="fas fa-eye"></i></button></div>
                    </div>
                    <div class="field-block"><div class="field-label">📊 Status URL</div><input type="text" value="Same URL + service=MRCSTATUS" readonly style="background:#f8fafc;color:#888"></div>
                    <div class="field-block"><div class="field-label">💰 Balance URL</div><input type="text" value="Same URL + service=BLCK" readonly style="background:#f8fafc;color:#888"></div>
                </div>
                <div style="margin-top:12px">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Custom APIs -->
    <?php foreach($customApis as $ca):
        $fm = $ca['_fm']; $rm = $ca['_rm']; $om = $ca['_om'];
        $hasKey = !empty($ca['api_key']); $hasSecret = !empty($ca['api_secret']);
    ?>
    <div class="api-divider"></div>
    <div class="api-row" id="row_<?= $ca['id'] ?>">
        <div class="api-row-head" onclick="toggleRow(<?= $ca['id'] ?>)">
            <div class="api-icon" style="background:#f0f4ff;color:var(--primary)">🔌</div>
            <div class="api-row-info">
                <div class="api-row-name"><?= htmlspecialchars($ca['name']) ?></div>
                <div class="api-row-url"><?= htmlspecialchars(substr($ca['endpoint_recharge']??'No endpoint',0,50)) ?></div>
            </div>
            <div style="display:flex;align-items:center;gap:8px;margin-left:auto;flex-wrap:wrap">
                <span class="abadge abadge-<?= $ca['type'] ?>"><?= $ca['type'] ?></span>
                <span class="astatus <?= $ca['is_active']?'astatus-on':'astatus-off' ?>"><?= $ca['is_active']?'✅ Active':'❌ Off' ?></span>
                <div class="afield-pills">
                    <span class="apill"><?= $hasKey?'🔑 Key: ✓':'❌ No Key' ?></span>
                    <span class="apill"><?= $hasSecret?'🔐 Secret: ✓':'❌ No Secret' ?></span>
                    <span class="apill">📤 <?= $ca['http_method'] ?>/<?= strtoupper($ca['request_format']) ?></span>
                </div>
                <button class="btn-sm" style="background:#f0fff4;color:#276749" onclick="event.stopPropagation();checkBal('<?= $ca['id'] ?>',this)"><i class="fas fa-wallet"></i> Balance</button>
                <button class="btn-sm" style="background:#ebf8ff;color:var(--primary)" onclick="event.stopPropagation();openEditApi(<?= htmlspecialchars(json_encode($ca),ENT_QUOTES) ?>)"><i class="fas fa-edit"></i> Edit</button>
                <form method="POST" onsubmit="return confirm('Delete?')" style="display:inline">
                    <input type="hidden" name="action" value="del_api">
                    <input type="hidden" name="api_id" value="<?= $ca['id'] ?>">
                    <button type="submit" class="btn-sm" style="background:#fff5f5;color:#e53e3e" onclick="event.stopPropagation()"><i class="fas fa-trash"></i></button>
                </form>
                <i class="fas fa-chevron-down" id="chev_<?= $ca['id'] ?>" style="color:#ddd;transition:0.2s"></i>
            </div>
        </div>
        <div class="api-row-body" id="body_<?= $ca['id'] ?>">
            <div id="caBal_<?= $ca['id'] ?>" style="display:none;margin-bottom:12px;padding:12px 16px;background:#f0f4ff;border-radius:10px;font-size:14px;font-weight:800;color:var(--primary)"></div>
            <!-- Fields overview -->
            <div class="fields-grid">
                <div class="field-block"><div class="field-label">🔗 Recharge URL</div><input type="text" value="<?= htmlspecialchars($ca['endpoint_recharge']??'—') ?>" readonly style="background:#f8fafc;font-size:12px"></div>
                <div class="field-block"><div class="field-label">📊 Status URL</div><input type="text" value="<?= htmlspecialchars($ca['endpoint_status']??'—') ?>" readonly style="background:#f8fafc;font-size:12px"></div>
                <div class="field-block"><div class="field-label">💰 Balance URL</div><input type="text" value="<?= htmlspecialchars($ca['endpoint_balance']??'—') ?>" readonly style="background:#f8fafc;font-size:12px"></div>
                <div class="field-block"><div class="field-label">📦 Drive URL</div><input type="text" value="<?= htmlspecialchars($ca['endpoint_drives']??'—') ?>" readonly style="background:#f8fafc;font-size:12px"></div>
                <div class="field-block"><div class="field-label">🔑 Auth Key Field</div><input type="text" value="<?= htmlspecialchars($ca['auth_key_field']??'api_key') ?>" readonly style="background:#f8fafc"></div>
                <div class="field-block"><div class="field-label">🔐 Auth Secret Field</div><input type="text" value="<?= htmlspecialchars($ca['auth_secret_field']??'api_secret') ?>" readonly style="background:#f8fafc"></div>
            </div>
            <!-- Field Mapping -->
            <?php if(!empty($fm)): ?>
            <div style="margin-top:12px">
                <div style="font-size:11px;font-weight:800;color:#888;text-transform:uppercase;margin-bottom:8px">📤 Request Field Mapping</div>
                <div style="display:flex;gap:6px;flex-wrap:wrap">
                    <?php foreach($fm as $k=>$v): ?>
                    <div class="map-pill"><span style="color:#aaa"><?= $k ?></span> → <span style="color:var(--primary);font-weight:700"><?= $v ?></span></div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
            <!-- Response Mapping -->
            <?php if(!empty($rm)): ?>
            <div style="margin-top:10px">
                <div style="font-size:11px;font-weight:800;color:#888;text-transform:uppercase;margin-bottom:8px">📥 Response Mapping</div>
                <div style="display:flex;gap:6px;flex-wrap:wrap">
                    <div class="map-pill">Success: <b><?= htmlspecialchars($rm['success_key']??'result') ?> = <?= htmlspecialchars($rm['success_value']??'1') ?></b></div>
                    <div class="map-pill">TrxID: <b><?= htmlspecialchars($rm['trxid_key']??'trxid') ?></b></div>
                    <div class="map-pill">Status: <b><?= htmlspecialchars($rm['status_key']??'status') ?></b></div>
                    <div class="map-pill">Balance: <b><?= htmlspecialchars($rm['balance_key']??'balance') ?></b></div>
                </div>
            </div>
            <?php endif; ?>
            <!-- Operator Mapping -->
            <?php if(!empty($om)): ?>
            <div style="margin-top:10px">
                <div style="font-size:11px;font-weight:800;color:#888;text-transform:uppercase;margin-bottom:8px">📡 Operator Mapping</div>
                <div style="display:flex;gap:6px;flex-wrap:wrap">
                    <?php foreach($om as $k=>$v): ?>
                    <div class="map-pill"><?= $k ?> → <b><?= $v ?></b></div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
            <div style="margin-top:12px;padding-top:12px;border-top:1px solid #f0f0f0">
                <button class="btn" style="background:#ebf8ff;color:var(--primary)" onclick="openEditApi(<?= htmlspecialchars(json_encode($ca),ENT_QUOTES) ?>)"><i class="fas fa-edit"></i> Edit All Fields</button>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- Operators -->
<div class="card">
    <div class="card-h"><span>📡 Operators (<?= count($operators) ?>)</span>
        <button class="btn btn-primary btn-sm" onclick="openAddOp()"><i class="fas fa-plus"></i> Add</button>
    </div>
    <div style="padding:0">
    <?php foreach($operators as $op): ?>
    <div class="op-row">
        <span class="op-code"><?= htmlspecialchars($op['code']) ?></span>
        <div style="flex:1"><div style="font-size:13px;font-weight:700"><?= htmlspecialchars($op['name']) ?></div>
            <div style="font-size:11px;color:#aaa"><?= $op['status']==='active'?'✅ Active':'❌ Inactive' ?></div>
        </div>
        <button class="btn-sm" style="background:#ebf8ff;color:var(--primary)" onclick='openEditOp(<?= htmlspecialchars(json_encode($op),ENT_QUOTES) ?>)'><i class="fas fa-edit"></i></button>
        <form method="POST" onsubmit="return confirm('Delete?')" style="display:inline">
            <input type="hidden" name="action" value="del_op">
            <input type="hidden" name="op_id" value="<?= $op['id'] ?>">
            <button type="submit" class="btn-sm" style="background:#fff5f5;color:#e53e3e"><i class="fas fa-trash"></i></button>
        </form>
    </div>
    <?php endforeach; ?>
    </div>
</div>

</div></div>

<!-- Add/Edit Custom API Modal -->
<div class="modal-bg" id="apiModal">
<div class="modal-box">
    <div class="modal-title"><span id="apiModalTitle">Add New API</span><button class="close-btn" onclick="closeM('apiModal')">✕</button></div>
    <form method="POST">
        <input type="hidden" name="action" id="apiAction" value="save_api">
        <input type="hidden" name="api_id" id="apiId">

        <div class="sep">📋 Basic Info</div>
        <div class="frow2">
            <div class="fg"><label>API Name *</label><input name="api_name" id="apiName" placeholder="My Recharge API" required oninput="autoSlug(this)"></div>
            <div class="fg"><label>Slug (unique)</label><input name="api_slug" id="apiSlug" placeholder="my_recharge_api"></div>
        </div>
        <div class="frow3">
            <div class="fg"><label>Type</label>
                <select name="api_type" id="apiType">
                    <option value="both">📱+⚡ Both</option>
                    <option value="recharge">📱 Recharge</option>
                    <option value="drive">⚡ Drive</option>
                </select>
            </div>
            <div class="fg"><label>HTTP Method</label>
                <select name="api_method" id="apiMethod">
                    <option value="POST">POST</option>
                    <option value="GET">GET</option>
                </select>
            </div>
            <div class="fg"><label>Format</label>
                <select name="api_format" id="apiFormat">
                    <option value="json">JSON</option>
                    <option value="form">Form Data</option>
                </select>
            </div>
        </div>
        <div class="fg"><label>Status</label>
            <select name="api_active" id="apiActive"><option value="1">✅ Active</option><option value="0">❌ Inactive</option></select>
        </div>

        <div class="sep">🔗 Endpoints</div>
        <div class="fg"><label>Recharge URL</label><input type="url" name="ep_recharge" id="epRecharge" placeholder="https://api.example.com/recharge"></div>
        <div class="fg"><label>Status Check URL</label><input type="url" name="ep_status" id="epStatus" placeholder="https://api.example.com/status"></div>
        <div class="frow2">
            <div class="fg"><label>Balance URL</label><input type="url" name="ep_balance" id="epBalance" placeholder="https://api.example.com/balance"></div>
            <div class="fg"><label>Drive/Package URL</label><input type="url" name="ep_drives" id="epDrives" placeholder="https://api.example.com/drives"></div>
        </div>

        <div class="sep">🔑 Credentials</div>
        <div class="frow2">
            <div class="fg"><label>API Key / Username</label>
                <div class="key-wrap"><input type="text" name="api_key" id="apiKey" placeholder="Your API Key"><button type="button" onclick="toggleVis('apiKey')"><i class="fas fa-eye"></i></button></div>
            </div>
            <div class="fg"><label>API Secret / Password</label>
                <div class="key-wrap"><input type="password" name="api_secret" id="apiSecret" placeholder="Your Secret"><button type="button" onclick="toggleVis('apiSecret')"><i class="fas fa-eye"></i></button></div>
            </div>
        </div>
        <div class="frow2">
            <div class="fg"><label>Auth Key Field Name</label><input name="auth_key_field" id="authKeyF" value="api_key" placeholder="api_key"><small>Request এ key এর field name</small></div>
            <div class="fg"><label>Auth Secret Field Name</label><input name="auth_secret_field" id="authSecF" value="api_secret" placeholder="api_secret"><small>Request এ secret এর field name</small></div>
        </div>

        <div class="sep">📤 Request Field Mapping</div>
        <div style="background:#f8fafc;border-radius:10px;padding:14px;font-size:12px;color:#666;margin-bottom:12px">
            আমাদের field → API এর field name। Example: আমাদের <b>phone</b> কিন্তু API তে <b>mobile_number</b> হলে সেটা লিখুন।
        </div>
        <div class="frow3">
            <div class="fg"><label>Phone field</label><input name="fm_phone" id="fmPhone" value="number" placeholder="number"></div>
            <div class="fg"><label>Amount field</label><input name="fm_amount" id="fmAmount" value="amount" placeholder="amount"></div>
            <div class="fg"><label>Operator field</label><input name="fm_operator" id="fmOperator" value="operator" placeholder="operator"></div>
            <div class="fg"><label>TrxID field</label><input name="fm_trxid" id="fmTrxid" value="trxid" placeholder="trxid"></div>
            <div class="fg"><label>Type field</label><input name="fm_type" id="fmType" value="type" placeholder="type"></div>
            <div class="fg"><label>Package ID field</label><input name="fm_package" id="fmPackage" value="package_id" placeholder="package_id"></div>
        </div>

        <div class="sep">📥 Response Mapping</div>
        <div style="background:#f8fafc;border-radius:10px;padding:14px;font-size:12px;color:#666;margin-bottom:12px">
            API response এর কোন field দেখে success/fail বুঝব। Nested key: <b>data.status</b>
        </div>
        <div class="frow2">
            <div class="fg"><label>Success Key</label><input name="rm_success_key" id="rmSuccessKey" value="result" placeholder="result"><small>কোন field check করব</small></div>
            <div class="fg"><label>Success Value</label><input name="rm_success_value" id="rmSuccessVal" value="1" placeholder="1"><small>কোন value = success</small></div>
            <div class="fg"><label>TrxID Key</label><input name="rm_trxid_key" id="rmTrxid" value="trxid" placeholder="trxid"></div>
            <div class="fg"><label>Balance Key</label><input name="rm_balance_key" id="rmBalance" value="balance" placeholder="balance"></div>
            <div class="fg"><label>Message Key</label><input name="rm_message_key" id="rmMessage" value="message" placeholder="message"></div>
            <div class="fg"><label>Status Key</label><input name="rm_status_key" id="rmStatus" value="status" placeholder="status"></div>
        </div>

        <div class="sep">📡 Operator Code Mapping</div>
        <div style="background:#f8fafc;border-radius:10px;padding:14px;font-size:12px;color:#666;margin-bottom:12px">
            আমাদের operator code → API তে কোন code পাঠাব। ST তে GP→GP, Airtel→AT ইত্যাদি।
        </div>
        <div class="frow3">
            <?php foreach(['GP'=>'Grameenphone','BL'=>'Banglalink','RB'=>'Robi','AL'=>'Airtel','TT'=>'Teletalk','SK'=>'Skitto'] as $c=>$n): ?>
            <div class="fg"><label><?= $n ?> (<?= $c ?>)</label><input name="om_<?= $c ?>" id="om<?= $c ?>" value="<?= $c ?>" placeholder="<?= $c ?>"></div>
            <?php endforeach; ?>
        </div>

        <div class="fg"><label>Notes</label><input name="api_notes" id="apiNotes" placeholder="Optional notes..."></div>

        <div style="display:flex;gap:8px;justify-content:flex-end;padding-top:12px;border-top:1px solid #f0f0f0">
            <button type="button" onclick="closeM('apiModal')" class="btn" style="background:#f5f5f5;color:#555">Cancel</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save API</button>
        </div>
    </form>
</div>
</div>

<!-- Operator Modal -->
<div class="modal-bg" id="opModal">
<div class="modal-box" style="max-width:380px">
    <div class="modal-title"><span id="opModalTitle">Edit Operator</span><button class="close-btn" onclick="closeM('opModal')">✕</button></div>
    <form method="POST">
        <input type="hidden" name="action" id="opAction" value="save_op">
        <input type="hidden" name="op_id" id="opId">
        <div class="fg"><label>Operator Name</label><input name="op_name" id="opName" required placeholder="Grameenphone"></div>
        <div class="fg"><label>Short Code</label><input name="op_code" id="opCode" required placeholder="GP" style="text-transform:uppercase">
            <small>API তে যে code use হয় (GP, BL, RB, AL, TT)</small></div>
        <div class="fg"><label>Status</label>
            <select name="op_status" id="opStatus"><option value="active">✅ Active</option><option value="inactive">❌ Inactive</option></select>
        </div>
        <div style="display:flex;gap:8px;justify-content:flex-end;padding-top:12px;border-top:1px solid #f0f0f0">
            <button type="button" onclick="closeM('opModal')" class="btn" style="background:#f5f5f5;color:#555">Cancel</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
        </div>
    </form>
</div>
</div>

<script>
function toggleVis(id){const el=document.getElementById(id);el.type=el.type==='password'?'text':'password';}
function toggleRow(id){
    const body=document.getElementById('body_'+id);
    const chev=document.getElementById('chev_'+id);
    const isOpen=body.classList.contains('open');
    // Close all
    document.querySelectorAll('.api-row-body').forEach(b=>b.classList.remove('open'));
    document.querySelectorAll('[id^="chev_"]').forEach(c=>c.style.transform='');
    if(!isOpen){body.classList.add('open');chev.style.transform='rotate(180deg)';}
}
function closeM(id){document.getElementById(id).classList.remove('show');}
document.querySelectorAll('.modal-bg').forEach(m=>m.addEventListener('click',e=>{if(e.target===m)m.classList.remove('show');}));

function openAddApi(){
    document.getElementById('apiModalTitle').textContent='Add New API';
    document.getElementById('apiAction').value='save_api';
    document.getElementById('apiId').value='';
    ['apiName','apiSlug','epRecharge','epStatus','epBalance','epDrives','apiKey','apiNotes'].forEach(id=>document.getElementById(id).value='');
    document.getElementById('apiSecret').value='';
    document.getElementById('apiType').value='both';
    document.getElementById('apiMethod').value='POST';
    document.getElementById('apiFormat').value='json';
    document.getElementById('apiActive').value='1';
    document.getElementById('authKeyF').value='api_key';
    document.getElementById('authSecF').value='api_secret';
    document.getElementById('fmPhone').value='number';
    document.getElementById('fmAmount').value='amount';
    document.getElementById('fmOperator').value='operator';
    document.getElementById('fmTrxid').value='trxid';
    document.getElementById('fmType').value='type';
    document.getElementById('fmPackage').value='package_id';
    document.getElementById('rmSuccessKey').value='result';
    document.getElementById('rmSuccessVal').value='1';
    document.getElementById('rmTrxid').value='trxid';
    document.getElementById('rmBalance').value='balance';
    document.getElementById('rmMessage').value='message';
    document.getElementById('rmStatus').value='status';
    ['GP','BL','RB','AL','TT','SK'].forEach(c=>{const el=document.getElementById('om'+c);if(el)el.value=c==='AL'?'AT':c;});
    document.getElementById('apiModal').classList.add('show');
}

function openEditApi(a){
    document.getElementById('apiModalTitle').textContent='Edit: '+a.name;
    document.getElementById('apiAction').value='edit_api';
    document.getElementById('apiId').value=a.id||'';
    document.getElementById('apiName').value=a.name||'';
    document.getElementById('apiSlug').value=a.slug||'';
    document.getElementById('apiType').value=a.type||'both';
    document.getElementById('apiMethod').value=a.http_method||'POST';
    document.getElementById('apiFormat').value=a.request_format||'json';
    document.getElementById('epRecharge').value=a.endpoint_recharge||'';
    document.getElementById('epStatus').value=a.endpoint_status||'';
    document.getElementById('epBalance').value=a.endpoint_balance||'';
    document.getElementById('epDrives').value=a.endpoint_drives||'';
    document.getElementById('apiKey').value=a.api_key||'';
    document.getElementById('apiSecret').value=a.api_secret||'';
    document.getElementById('authKeyF').value=a.auth_key_field||'api_key';
    document.getElementById('authSecF').value=a.auth_secret_field||'api_secret';
    document.getElementById('apiActive').value=a.is_active!=null?a.is_active:1;
    document.getElementById('apiNotes').value=a.notes||'';
    // Field mapping — _fm is an object
    const fm = (a._fm && typeof a._fm==='object') ? a._fm : {};
    document.getElementById('fmPhone').value   = fm.phone    || 'number';
    document.getElementById('fmAmount').value  = fm.amount   || 'amount';
    document.getElementById('fmOperator').value= fm.operator || 'operator';
    document.getElementById('fmTrxid').value   = fm.trxid    || 'trxid';
    document.getElementById('fmType').value    = fm.type     || 'type';
    document.getElementById('fmPackage').value = fm.package  || 'package_id';
    // Response mapping
    const rm = (a._rm && typeof a._rm==='object') ? a._rm : {};
    document.getElementById('rmSuccessKey').value = rm.success_key   || 'result';
    document.getElementById('rmSuccessVal').value = rm.success_value || '1';
    document.getElementById('rmTrxid').value      = rm.trxid_key     || 'trxid';
    document.getElementById('rmBalance').value    = rm.balance_key   || 'balance';
    document.getElementById('rmMessage').value    = rm.message_key   || 'message';
    document.getElementById('rmStatus').value     = rm.status_key    || 'status';
    // Operator mapping
    const om = (a._om && typeof a._om==='object') ? a._om : {};
    ['GP','BL','RB','AL','TT','SK'].forEach(c=>{
        const el=document.getElementById('om'+c);
        if(el) el.value = om[c] || (c==='AL'?'AT':c);
    });
    document.getElementById('apiModal').classList.add('show');
}

function openEditOp(op){
    document.getElementById('opModalTitle').textContent='Edit Operator';
    document.getElementById('opAction').value='save_op';
    document.getElementById('opId').value=op.id;
    document.getElementById('opName').value=op.name;
    document.getElementById('opCode').value=op.code;
    document.getElementById('opStatus').value=op.status;
    document.getElementById('opModal').classList.add('show');
}
function openAddOp(){
    document.getElementById('opModalTitle').textContent='Add Operator';
    document.getElementById('opAction').value='add_op';
    document.getElementById('opId').value='';
    document.getElementById('opName').value='';
    document.getElementById('opCode').value='';
    document.getElementById('opStatus').value='active';
    document.getElementById('opModal').classList.add('show');
}

function checkBal(which,btn){
    const orig=btn.innerHTML; btn.innerHTML='<i class="fas fa-spinner fa-spin"></i>'; btn.disabled=true;
    fetch('api_manager.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'action=check_bal&which='+which})
    .then(r=>r.json()).then(d=>{
        if(which==='st'||which==='ecare'){
            const pfx=which==='st'?'st':'ec';
            const box=document.getElementById(pfx+'BalBox');
            box.style.display='flex';
            document.getElementById(pfx+'Bal').textContent=d.balance;
            document.getElementById(pfx+'Bal').style.color=d.ok?'var(--primary)':'#e53e3e';
            if(d.extra)document.getElementById(pfx+'Extra').textContent=d.extra;
        } else {
            const el=document.getElementById('caBal_'+which);
            el.style.display='block';
            el.textContent='💰 Balance: '+d.balance;
            el.style.color=d.ok?'var(--primary)':'#e53e3e';
        }
        btn.innerHTML=orig; btn.disabled=false;
    }).catch(()=>{btn.innerHTML=orig;btn.disabled=false;});
}
</script>
</body>
</html>
