<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: ../admin_panel.php");
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM admin WHERE id = ?");
$stmt->execute([$_SESSION['admin_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (isset($_POST['add_agent'])) {
    $name = trim($_POST['name']);
    $token = trim($_POST['token']);
    $balance = (int)$_POST['balance'];
    $discount = (int)$_POST['discount'];
    $service_limit = (int)$_POST['service_limit'];
    $status = isset($_POST['status']) ? 1 : 0;
    
    $check = $pdo->prepare("SELECT id FROM agents WHERE token = ?");
    $check->execute([$token]);
    if ($check->fetch()) {
        $_SESSION['error'] = "این توکن قبلاً استفاده شده است";
    } else {
        $stmt = $pdo->prepare("INSERT INTO agents (name, token, balance, discount, service_limit, status) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$name, $token, $balance, $discount, $service_limit, $status]);
        $_SESSION['success'] = "نماینده با موفقیت اضافه شد";
    }
    header("Location: agents.php");
    exit;
}

if (isset($_POST['edit_agent'])) {
    $id = (int)$_POST['id'];
    $name = trim($_POST['name']);
    $token = trim($_POST['token']);
    $balance = (int)$_POST['balance'];
    $discount = (int)$_POST['discount'];
    $service_limit = (int)$_POST['service_limit'];
    $status = isset($_POST['status']) ? 1 : 0;
    
    $check = $pdo->prepare("SELECT id FROM agents WHERE token = ? AND id != ?");
    $check->execute([$token, $id]);
    if ($check->fetch()) {
        $_SESSION['error'] = "این توکن قبلاً استفاده شده است";
    } else {
        $stmt = $pdo->prepare("UPDATE agents SET name = ?, token = ?, balance = ?, discount = ?, service_limit = ?, status = ? WHERE id = ?");
        $stmt->execute([$name, $token, $balance, $discount, $service_limit, $status, $id]);
        $_SESSION['success'] = "نماینده با موفقیت ویرایش شد";
    }
    header("Location: agents.php");
    exit;
}

if (isset($_GET['delete_agent'])) {
    $id = (int)$_GET['delete_agent'];
    $pdo->prepare("DELETE FROM agents WHERE id = ?")->execute([$id]);
    $_SESSION['success'] = "نماینده با موفقیت حذف شد";
    header("Location: agents.php");
    exit;
}

if (isset($_GET['get_agent_json'])) {
    $stmt = $pdo->prepare("SELECT * FROM agents WHERE id = ?");
    $stmt->execute([$_GET['get_agent_json']]);
    header('Content-Type: application/json');
    echo json_encode($stmt->fetch(PDO::FETCH_ASSOC));
    exit;
}

$agents = $pdo->query("SELECT * FROM agents ORDER BY id DESC")->fetchAll();
$success = $_SESSION['success'] ?? null;
$error = $_SESSION['error'] ?? null;
unset($_SESSION['success'], $_SESSION['error']);
?>
<!DOCTYPE html>
<html dir="rtl" lang="fa">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مدیریت نمایندگان | رهگذر</title>
    <link rel="stylesheet" href="../style.css">
</head>
<body>
<div class="container">
    <div class="admin-header">
        <div class="brand">
            <img src="../picture/rahgozar.png" alt="مدیریت" class="brand-logo">
            <span class="brand-name">مدیریت نمایندگان</span>
        </div>
        <div class="admin-info">
            <div class="admin-welcome">خوش آمدید، <strong><?= htmlspecialchars($admin['full_name'] ?? $admin['username']) ?></strong></div>
            <a href="../admin_panel.php" class="logout-btn">بازگشت به داشبورد</a>
            <a href="../admin_panel.php?logout=1" class="logout-btn">خروج</a>
        </div>
    </div>

    <?php if($success): ?><div class="alert alert-success"><?= htmlspecialchars($success) ?></div><?php endif; ?>
    <?php if($error): ?><div class="alert alert-error"><?= htmlspecialchars($error) ?></div><?php endif; ?>

    <div class="content-card">
        <div class="section-header">
            <div class="section-title">لیست نمایندگان</div>
            <button class="add-btn" onclick="openAddAgentModal()">+ افزودن نماینده</button>
        </div>
        <div class="table-wrapper">
            <table>
                <thead>
                    <tr><th>آیدی</th><th>نام</th><th>توکن</th><th>موجودی</th><th>تخفیف</th><th>سقف سرویس</th><th>وضعیت</th><th>عملیات</th></tr>
                </thead>
                <tbody>
                    <?php foreach($agents as $agent): ?>
                    <tr>
                        <td><?= $agent['id'] ?></td>
                        <td><?= htmlspecialchars($agent['name']) ?></td>
                        <td><code><?= htmlspecialchars($agent['token']) ?></code></td>
                        <td><?= number_format($agent['balance']) ?> تومان</td>
                        <td><?= $agent['discount'] ?>%</td>
                        <td><?= $agent['service_limit'] == 0 ? 'نامحدود' : number_format($agent['service_limit']) ?></td>
                        <td><span class="badge <?= $agent['status'] ? 'badge-active' : 'badge-inactive' ?>"><?= $agent['status'] ? 'فعال' : 'غیرفعال' ?></span></td>
                        <td class="action-buttons">
                            <button class="edit-btn" onclick="openEditAgentModal(<?= $agent['id'] ?>)">ویرایش</button>
                            <a href="?delete_agent=<?= $agent['id'] ?>" class="delete-btn" onclick="return confirm('حذف نماینده؟')">حذف</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div id="agentModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="agentModalTitle">افزودن نماینده</h3>
            <button class="close-modal" onclick="closeModal('agentModal')">×</button>
        </div>
        <form id="agentForm" method="POST">
            <input type="hidden" name="id" id="agent_id">
            <div class="form-group"><label>نام نماینده</label><input type="text" name="name" id="agent_name" required></div>
            <div class="form-group"><label>توکن</label><input type="text" name="token" id="agent_token" required></div>
            <div class="form-group"><label>موجودی (تومان)</label><input type="number" name="balance" id="agent_balance" value="0"></div>
            <div class="form-group"><label>درصد تخفیف</label><input type="number" name="discount" id="agent_discount" value="0" min="0" max="100"></div>
            <div class="form-group"><label>سقف سرویس (0=نامحدود)</label><input type="number" name="service_limit" id="agent_service_limit" value="0"></div>
            <div class="form-group checkbox-group"><input type="checkbox" name="status" id="agent_status" value="1" checked><label>فعال</label></div>
            <div class="form-actions"><button type="submit" class="btn-submit" id="agentSubmitBtn">افزودن</button><button type="button" class="btn-cancel" onclick="closeModal('agentModal')">انصراف</button></div>
        </form>
    </div>
</div>

<script>
function closeModal(modalId) { document.getElementById(modalId).style.display = 'none'; }
function openAddAgentModal() {
    document.getElementById('agentModalTitle').innerHTML = 'افزودن نماینده';
    document.getElementById('agentForm').reset();
    document.getElementById('agent_id').value = '';
    document.getElementById('agent_status').checked = true;
    let oldInput = document.querySelector('#agentForm input[name="add_agent"], #agentForm input[name="edit_agent"]');
    if (oldInput) oldInput.remove();
    let input = document.createElement('input');
    input.type = 'hidden'; input.name = 'add_agent'; input.value = '1';
    document.getElementById('agentForm').appendChild(input);
    document.getElementById('agentModal').style.display = 'flex';
}
function openEditAgentModal(id) {
    fetch('?get_agent_json=' + id).then(r => r.json()).then(agent => {
        document.getElementById('agentModalTitle').innerHTML = 'ویرایش نماینده';
        document.getElementById('agent_id').value = agent.id;
        document.getElementById('agent_name').value = agent.name;
        document.getElementById('agent_token').value = agent.token;
        document.getElementById('agent_balance').value = agent.balance;
        document.getElementById('agent_discount').value = agent.discount;
        document.getElementById('agent_service_limit').value = agent.service_limit;
        document.getElementById('agent_status').checked = (agent.status == 1);
        let oldInput = document.querySelector('#agentForm input[name="add_agent"], #agentForm input[name="edit_agent"]');
        if (oldInput) oldInput.remove();
        let input = document.createElement('input');
        input.type = 'hidden'; input.name = 'edit_agent'; input.value = '1';
        document.getElementById('agentForm').appendChild(input);
        document.getElementById('agentModal').style.display = 'flex';
    });
}
</script>
</body>
</html>