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

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

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

    if (in_array($action, ['add','edit'])) {
        $id          = intval($_POST['id'] ?? 0);
        $name        = sanitize($_POST['name'] ?? '');
        $code        = strtoupper(sanitize($_POST['code'] ?? ''));
        $prefix      = sanitize($_POST['prefix'] ?? '');
        $commission  = floatval($_POST['commission'] ?? 0);
        $charge      = floatval($_POST['charge'] ?? 0);
        $charge_type = sanitize($_POST['charge_type'] ?? 'flat');
        $status      = sanitize($_POST['status'] ?? 'active');
        $st_code     = strtoupper(sanitize($_POST['st_code'] ?? $code));
        $ecare_code  = sanitize($_POST['ecare_code'] ?? '');
        $op_api_mode = sanitize($_POST['op_api'] ?? 'manual');
        $prefixes    = array_values(array_filter(array_map('trim', explode(',', $prefix))));

        // Logo upload
        $logoPath = $_POST['existing_logo'] ?? null;
        if (!empty($_FILES['logo']['name'])) {
            $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg','jpeg','png','svg','webp'])) {
                $dir = '../assets/img/operators/';
                @mkdir($dir, 0755, true);
                $fn = strtolower($code).'_'.time().'.'.$ext;
                if (move_uploaded_file($_FILES['logo']['tmp_name'], $dir.$fn))
                    $logoPath = SITE_URL.'/assets/img/operators/'.$fn;
            }
        }

        if ($action === 'add') {
            $db->prepare("INSERT INTO operators (name,code,prefix,commission_percent,charge,charge_type,logo,status) VALUES (?,?,?,?,?,?,?,?)")
               ->execute([$name,$code,json_encode($prefixes),$commission,$charge,$charge_type,$logoPath,$status]);
            $newId = $db->lastInsertId();
            $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['op_api_'.$newId.'_st',$st_code,$st_code]);
            $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['op_api_'.$newId.'_ecare',$ecare_code,$ecare_code]);
            $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['op_api_'.$newId,$op_api_mode,$op_api_mode]);
        } else {
            $logoSql = $logoPath ? ', logo=?' : '';
            $params  = [$name,$code,json_encode($prefixes),$commission,$charge,$charge_type,$status];
            if ($logoPath) $params[] = $logoPath;
            $params[] = $id;
            $db->prepare("UPDATE operators SET name=?,code=?,prefix=?,commission_percent=?,charge=?,charge_type=?,status=?{$logoSql} WHERE id=?")->execute($params);
            $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['op_api_'.$id.'_st',$st_code,$st_code]);
            $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['op_api_'.$id.'_ecare',$ecare_code,$ecare_code]);
            $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['op_api_'.$id,$op_api_mode,$op_api_mode]);
        }
        header('Location: operators.php?ok=1'); exit;
    }

    if ($action === 'toggle') {
        $id = intval($_POST['id']);
        $db->prepare("UPDATE operators SET status=IF(status='active','inactive','active') WHERE id=?")->execute([$id]);
        header('Location: operators.php?ok=1'); exit;
    }

    if ($action === 'delete') {
        $id = intval($_POST['id']);
        $db->prepare("DELETE FROM operators WHERE id=?")->execute([$id]);
        header('Location: operators.php?ok=1'); exit;
    }
}

try {
    $operators = $db->query("SELECT o.*, (SELECT COUNT(*) FROM transactions WHERE operator_id=o.id AND type='topup') as txn_count FROM operators o ORDER BY o.id")->fetchAll();
} catch(Exception $e) {
    $operators = $db->query("SELECT * FROM operators ORDER BY id")->fetchAll();
    foreach($operators as &$op) $op['txn_count'] = 0; unset($op);
}

$opApiSettings = [];
foreach($operators as $op) {
    $opApiSettings[$op['id']] = [
        'st'    => getSetting('op_api_'.$op['id'].'_st')    ?: $op['code'],
        'ecare' => getSetting('op_api_'.$op['id'].'_ecare') ?: '',
        'api'   => getSetting('op_api_'.$op['id'])           ?: 'manual',
    ];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Operators — Admin</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>
.page-title{font-size:20px;font-weight:800;color:#0d1f4e;margin-bottom:20px;display:flex;align-items:center;gap:10px}
.btn-add-op{background:#1a3c8f;color:white;border:none;padding:10px 20px;border-radius:10px;font-size:13px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:6px}
.btn-add-op:hover{background:#0d1f4e}
.op-table{width:100%;border-collapse:collapse;background:white;border-radius:14px;overflow:hidden;box-shadow:0 2px 10px rgba(0,0,0,0.06)}
.op-table th{background:#f8fafc;padding:12px 16px;font-size:11px;font-weight:800;color:#888;text-transform:uppercase;letter-spacing:0.5px;text-align:left;border-bottom:2px solid #eef0f5}
.op-table td{padding:12px 16px;border-bottom:1px solid #f5f5f5;font-size:13px;vertical-align:middle}
.op-table tr:last-child td{border-bottom:none}
.op-table tr:hover td{background:#fafbff}
.op-logo-img{width:36px;height:36px;border-radius:8px;object-fit:contain;background:#f0f4ff;padding:4px}
.op-logo-txt{width:36px;height:36px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:900;color:white}
.op-name{font-weight:700;color:#1a1a2e}
.op-code{display:inline-block;padding:2px 8px;border-radius:20px;font-size:10px;font-weight:800;color:white}
.prefix-chip{display:inline-block;background:#e8f0fe;color:#1a3c8f;font-size:10px;font-weight:700;padding:2px 7px;border-radius:20px;margin:1px;font-family:monospace}
.api-badge{display:inline-block;padding:3px 8px;border-radius:20px;font-size:10px;font-weight:700}
.api-st{background:#e8f5e9;color:#2e7d32}
.api-ecare{background:#fff3e0;color:#e65100}
.api-custom{background:#f3e8ff;color:#553c9a}
.api-manual{background:#f0f0f0;color:#666}
.status-on{color:#38a169;font-weight:700}
.status-off{color:#e53e3e;font-weight:700}
.act-btn{padding:6px 12px;border:none;border-radius:7px;font-size:11px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:4px}
.btn-edit-sm{background:#e8f0fe;color:#1a3c8f}
.btn-edit-sm:hover{background:#1a3c8f;color:white}
.btn-del-sm{background:#fff5f5;color:#e53e3e}
.btn-del-sm:hover{background:#e53e3e;color:white}
/* Modal */
.modal-bg{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:9999;align-items:center;justify-content:center;padding:16px}
.modal-bg.show{display:flex}
.modal-box{background:white;border-radius:20px;width:100%;max-width:560px;max-height:90vh;overflow-y:auto;padding:28px}
.modal-title{font-size:18px;font-weight:800;color:#0d1f4e;margin-bottom:20px;display:flex;align-items:center;justify-content:space-between}
.modal-close{background:#f5f5f5;border:none;width:32px;height:32px;border-radius:50%;cursor:pointer;font-size:16px;display:flex;align-items:center;justify-content:center}
.form-group{margin-bottom:14px}
.form-group label{display:block;font-size:11px;font-weight:700;color:#666;text-transform:uppercase;letter-spacing:0.4px;margin-bottom:5px}
.form-group input,.form-group select{width:100%;padding:11px 13px;border:2px solid #e8ecf4;border-radius:10px;font-size:14px;outline:none;font-family:inherit;transition:0.2s}
.form-group input:focus,.form-group select:focus{border-color:#1a3c8f}
.form-row{display:grid;gap:12px}
.form-row-2{grid-template-columns:1fr 1fr}
.form-row-3{grid-template-columns:1fr 1fr 1fr}
.section-sep{font-size:11px;font-weight:700;color:#888;text-transform:uppercase;letter-spacing:0.5px;margin:18px 0 10px;padding-bottom:6px;border-bottom:1px solid #f0f0f0}
.logo-preview{margin-top:8px;height:64px;background:#f0f4ff;border-radius:10px;display:flex;align-items:center;justify-content:center;overflow:hidden;border:2px dashed #c3d3f7}
.logo-preview img{max-height:60px;max-width:100%;object-fit:contain}
.modal-footer{display:flex;gap:10px;justify-content:flex-end;margin-top:20px;padding-top:16px;border-top:1px solid #f0f0f0}
.btn-cancel{background:#f5f5f5;color:#666;border:none;padding:10px 20px;border-radius:10px;font-size:13px;font-weight:700;cursor:pointer}
.btn-save{background:#1a3c8f;color:white;border:none;padding:10px 24px;border-radius:10px;font-size:13px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:6px}
.btn-save:hover{background:#0d1f4e}
.alert{padding:12px 16px;border-radius:10px;margin-bottom:16px;font-size:13px;font-weight:600}
.alert-ok{background:#f0fff4;color:#276749;border:1px solid #c6f6d5}
.info-tip{background:#f0f4ff;border-radius:8px;padding:10px 12px;font-size:11px;color:#555;line-height:1.7;margin-bottom:10px}
</style>
</head>
<body>
<div class="admin-wrap">
<?php include '../includes/admin_sidebar.php'; ?>
<div class="main">

<?php if($msg): ?>
<div class="alert alert-ok"><?= htmlspecialchars($msg['text']) ?></div>
<?php endif; ?>

<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:20px">
    <div class="page-title"><i class="fas fa-sim-card"></i> Operators <span style="font-size:14px;color:#aaa;font-weight:400">(<?= count($operators) ?>)</span></div>
    <button class="btn-add-op" onclick="openModal()"><i class="fas fa-plus"></i> Add Operator</button>
</div>

<?php if(empty($operators)): ?>
<div style="background:white;border-radius:14px;padding:40px;text-align:center;color:#aaa;box-shadow:0 2px 10px rgba(0,0,0,0.05)">
    <i class="fas fa-sim-card" style="font-size:36px;display:block;margin-bottom:10px"></i>No operators yet
</div>
<?php else: ?>
<div style="overflow-x:auto">
<table class="op-table">
    <thead>
        <tr>
            <th>Operator</th>
            <th>Prefixes</th>
            <th>Commission</th>
            <th>API Mode</th>
            <th>Recharges</th>
            <th>Status</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
    <?php foreach($operators as $op):
        $prefixes = json_decode($op['prefix']??'[]',true) ?: [];
        $api = $opApiSettings[$op['id']] ?? [];
        $apiMode = $api['api'] ?: 'manual';
        $opColors = ['GP'=>'#009B3A','BL'=>'#FF6B00','RB'=>'#E4001D','AL'=>'#F7941D','AR'=>'#F7941D','TT'=>'#1C3F7A'];
        $color = $opColors[strtoupper($op['code'])] ?? '#1a3c8f';
        $apiLabels = ['successtopup'=>'🔄 ST','ecare'=>'⚡ ECARE','manual'=>'🖐 Manual'];
        $apiClasses = ['successtopup'=>'api-st','ecare'=>'api-ecare','manual'=>'api-manual'];
        $apiLabel = $apiLabels[$apiMode] ?? '🔌 '.$apiMode;
        $apiClass = $apiClasses[$apiMode] ?? 'api-custom';
    ?>
    <tr>
        <td>
            <div style="display:flex;align-items:center;gap:10px">
                <?php if($op['logo']): ?>
                <img src="<?= htmlspecialchars($op['logo']) ?>" class="op-logo-img" onerror="this.style.display='none'">
                <?php else: ?>
                <div class="op-logo-txt" style="background:<?= $color ?>"><?= strtoupper(substr($op['name'],0,2)) ?></div>
                <?php endif; ?>
                <div>
                    <div class="op-name"><?= htmlspecialchars($op['name']) ?></div>
                    <span class="op-code" style="background:<?= $color ?>"><?= htmlspecialchars($op['code']) ?></span>
                </div>
            </div>
        </td>
        <td>
            <?php foreach($prefixes as $p): ?>
            <span class="prefix-chip"><?= htmlspecialchars($p) ?></span>
            <?php endforeach; ?>
            <?php if(empty($prefixes)): ?><span style="color:#ccc">—</span><?php endif; ?>
        </td>
        <td style="font-weight:700;color:#1a3c8f"><?= floatval($op['commission_percent']) ?>%</td>
        <td><span class="api-badge <?= $apiClass ?>"><?= $apiLabel ?></span></td>
        <td style="font-weight:700"><?= $op['txn_count'] ?></td>
        <td>
            <form method="POST" style="display:inline">
                <input type="hidden" name="action" value="toggle">
                <input type="hidden" name="id" value="<?= $op['id'] ?>">
                <button type="submit" style="background:none;border:none;cursor:pointer;font-weight:700;font-size:12px;<?= $op['status']==='active'?'color:#38a169':'color:#e53e3e' ?>">
                    <?= $op['status']==='active' ? '✅ Active' : '❌ Inactive' ?>
                </button>
            </form>
        </td>
        <td>
            <?php
            $editData = [
                'id'=>$op['id'],'name'=>$op['name'],'code'=>$op['code'],
                'prefix'=>implode(', ',$prefixes),
                'commission_percent'=>$op['commission_percent'],
                'charge'=>$op['charge'],'charge_type'=>$op['charge_type'],
                'status'=>$op['status'],'logo'=>$op['logo']??'',
                'st_code'=>$api['st']??$op['code'],
                'ecare_code'=>$api['ecare']??'',
                'api_mode'=>$apiMode,
            ];
            ?>
            <button class="act-btn btn-edit-sm" onclick='openModal(<?= htmlspecialchars(json_encode($editData),ENT_QUOTES) ?>)'>
                <i class="fas fa-edit"></i> Edit
            </button>
            <form method="POST" style="display:inline" onsubmit="return confirm('Delete <?= addslashes($op['name']) ?>?')">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?= $op['id'] ?>">
                <button type="submit" class="act-btn btn-del-sm"><i class="fas fa-trash"></i></button>
            </form>
        </td>
    </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>
<?php endif; ?>

</div>
</div>

<!-- Add/Edit Modal -->
<div class="modal-bg" id="opModal">
<div class="modal-box">
    <div class="modal-title">
        <span id="modalTitle"><i class="fas fa-plus-circle" style="color:#1a3c8f"></i> Add Operator</span>
        <button class="modal-close" onclick="closeModal()">✕</button>
    </div>
    <form method="POST" enctype="multipart/form-data" id="opForm">
        <input type="hidden" name="action" id="fAction" value="add">
        <input type="hidden" name="id" id="fId">
        <input type="hidden" name="existing_logo" id="fExistLogo">

        <div class="section-sep">Basic Info</div>
        <div class="form-row form-row-2">
            <div class="form-group">
                <label>Name *</label>
                <input name="name" id="fName" required placeholder="Grameenphone">
            </div>
            <div class="form-group">
                <label>Code *</label>
                <input name="code" id="fCode" required placeholder="GP" style="font-weight:800;letter-spacing:1px;text-transform:uppercase" oninput="this.value=this.value.toUpperCase();autoFillCodes()">
            </div>
        </div>
        <div class="form-group">
            <label>Prefix Numbers (comma separated)</label>
            <input name="prefix" id="fPrefix" placeholder="017, 013, 019">
        </div>

        <div class="section-sep">Logo</div>
        <div class="form-group">
            <label>Logo Image (PNG/SVG/JPG)</label>
            <input type="file" name="logo" accept="image/*" onchange="previewImg(this)">
            <div class="logo-preview" id="logoPreview">
                <span style="color:#aaa;font-size:12px">No logo</span>
            </div>
        </div>

        <div class="section-sep">Commission & Charge</div>
        <div class="form-row form-row-3">
            <div class="form-group">
                <label>Commission %</label>
                <input type="number" step="0.01" name="commission" id="fComm" value="0" min="0">
            </div>
            <div class="form-group">
                <label>Charge</label>
                <input type="number" step="0.01" name="charge" id="fCharge" value="0" min="0">
            </div>
            <div class="form-group">
                <label>Charge Type</label>
                <select name="charge_type" id="fChargeType">
                    <option value="flat">Flat ৳</option>
                    <option value="percent">Percent %</option>
                </select>
            </div>
        </div>

        <div class="section-sep">API Settings</div>
        <div class="info-tip">
            🔄 <b>ST codes:</b> GP, BL, RB, AT (Airtel), TT &nbsp;|&nbsp;
            ⚡ <b>ECARE codes:</b> 7(GP), 4(BL), 8(Robi), 6(Airtel), 5(TT)
        </div>
        <div class="form-row form-row-3">
            <div class="form-group">
                <label>🔄 ST Code</label>
                <input name="st_code" id="fStCode" placeholder="GP" style="font-weight:700">
            </div>
            <div class="form-group">
                <label>⚡ ECARE Code</label>
                <input name="ecare_code" id="fEcareCode" placeholder="7" style="font-weight:700">
            </div>
            <div class="form-group">
                <label>Default API</label>
                <select name="op_api" id="fApiMode">
                    <option value="manual">🖐 Manual</option>
                    <option value="successtopup">🔄 SuccessTopUp</option>
                    <option value="ecare">⚡ ECARE</option>
                    <?php
                    try {
                        $cas = $db->query("SELECT slug,name FROM custom_apis WHERE is_active=1 ORDER BY name")->fetchAll();
                        foreach($cas as $ca) echo '<option value="'.htmlspecialchars($ca['slug']).'">🔌 '.htmlspecialchars($ca['name']).'</option>';
                    } catch(Exception $e){}
                    ?>
                </select>
            </div>
        </div>

        <div class="form-group">
            <label>Status</label>
            <select name="status" id="fStatus">
                <option value="active">✅ Active</option>
                <option value="inactive">❌ Inactive</option>
            </select>
        </div>

        <div class="modal-footer">
            <button type="button" class="btn-cancel" onclick="closeModal()">Cancel</button>
            <button type="submit" class="btn-save"><i class="fas fa-save"></i> Save Operator</button>
        </div>
    </form>
</div>
</div>

<script>
const stMap    = {GP:'GP',BL:'BL',RB:'RB',AL:'AT',AR:'AT',TT:'TT',SK:'SK',BT:'BT'};
const ecareMap = {GP:'7',BL:'4',RB:'8',AL:'6',AR:'6',TT:'5',TL:'5'};

function autoFillCodes(){
    const code = document.getElementById('fCode').value;
    if(!document.getElementById('fStCode').value)    document.getElementById('fStCode').value    = stMap[code]    || '';
    if(!document.getElementById('fEcareCode').value) document.getElementById('fEcareCode').value = ecareMap[code] || '';
}

function openModal(op){
    document.getElementById('fAction').value   = op ? 'edit' : 'add';
    document.getElementById('fId').value       = op ? op.id : '';
    document.getElementById('fName').value     = op ? op.name : '';
    document.getElementById('fCode').value     = op ? op.code : '';
    document.getElementById('fPrefix').value   = op ? op.prefix : '';
    document.getElementById('fComm').value     = op ? op.commission_percent : '0';
    document.getElementById('fCharge').value   = op ? op.charge : '0';
    document.getElementById('fChargeType').value = op ? op.charge_type : 'flat';
    document.getElementById('fStCode').value   = op ? op.st_code : '';
    document.getElementById('fEcareCode').value= op ? op.ecare_code : '';
    document.getElementById('fApiMode').value  = op ? op.api_mode : 'manual';
    document.getElementById('fStatus').value   = op ? op.status : 'active';
    document.getElementById('fExistLogo').value= op ? op.logo : '';
    document.getElementById('modalTitle').innerHTML = op
        ? '<i class="fas fa-edit" style="color:#1a3c8f"></i> Edit: '+op.name
        : '<i class="fas fa-plus-circle" style="color:#1a3c8f"></i> Add Operator';
    const prev = document.getElementById('logoPreview');
    prev.innerHTML = (op && op.logo)
        ? '<img src="'+op.logo+'">'
        : '<span style="color:#aaa;font-size:12px">No logo</span>';
    document.getElementById('opModal').classList.add('show');
}

function closeModal(){
    document.getElementById('opModal').classList.remove('show');
    document.getElementById('opForm').reset();
    document.getElementById('logoPreview').innerHTML='<span style="color:#aaa;font-size:12px">No logo</span>';
}

document.getElementById('opModal').addEventListener('click',function(e){
    if(e.target===this) closeModal();
});

function previewImg(input){
    const prev = document.getElementById('logoPreview');
    if(input.files && input.files[0]){
        const r = new FileReader();
        r.onload = e => prev.innerHTML='<img src="'+e.target.result+'">';
        r.readAsDataURL(input.files[0]);
    }
}
</script>
</body>
</html>
