<?php
/*
 * Admin Panel - Tambah Agent
 * Integrated with MikhMon
 */

// 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('./lib/Agent.class.php');

$agent = new Agent();
$error = '';
$success = '';

// Handle form submission
if (isset($_POST['add_agent'])) {
    $agentCode = $agent->generateAgentCode();
    $agentName = trim($_POST['agent_name']);
    $phone = trim($_POST['phone']);
    $email = trim($_POST['email']);
    $password = $_POST['password'];
    $balance = floatval($_POST['balance']);
    $level = $_POST['level'];
    $commissionPercent = floatval($_POST['commission_percent']);
    $notes = trim($_POST['notes']);
    
    // Validation
    if (empty($agentName) || empty($phone) || empty($password)) {
        $error = 'Nama, nomor WhatsApp, dan password wajib diisi!';
    } else {
        // Check if phone already exists
        $existingAgent = $agent->getAgentByPhone($phone);
        if ($existingAgent) {
            $error = 'Nomor WhatsApp sudah terdaftar!';
        } else {
            $data = [
                'agent_code' => $agentCode,
                'agent_name' => $agentName,
                'phone' => $phone,
                'email' => $email,
                'password' => $password,
                'balance' => $balance,
                'status' => 'active',
                'level' => $level,
                'commission_percent' => $commissionPercent,
                'created_by' => $_SESSION['mikhmon'],
                'notes' => $notes
            ];
            
            $result = $agent->createAgent($data);
            
            if ($result['success']) {
                $success = 'Agent berhasil ditambahkan! Kode Agent: ' . $agentCode;
                // Clear form
                $_POST = array();
            } else {
                $error = $result['message'];
            }
        }
    }
}
?>

<style>
.form-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
}

.card {
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    padding: 25px;
    margin-bottom: 20px;
}

.card-header {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 2px solid #f0f0f0;
}

.card-header h3 {
    margin: 0;
    color: #333;
    font-size: 18px;
}

.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 20px;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    color: #333;
    font-weight: 500;
}

.form-group label .required {
    color: #ef4444;
}

.form-control {
    width: 100%;
    padding: 10px 15px;
    border: 1px solid #e0e0e0;
    border-radius: 5px;
    font-size: 14px;
}

.form-control:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102,126,234,0.1);
}

.form-control:disabled {
    background: #f5f5f5;
    cursor: not-allowed;
}

.btn {
    padding: 12px 30px;
    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-primary:hover {
    background: #5568d3;
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-block {
    width: 100%;
}

.alert {
    padding: 15px 20px;
    border-radius: 5px;
    margin-bottom: 20px;
}

.alert-danger {
    background: #fee;
    color: #c33;
    border: 1px solid #fcc;
}

.alert-success {
    background: #efe;
    color: #3c3;
    border: 1px solid #cfc;
}

.info-box {
    background: #f0f9ff;
    border-left: 4px solid #3b82f6;
    padding: 15px;
    border-radius: 5px;
    margin-bottom: 20px;
}

.info-box h4 {
    margin: 0 0 10px 0;
    color: #1e40af;
}

.info-box ul {
    margin: 10px 0 0 20px;
    color: #1e40af;
}

@media (max-width: 768px) {
    .form-row {
        grid-template-columns: 1fr;
    }
}
</style>

<div class="form-container">
    <div style="margin-bottom: 20px;">
        <h2><i class="fa fa-user-plus"></i> Tambah Agent Baru</h2>
        <p style="color: #666;">Daftarkan agent/reseller baru untuk sistem voucher</p>
    </div>

    <?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; ?>
        <br><br>
        <a href="./?hotspot=agent-list&session=<?= $session; ?>" class="btn btn-primary">
            <i class="fa fa-list"></i> Lihat Daftar Agent
        </a>
        <a href="./?hotspot=agent-add&session=<?= $session; ?>" class="btn btn-secondary">
            <i class="fa fa-plus"></i> Tambah Agent Lagi
        </a>
    </div>
    <?php endif; ?>

    <div class="info-box">
        <h4><i class="fa fa-info-circle"></i> Informasi</h4>
        <ul>
            <li>Kode agent akan di-generate otomatis</li>
            <li>Nomor WhatsApp akan digunakan untuk login</li>
            <li>Password minimal 6 karakter</li>
            <li>Saldo awal bisa diisi 0 dan ditopup kemudian</li>
        </ul>
    </div>

    <form method="POST">
        <!-- Data Agent -->
        <div class="card">
            <div class="card-header">
                <h3><i class="fa fa-user"></i> Data Agent</h3>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label>Nama Lengkap <span class="required">*</span></label>
                    <input type="text" name="agent_name" class="form-control" 
                           value="<?= $_POST['agent_name'] ?? ''; ?>" 
                           placeholder="Nama lengkap agent" required>
                </div>

                <div class="form-group">
                    <label>Nomor WhatsApp <span class="required">*</span></label>
                    <input type="tel" name="phone" class="form-control" 
                           value="<?= $_POST['phone'] ?? ''; ?>" 
                           placeholder="08123456789" required>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" 
                           value="<?= $_POST['email'] ?? ''; ?>" 
                           placeholder="email@example.com">
                </div>

                <div class="form-group">
                    <label>Password <span class="required">*</span></label>
                    <input type="password" name="password" class="form-control" 
                           placeholder="Minimal 6 karakter" minlength="6" required>
                </div>
            </div>
        </div>

        <!-- Pengaturan -->
        <div class="card">
            <div class="card-header">
                <h3><i class="fa fa-cog"></i> Pengaturan Agent</h3>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label>Level Agent</label>
                    <select name="level" class="form-control">
                        <option value="bronze">Bronze</option>
                        <option value="silver">Silver</option>
                        <option value="gold">Gold</option>
                        <option value="platinum">Platinum</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Komisi (%)</label>
                    <input type="number" name="commission_percent" class="form-control" 
                           value="<?= $_POST['commission_percent'] ?? '5'; ?>" 
                           min="0" max="100" step="0.1">
                </div>
            </div>

            <div class="form-group">
                <label>Saldo Awal</label>
                <input type="number" name="balance" class="form-control" 
                       value="<?= $_POST['balance'] ?? '0'; ?>" 
                       min="0" step="1000" placeholder="0">
                <small style="color: #666;">Biarkan 0 jika tidak ingin memberikan saldo awal</small>
            </div>

            <div class="form-group">
                <label>Catatan</label>
                <textarea name="notes" class="form-control" rows="3" 
                          placeholder="Catatan tambahan tentang agent ini"><?= $_POST['notes'] ?? ''; ?></textarea>
            </div>
        </div>

        <!-- Submit -->
        <div class="card">
            <button type="submit" name="add_agent" class="btn btn-primary btn-block">
                <i class="fa fa-save"></i> Simpan Agent
            </button>
            <br>
            <a href="./?hotspot=agent-list&session=<?= $session; ?>" class="btn btn-secondary btn-block">
                <i class="fa fa-arrow-left"></i> Kembali ke Daftar Agent
            </a>
        </div>
    </form>
</div>

<script>
// Format phone number
document.querySelector('input[name="phone"]').addEventListener('input', function(e) {
    let value = e.target.value.replace(/\D/g, '');
    if (value.startsWith('62')) {
        value = '0' + value.substring(2);
    }
    e.target.value = value;
});

// Generate strong password
function generatePassword() {
    const length = 8;
    const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let password = "";
    for (let i = 0; i < length; i++) {
        password += charset.charAt(Math.floor(Math.random() * charset.length));
    }
    document.querySelector('input[name="password"]').value = password;
}
</script>
