<?php
session_start();
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/lib/icons.php';
require_once __DIR__ . '/../function.php';

$query = $pdo->prepare("SELECT * FROM admin WHERE username=:username");
$query->bindParam("username", $_SESSION["user"], PDO::PARAM_STR);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);

if (!isset($_SESSION["user"]) || !$result) {
    header('Location: login.php');
    return;
}

$query = $pdo->prepare("SELECT * FROM product ORDER BY id ASC");
$query->execute();
$listinvoice = $query->fetchAll();

$query = $pdo->prepare("SELECT * FROM marzban_panel");
$query->execute();
$listpanel = $query->fetchAll();


$nameProduct = $_POST['nameproduct'] ?? null;
if (!empty($nameProduct)) {
    $randomString = bin2hex(random_bytes(2));
    $userdata['data_limit_reset'] = "no_reset";

    $product_count = select("product", "*", "name_product", $nameProduct, "count");
    if ($product_count != 0) {
        echo "<script>
alert('محصول از قبل وجود دارد'); window.location.href='product.php';
</script>";
        return;
    }

    $hidepanel       = "{}";
    $priceProduct    = $_POST['price_product']    ?? '';
    $volumeProduct   = $_POST['volume_product']   ?? '';
    $serviceTime     = $_POST['time_product']     ?? '';
    $location        = $_POST['namepanel']        ?? '';
    $agentProduct    = $_POST['agent_product']    ?? '';
    $category        = $_POST['cetegory_product'] ?? '';
    $note            = $_POST['note_product']     ?? '';
    $dataLimitReset  = $userdata['data_limit_reset'];
    $productKind     = (string)($_POST['product_kind'] ?? 'vpn');
    if (!in_array($productKind, ['vpn','pasarguard_reseller'], true)) $productKind = 'vpn';
    $provisioningJson = null;
    if ($productKind === 'pasarguard_reseller') {
        if ($location === '' || $location === '/all') {
            echo "<script>alert('برای محصول نمایندگی باید یک Backend مشخص PasarGuard انتخاب شود.');history.back();</script>"; return;
        }
        $ps = $pdo->prepare("SELECT * FROM marzban_panel WHERE name_panel=:n LIMIT 1"); $ps->execute([':n'=>$location]); $pr = $ps->fetch(PDO::FETCH_ASSOC);
        if (!$pr || ($pr['type'] ?? '') !== 'pasarguard') {
            echo "<script>alert('لوکیشن محصول نمایندگی باید از نوع PasarGuard API باشد.');history.back();</script>"; return;
        }
        $roleId = max(0, (int)($_POST['pg_role_id'] ?? ($pr['pg_default_role_id'] ?? 0)));
        if ($roleId <= 0) { echo "<script>alert('Role ID نمایندگی PasarGuard را وارد کن.');history.back();</script>"; return; }
        $pgTraffic = max(0, (float)($_POST['pg_data_limit_gb'] ?? $volumeProduct));
        $passwordLength = max(12, min(64, (int)($_POST['pg_password_length'] ?? 18)));
        $provisioningJson = json_encode([
            'role_id'=>$roleId,
            'data_limit_gb'=>$pgTraffic,
            'sub_domain'=>trim((string)($_POST['pg_sub_domain'] ?? '')) ?: null,
            'profile_title'=>trim((string)($_POST['pg_profile_title'] ?? '')) ?: null,
            'support_url'=>trim((string)($_POST['pg_support_url'] ?? '')) ?: null,
            'password_length'=>$passwordLength,
        ], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    }
    if ($productKind === 'vpn') {
        $rbProvision = [];
        $rbServiceId = max(0, (int)($_POST['rb_service_id'] ?? 0));
        $rbReset = trim((string)($_POST['rb_reset_strategy'] ?? ''));
        $rbIpLimitRaw = trim((string)($_POST['rb_ip_limit'] ?? ''));
        $rbAutoDeleteRaw = trim((string)($_POST['rb_auto_delete_days'] ?? ''));
        $rbFlow = trim((string)($_POST['rb_flow'] ?? ''));
        $rbOnHoldTimeout = max(0, (int)($_POST['rb_on_hold_timeout'] ?? 0));
        $rbOnHoldExpire = max(0, (int)($_POST['rb_on_hold_expire_duration'] ?? 0));
        $rbNextPlansRaw = trim((string)($_POST['rb_next_plans'] ?? ''));
        if ($rbServiceId > 0) $rbProvision['rb_service_id'] = $rbServiceId;
        if ($rbReset !== '') $rbProvision['rb_reset_strategy'] = $rbReset;
        if ($rbIpLimitRaw !== '') $rbProvision['rb_ip_limit'] = max(0, (int)$rbIpLimitRaw);
        if ($rbAutoDeleteRaw !== '') $rbProvision['rb_auto_delete_days'] = max(0, (int)$rbAutoDeleteRaw);
        if ($rbFlow !== '') $rbProvision['rb_flow'] = $rbFlow;
        if ($rbOnHoldTimeout > 0) $rbProvision['rb_on_hold_timeout'] = $rbOnHoldTimeout;
        if ($rbOnHoldExpire > 0) $rbProvision['rb_on_hold_expire_duration'] = $rbOnHoldExpire;
        if ($rbNextPlansRaw !== '') {
            $decoded = json_decode($rbNextPlansRaw, true);
            if (!is_array($decoded)) { echo "<script>alert('Next Plans ربکا باید JSON معتبر باشد.');history.back();</script>"; return; }
            $rbProvision['rb_next_plans'] = $decoded;
        }
        if ($rbProvision) $provisioningJson = json_encode($rbProvision, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    }

    $stmt = $pdo->prepare("INSERT IGNORE INTO product (name_product,code_product,price_product,Volume_constraint,Service_time,Location,agent,data_limit_reset,note,category,hide_panel,one_buy_status,product_kind,provisioning_json) VALUES (:name_product,:code_product,:price_product,:Volume_constraint,:Service_time,:Location,:agent,:data_limit_reset,:note,:category,:hide_panel,'0',:product_kind,:provisioning_json)");
    $stmt->bindParam(':name_product',     $nameProduct, PDO::PARAM_STR);
    $stmt->bindParam(':code_product',     $randomString);
    $stmt->bindParam(':price_product',    $priceProduct, PDO::PARAM_STR);
    $stmt->bindParam(':Volume_constraint',$volumeProduct, PDO::PARAM_STR);
    $stmt->bindParam(':Service_time',     $serviceTime, PDO::PARAM_STR);
    $stmt->bindParam(':Location',         $location, PDO::PARAM_STR);
    $stmt->bindParam(':agent',            $agentProduct, PDO::PARAM_STR);
    $stmt->bindParam(':data_limit_reset', $dataLimitReset);
    $stmt->bindParam(':category',         $category, PDO::PARAM_STR);
    $stmt->bindParam(':note',             $note, PDO::PARAM_STR);
    $stmt->bindParam(':hide_panel',       $hidepanel);
    $stmt->bindParam(':product_kind',     $productKind);
    $stmt->bindParam(':provisioning_json',$provisioningJson);
    $stmt->execute();

    header("Location: product.php");
    exit;
}


if (isset($_GET['oneproduct'], $_GET['toweproduct']) && $_GET['oneproduct'] !== '' && $_GET['toweproduct'] !== '') {
    update("product", "id", 10000, "id", $_GET['oneproduct']);
    update("product", "id", intval($_GET['oneproduct']),  "id", intval($_GET['toweproduct']));
    update("product", "id", intval($_GET['toweproduct']), "id", 10000);
    header("Location: product.php");
    exit;
}


if (isset($_GET['removeid']) && $_GET['removeid'] !== '') {
    $stmt = $pdo->prepare("DELETE FROM product WHERE id = :id");
    $stmt->bindParam(':id', $_GET['removeid']);
    $stmt->execute();
    header("Location: product.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>مدیریت پلن‌ها | iTzAYDiN-BOT</title>
    <link rel="stylesheet" href="css/theme.css">
<script src="js/theme.js" defer>

</script>
</head>
<body>

<section id="container">
    <?php include("header.php"); ?>

    <section id="main-content">
        <div class="wrapper">

            <div class="page-head">
                <div>
                    <div class="page-head__title">
                        <?php echo icon('grid', 'svg-icon svg-lg'); ?>
                        لیست پلن‌ها
                    </div>
                    <div class="page-head__sub">مدیریت محصولات روی همه Backendها؛ VPN، پنل و نمایندگی</div>
                </div>
                <div class="chip-row">
                    <button onclick="openModal('modal-add-product')" class="btn btn-primary btn-sm">
                        <?php echo icon('plus', 'svg-icon'); ?> افزودن محصول
                    </button>
                    <button onclick="openModal('modal-move-product')" class="btn btn-soft-purple btn-sm">
                        <?php echo icon('arrow-right-arrow-left', 'svg-icon'); ?> جابجایی ردیف
                    </button>
                </div>
            </div>

            <div class="card">
                <div class="table-wrap">
                    <table id="productsTable" class="display app-table" style="width:100%" data-mdt-filter="5,6,7">
                        <thead>
                            <tr>
                                <th>شناسه</th>
                                <th>عنوان پلن</th>
                                <th>نوع محصول</th>
                                <th>قیمت</th>
                                <th>حجم (GB)</th>
                                <th>زمان (روز)</th>
                                <th>لوکیشن</th>
                                <th>گروه کاربری</th>
                                <th>دسته‌بندی</th>
                                <th>عملیات</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($listinvoice as $list):
                            $category = ($list['category'] == null) ? 'ندارد' : htmlspecialchars($list['category'], ENT_QUOTES, 'UTF-8');
                            $agent_type = 'عادی'; $agent_badge = 'badge-gray';
                            if ($list['agent'] == 'n')  { $agent_type = 'نماینده';      $agent_badge = 'badge-purple';  }
                            if ($list['agent'] == 'n2') { $agent_type = 'نماینده ویژه';  $agent_badge = 'badge-warning'; }
                        ?>
                            <tr>
                                <td data-label="شناسه"><?php echo $list['id']; ?></td>
                                <td data-label="عنوان پلن"><?php echo htmlspecialchars($list['name_product'], ENT_QUOTES, 'UTF-8'); ?></td>
                                <td data-label="نوع محصول"><span class="badge <?php echo (($list['product_kind'] ?? 'vpn') === 'pasarguard_reseller') ? 'badge-warning' : 'badge-info'; ?>"><?php echo (($list['product_kind'] ?? 'vpn') === 'pasarguard_reseller') ? '🛡 نمایندگی PasarGuard' : '🌐 سرویس VPN'; ?></span></td>
                                <td data-label="قیمت"><span class="badge badge-success"><?php echo number_format($list['price_product']); ?></span></td>
                                <td data-label="حجم (GB)"><span class="badge badge-info"><?php echo (int)$list['Volume_constraint']; ?></span></td>
                                <td data-label="زمان (روز)"><span class="badge badge-warning"><?php echo (int)$list['Service_time']; ?></span></td>
                                <td data-label="لوکیشن"><span class="badge badge-cyan"><?php echo htmlspecialchars($list['Location'], ENT_QUOTES, 'UTF-8'); ?></span></td>
                                <td data-label="گروه کاربری"><span class="badge <?php echo $agent_badge; ?>"><?php echo $agent_type; ?></span></td>
                                <td data-label="دسته‌بندی"><?php echo $category; ?></td>
                                <td data-label="عملیات" class="cell-actions">
                                    <div style="display:inline-flex; gap:6px;">
                                        <a href="productedit.php?id=<?php echo $list['id']; ?>" class="btn btn-sm btn-soft-info" title="ویرایش">
                                            <?php echo icon('pen', 'svg-icon'); ?>
                                        </a>
                                        <a href="product.php?removeid=<?php echo $list['id']; ?>" class="btn btn-sm btn-soft-danger" title="حذف"
                                           onclick="return confirm('آیا از حذف این محصول مطمئن هستید؟')">
                                            <?php echo icon('trash', 'svg-icon'); ?>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        </div>
    </section>
</section>


<div id="modal-add-product" class="modal-overlay">
    <div class="modal-box" style="max-width:560px;">
        <div class="modal-head">
            <span class="modal-head__title">افزودن محصول جدید</span>
            <button class="modal-close" onclick="closeModal('modal-add-product')">&times;</button>
        </div>
        <form action="product.php" method="POST">
            <div class="form-group">
                <label class="form-label">عنوان پلن</label>
                <input type="text" name="nameproduct" class="form-control" placeholder="عنوان پلن را وارد کنید" required>
            </div>

            <div class="form-group">
                <label class="form-label">نوع محصول</label>
                <select name="product_kind" id="productKind" class="form-control" required>
                    <option value="vpn">🌐 سرویس VPN / اشتراک معمولی</option>
                    <option value="pasarguard_reseller">🛡 پنل نمایندگی PasarGuard</option>
                </select>
                <div class="form-hint">محصول نمایندگی بعد از پرداخت، Remote Admin واقعی را از API خود PasarGuard می‌سازد.</div>
            </div>

            <div class="form-group">
                <label class="form-label">پنل (موقعیت)</label>
                <select name="namepanel" id="productPanel" class="form-control" required>
                    <option value="/all">تمامی پنل‌ها</option>
                    <?php foreach ($listpanel as $panel): ?>
                        <option data-panel-type="<?php echo htmlspecialchars((string)($panel['type'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>" value="<?php echo htmlspecialchars($panel['name_panel'], ENT_QUOTES, 'UTF-8'); ?>">
                            <?php echo htmlspecialchars($panel['name_panel'], ENT_QUOTES, 'UTF-8'); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label class="form-label">قیمت (تومان)</label>
                    <input type="number" name="price_product" class="form-control" required>
                </div>
                <div class="form-group">
                    <label class="form-label">حجم (GB)</label>
                    <input type="number" name="volume_product" class="form-control" required>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label class="form-label">زمان (روز)</label>
                    <input type="number" name="time_product" class="form-control" required>
                </div>
                <div class="form-group">
                    <label class="form-label">نوع کاربر</label>
                    <select name="agent_product" class="form-control" required>
                        <option value="f">کاربر عادی</option>
                        <option value="n">نماینده</option>
                        <option value="n2">نماینده پیشرفته</option>
                    </select>
                </div>
            </div>

            <div id="pgResellerFields" style="display:none;padding:14px;border:1px solid var(--border-soft);border-radius:14px;margin-bottom:14px">
                <div class="alert alert-info">این قسمت فقط برای فروش <b>Remote Admin / نمایندگی واقعی PasarGuard</b> است.</div>
                <div class="form-row"><div class="form-group"><label class="form-label">Role ID نمایندگی</label><input type="number" min="1" name="pg_role_id" class="form-control" placeholder="مثلاً 2"></div><div class="form-group"><label class="form-label">سقف ترافیک نماینده (GB)</label><input type="number" min="0" step="0.01" name="pg_data_limit_gb" class="form-control" placeholder="0 = نامحدود"></div></div>
                <div class="form-row"><div class="form-group"><label class="form-label">طول رمز خودکار</label><input type="number" min="12" max="64" name="pg_password_length" class="form-control" value="18"></div><div class="form-group"><label class="form-label">Profile Title</label><input type="text" name="pg_profile_title" class="form-control" placeholder="iTzAYDiN Reseller"></div></div>
                <div class="form-row"><div class="form-group"><label class="form-label">Sub Domain (اختیاری)</label><input type="text" name="pg_sub_domain" class="form-control"></div><div class="form-group"><label class="form-label">Support URL (اختیاری)</label><input type="url" name="pg_support_url" class="form-control"></div></div>
                <div class="form-hint">Role IDها را در iTz PasarGuard Hub می‌بینی. مدت محصول، تاریخ پایان نمایندگی در iTzAYDiN-BOT است و Cron بعد از پایان آن Remote Admin را Disable می‌کند.</div>
            </div>
            <details id="rbProvisionFields" style="padding:14px;border:1px solid var(--border-soft);border-radius:14px;margin-bottom:14px">
                <summary style="cursor:pointer;font-weight:800">🧬 تنظیمات پیشرفته Rebecca (اختیاری)</summary>
                <div class="alert alert-info" style="margin-top:12px">Rebecca کاربر را به <b>Service</b> متصل می‌کند. اگر Service ID را خالی بگذاری، Service پیش‌فرض انتخاب‌شده در Rebecca Hub استفاده می‌شود.</div>
                <div class="form-row"><div class="form-group"><label class="form-label">Service ID</label><input type="number" min="1" name="rb_service_id" class="form-control" placeholder="خالی = پیش‌فرض Backend"></div><div class="form-group"><label class="form-label">IP Limit</label><input type="number" min="0" name="rb_ip_limit" class="form-control" placeholder="مثلاً 2"></div></div>
                <div class="form-row"><div class="form-group"><label class="form-label">Traffic Reset Strategy</label><input type="text" name="rb_reset_strategy" class="form-control" placeholder="طبق مقدار معتبر همین نسخه Rebecca"></div><div class="form-group"><label class="form-label">Flow</label><input type="text" name="rb_flow" class="form-control" placeholder="مثلاً xtls-rprx-vision"></div></div>
                <div class="form-row"><div class="form-group"><label class="form-label">Auto Delete (روز)</label><input type="number" min="0" name="rb_auto_delete_days" class="form-control" placeholder="0 = غیرفعال"></div><div class="form-group"><label class="form-label">On-hold timeout</label><input type="number" min="0" name="rb_on_hold_timeout" class="form-control"></div></div>
                <div class="form-group"><label class="form-label">On-hold expire duration</label><input type="number" min="0" name="rb_on_hold_expire_duration" class="form-control"></div>
                <div class="form-group"><label class="form-label">Next Plans JSON</label><textarea name="rb_next_plans" class="form-control" rows="3" dir="ltr" placeholder='[]'></textarea></div>
                <div class="form-hint">برای دیدن Serviceها و قابلیت‌های دقیق نسخه نصب‌شده، از iTz Rebecca Hub → Live OpenAPI استفاده کن.</div>
            </details>

            <div class="form-group">
                <label class="form-label">دسته‌بندی</label>
                <input type="text" name="cetegory_product" class="form-control" required>
            </div>

            <div class="form-group">
                <label class="form-label">توضیحات</label>
                <input type="text" name="note_product" class="form-control" required>
            </div>

            <button type="submit" class="btn btn-primary btn-block">افزودن محصول</button>
        </form>
    </div>
</div>


<div id="modal-move-product" class="modal-overlay">
    <div class="modal-box">
        <div class="modal-head">
            <span class="modal-head__title">جابجایی ردیف پلن‌ها</span>
            <button class="modal-close" onclick="closeModal('modal-move-product')">&times;</button>
        </div>
        <form action="product.php" method="GET">
            <div class="form-group">
                <label class="form-label">شناسه محصول اول</label>
                <input type="number" name="oneproduct" class="form-control" required>
            </div>
            <div class="form-group">
                <label class="form-label">شناسه محصول دوم</label>
                <input type="number" name="toweproduct" class="form-control" required>
            </div>
            <button type="submit" class="btn btn-soft-purple btn-block">جابجایی</button>
        </form>
    </div>
</div>
<script src="js/datatable.js" defer>

</script>
<script>
  document.addEventListener("DOMContentLoaded", function () {
    AYCoreDT.init("#productsTable");
  });
</script>
<script>
(function(){
 const kind=document.getElementById('productKind'), box=document.getElementById('pgResellerFields'), rbBox=document.getElementById('rbProvisionFields');
 const panel=document.querySelector('select[name="namepanel"]');
 function sync(){const isPg=kind&&kind.value==='pasarguard_reseller'; if(box) box.style.display=isPg?'block':'none'; if(rbBox) rbBox.style.display=isPg?'none':'block'; if(panel){[...panel.options].forEach(o=>{if(o.value==='/all')o.disabled=isPg; else if(isPg)o.disabled=(o.dataset.panelType!=='pasarguard'); else o.disabled=false;}); if(isPg && (panel.value==='/all'||panel.selectedOptions[0]?.disabled)){const ok=[...panel.options].find(o=>!o.disabled&&o.value!=='/all'); if(ok)panel.value=ok.value;}}}
 kind?.addEventListener('change',sync); sync();
})();
</script></body>
</html>


