<?php
/*
 * Admin Panel - Kelola Harga Agent
 */

// No session_start() needed - already started in index.php
// No auth check needed - already checked in index.php

include_once('./include/db_config.php');
include_once('./include/config.php');
include_once('./lib/Agent.class.php');
include_once('./lib/routeros_api.class.php');

$agent = new Agent();
$agents = $agent->getAllAgents('active');

// Get MikroTik profiles
$sessions = array_keys($data);
$session_name = null;
foreach ($sessions as $s) {
    if ($s != 'mikhmon') {
        $session_name = $s;
        break;
    }
}

$profiles = [];
if ($session_name) {
    $iphost = explode('!', $data[$session_name][1])[1];
    $userhost = explode('@|@', $data[$session_name][2])[1];
    $passwdhost = explode('#|#', $data[$session_name][3])[1];
    
    $API = new RouterosAPI();
    $API->debug = false;
    if ($API->connect($iphost, $userhost, decrypt($passwdhost))) {
        $profiles = $API->comm("/ip/hotspot/user/profile/print");
        $API->disconnect();
    }
}

$error = '';
$success = '';

// Handle delete
if (isset($_GET['delete'])) {
    $priceId = $_GET['delete'];
    $result = $agent->deleteAgentPrice($priceId);
    if ($result['success']) {
        $success = 'Harga berhasil dihapus!';
    } else {
        $error = $result['message'];
    }
}

// Handle set/update price
if (isset($_POST['set_price'])) {
    $agentId = $_POST['agent_id'];
    $profileName = $_POST['profile_name'];
    $buyPrice = floatval($_POST['buy_price']);
    $sellPrice = floatval($_POST['sell_price']);
    
    $result = $agent->setAgentPrice($agentId, $profileName, $buyPrice, $sellPrice);
    
    if ($result['success']) {
        $success = 'Harga berhasil diset!';
    } else {
        $error = $result['message'];
    }
}
?>

<style>
.price-container { padding: 20px; max-width: 1200px; margin: 0 auto; }
.card { background: white; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); padding: 25px; margin-bottom: 20px; }
.form-row { display: grid; grid-template-columns: 2fr 1fr 1fr 1fr; gap: 15px; align-items: end; margin-bottom: 15px; }
.form-group { margin-bottom: 15px; }
.form-group label { display: block; margin-bottom: 8px; color: #333; font-weight: 500; font-size: 14px; }
.form-control { width: 100%; padding: 10px 15px; border: 1px solid #e0e0e0; border-radius: 5px; font-size: 14px; }
.btn { padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; font-weight: 500; font-size: 14px; text-decoration: none; display: inline-block; }
.btn-primary { background: #667eea; color: white; }
.btn-success { background: #10b981; color: white; }
.btn-warning { background: #f59e0b; color: white; }
.btn-danger { background: #ef4444; color: white; }
.btn-sm { padding: 6px 12px; font-size: 12px; margin-right: 5px; }
.alert { padding: 15px 20px; border-radius: 5px; margin-bottom: 20px; }
.alert-danger { background: #fee; color: #c33; }
.alert-success { background: #efe; color: #3c3; }
table { width: 100%; border-collapse: collapse; }
table th { background: #f8f9fa; padding: 12px; text-align: left; font-weight: 600; border-bottom: 2px solid #e0e0e0; }
table td { padding: 12px; border-bottom: 1px solid #f0f0f0; }
@media (max-width: 768px) { .form-row { grid-template-columns: 1fr; } }
</style>

<div class="price-container">
    <h2><i class="fa fa-tags"></i> Kelola Harga Agent</h2>
    <p style="color: #666; margin-bottom: 20px;">Set harga beli dan jual untuk setiap agent per profile</p>

    <?php if ($error): ?>
    <div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?= $error; ?></div>
    <?php endif; ?>

    <?php if ($success): ?>
    <div class="alert alert-success"><i class="fa fa-check-circle"></i> <?= $success; ?></div>
    <?php endif; ?>

    <div class="card">
        <h3 style="margin-bottom: 20px;"><i class="fa fa-plus-circle"></i> Set Harga Baru</h3>
        <form method="POST">
            <div class="form-row">
                <div class="form-group">
                    <label>Pilih Agent</label>
                    <select name="agent_id" class="form-control" required>
                        <option value="">-- Pilih Agent --</option>
                        <?php foreach ($agents as $agt): ?>
                        <option value="<?= $agt['id']; ?>"><?= $agt['agent_name']; ?> (<?= $agt['agent_code']; ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Profile</label>
                    <select name="profile_name" class="form-control" required>
                        <option value="">-- Pilih Profile --</option>
                        <?php foreach ($profiles as $prof): ?>
                        <?php if ($prof['name'] != 'default' && $prof['name'] != 'default-encryption'): ?>
                        <option value="<?= $prof['name']; ?>"><?= $prof['name']; ?></option>
                        <?php endif; ?>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Harga Beli</label>
                    <input type="number" name="buy_price" class="form-control" placeholder="5000" required>
                </div>
                <div class="form-group">
                    <label>Harga Jual</label>
                    <input type="number" name="sell_price" class="form-control" placeholder="7000" required>
                </div>
            </div>
            <button type="submit" name="set_price" class="btn btn-primary">
                <i class="fa fa-save"></i> Simpan Harga
            </button>
        </form>
    </div>

    <?php foreach ($agents as $agt): ?>
    <?php $agentPrices = $agent->getAllAgentPrices($agt['id']); ?>
    <?php if (!empty($agentPrices)): ?>
    <div class="card">
        <h3><i class="fa fa-user"></i> <?= $agt['agent_name']; ?> (<?= $agt['agent_code']; ?>)</h3>
        <table>
            <thead>
                <tr>
                    <th>Profile</th>
                    <th>Harga Beli</th>
                    <th>Harga Jual</th>
                    <th>Profit</th>
                    <th>Update</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($agentPrices as $price): ?>
                <tr>
                    <td><strong><?= $price['profile_name']; ?></strong></td>
                    <td>Rp <?= number_format($price['buy_price'], 0, ',', '.'); ?></td>
                    <td>Rp <?= number_format($price['sell_price'], 0, ',', '.'); ?></td>
                    <td style="color: #10b981; font-weight: bold;">Rp <?= number_format($price['sell_price'] - $price['buy_price'], 0, ',', '.'); ?></td>
                    <td><?= date('d M Y', strtotime($price['updated_at'])); ?></td>
                    <td>
                        <button onclick="editPrice(<?= $agt['id']; ?>, '<?= $price['profile_name']; ?>', <?= $price['buy_price']; ?>, <?= $price['sell_price']; ?>)" 
                                class="btn btn-sm btn-warning" title="Edit">
                            <i class="fa fa-edit"></i>
                        </button>
                        <a href="?hotspot=agent-prices&delete=<?= $price['id']; ?>&session=<?= $session; ?>" 
                           onclick="return confirm('Yakin ingin menghapus harga untuk profile <?= $price['profile_name']; ?>?')"
                           class="btn btn-sm btn-danger" title="Hapus">
                            <i class="fa fa-trash"></i>
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
    <?php endforeach; ?>
</div>

<script>
function editPrice(agentId, profileName, buyPrice, sellPrice) {
    // Scroll to form
    window.scrollTo({ top: 0, behavior: 'smooth' });
    
    // Fill form
    document.querySelector('select[name="agent_id"]').value = agentId;
    document.querySelector('select[name="profile_name"]').value = profileName;
    document.querySelector('input[name="buy_price"]').value = buyPrice;
    document.querySelector('input[name="sell_price"]').value = sellPrice;
    
    // Focus on buy price
    document.querySelector('input[name="buy_price"]').focus();
    
    // Change button text
    const btn = document.querySelector('button[name="set_price"]');
    btn.innerHTML = '<i class="fa fa-save"></i> Update Harga';
    btn.classList.remove('btn-primary');
    btn.classList.add('btn-warning');
}
</script>
