<?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;
}

$statusmessage = false;
$infomesssage  = "";
$id_product    = htmlspecialchars($_GET['id'], ENT_QUOTES, 'UTF-8');
$product       = select("product", "*", "id", $id_product, "select");

$panelQuery = $pdo->prepare("SELECT name_panel,type,pg_default_role_id FROM marzban_panel ORDER BY id ASC");
$panelQuery->execute();
$listpanel = $panelQuery->fetchAll(PDO::FETCH_ASSOC);

if ($product == false) {
    $statusmessage = true;
    $infomesssage  = "محصول موردنظر پیدا نشد!";
} else {
    if (isset($_GET['action']) && $_GET['action'] == "save") {
        $name_product = htmlspecialchars($_POST['name_product'], ENT_QUOTES, 'UTF-8');
        $prodcutcheck = select("product", "*", "name_product", $name_product, "count");
        if ($product['name_product'] != $name_product && $prodcutcheck != 0) {
            $statusmessage = true;
            $infomesssage  = "عنوان پلن تکراری است.";
        } else {
            if ($product['name_product'] != $name_product) {
                update("product", "name_product", $name_product, "id", $id_product);
            }
        }

        $price_product = htmlspecialchars($_POST['price_product'], ENT_QUOTES, 'UTF-8');
        if (!is_numeric($price_product)) {
            $statusmessage = true; $infomesssage = "مبلغ محصول باید عدد باشد";
        } elseif ($product['price_product'] != $price_product) {
            update("product", "price_product", $price_product, "id", $id_product);
        }

        $Volume_constraint = htmlspecialchars($_POST['Volume_constraint'], ENT_QUOTES, 'UTF-8');
        if (!is_numeric($Volume_constraint)) {
            $statusmessage = true; $infomesssage = "حجم محصول باید عدد باشد";
        } elseif ($product['Volume_constraint'] != $Volume_constraint) {
            update("product", "Volume_constraint", $Volume_constraint, "id", $id_product);
        }

        $Service_time = htmlspecialchars($_POST['Service_time'], ENT_QUOTES, 'UTF-8');
        if (!is_numeric($Service_time)) {
            $statusmessage = true; $infomesssage = "زمان محصول باید عدد باشد";
        } elseif ($product['Service_time'] != $Service_time) {
            update("product", "Service_time", $Service_time, "id", $id_product);
        }

        $agent = htmlspecialchars($_POST['agent'], ENT_QUOTES, 'UTF-8');
        if (!in_array($agent, ['f', 'n', 'n2'])) {
            $statusmessage = true; $infomesssage = "گروه کاربری معتبر نیست";
        } elseif ($product['agent'] != $agent) {
            update("product", "agent", $agent, "id", $id_product);
        }

        $category = htmlspecialchars($_POST['category'], ENT_QUOTES, 'UTF-8');
        if ($product['category'] != $category) {
            update("product", "category", $category, "id", $id_product);
        }

        $locationPost = htmlspecialchars($_POST['Location'] ?? '', ENT_QUOTES, 'UTF-8');
        if ($product['Location'] != $locationPost) {
            update("product", "Location", $locationPost, "id", $id_product);
        }

        $productKind = (string)($_POST['product_kind'] ?? ($product['product_kind'] ?? 'vpn'));
        if (!in_array($productKind, ['vpn','pasarguard_reseller'], true)) $productKind='vpn';
        $provisioningJson = null;
        if ($productKind === 'pasarguard_reseller') {
            $ps=$pdo->prepare("SELECT * FROM marzban_panel WHERE name_panel=:n LIMIT 1");$ps->execute([':n'=>$locationPost]);$pr=$ps->fetch(PDO::FETCH_ASSOC);
            if(!$pr || ($pr['type']??'')!=='pasarguard') { $statusmessage=true; $infomesssage='محصول نمایندگی باید به Backend واقعی PasarGuard متصل باشد.'; }
            else {
                $roleId=max(0,(int)($_POST['pg_role_id']??($pr['pg_default_role_id']??0)));
                if($roleId<=0){$statusmessage=true;$infomesssage='Role ID نمایندگی لازم است.';}
                $provisioningJson=json_encode([
                    'role_id'=>$roleId,
                    'data_limit_gb'=>max(0,(float)($_POST['pg_data_limit_gb']??0)),
                    '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'=>max(12,min(64,(int)($_POST['pg_password_length']??18))),
                ],JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
            }
        }
        if(!$statusmessage){ update('product','product_kind',$productKind,'id',$id_product); update('product','provisioning_json',$provisioningJson,'id',$id_product); }

        $note = htmlspecialchars($_POST['note'], ENT_QUOTES, 'UTF-8');
        if ($product['note'] != $note) {
            update("product", "note", $note, "id", $id_product);
        }

        if (!$statusmessage) {
            header('Location: product.php');
            exit;
        }
    }
}
$pgMeta=[];
if(is_array($product) && !empty($product['provisioning_json'])){ $tmp=json_decode((string)$product['provisioning_json'],true); if(is_array($tmp))$pgMeta=$tmp; }
?>
<!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('pen-to-square', 'svg-icon svg-lg'); ?>
                        ویرایش محصول
                    </div>
                    <div class="page-head__sub">
                        <a href="product.php" class="text-link">
                            <?php echo icon('arrow-right', 'svg-icon'); ?> بازگشت به لیست پلن‌ها
                        </a>
                    </div>
                </div>
            </div>

            <div class="card" style="max-width:820px; margin: 0 auto;">

                <?php if ($statusmessage): ?>
                    <div class="alert alert-error">
                        <?php echo icon('circle-exclamation', 'svg-icon'); ?>
                        <span><?php echo $infomesssage; ?></span>
                    </div>
                <?php endif; ?>

                <?php if ($product): ?>
                <form action="productedit.php?action=save&id=<?php echo $id_product; ?>" method="POST">

                    <div class="form-group">
                        <label class="form-label">عنوان پلن</label>
                        <input type="text" name="name_product" class="form-control" value="<?php echo htmlspecialchars($product['name_product'], ENT_QUOTES, 'UTF-8'); ?>" required>
                    </div>

                    <div class="form-group"><label class="form-label">نوع محصول</label><select class="form-control" name="product_kind" id="productKind"><option value="vpn" <?php if(($product['product_kind']??'vpn')==='vpn')echo 'selected';?>>🌐 سرویس VPN</option><option value="pasarguard_reseller" <?php if(($product['product_kind']??'')==='pasarguard_reseller')echo 'selected';?>>🛡 نمایندگی PasarGuard</option></select></div>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">قیمت (تومان)</label>
                            <input type="number" name="price_product" class="form-control" value="<?php echo htmlspecialchars($product['price_product'], ENT_QUOTES, 'UTF-8'); ?>" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">حجم (GB)</label>
                            <input type="number" name="Volume_constraint" class="form-control" value="<?php echo htmlspecialchars($product['Volume_constraint'], ENT_QUOTES, 'UTF-8'); ?>" required>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">زمان (روز)</label>
                            <input type="number" name="Service_time" class="form-control" value="<?php echo htmlspecialchars($product['Service_time'], ENT_QUOTES, 'UTF-8'); ?>" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">نوع کاربر</label>
                            <select name="agent" class="form-control">
                                <option value="f"  <?php if ($product['agent']=='f')  echo 'selected'; ?>>کاربر عادی</option>
                                <option value="n"  <?php if ($product['agent']=='n')  echo 'selected'; ?>>نماینده معمولی</option>
                                <option value="n2" <?php if ($product['agent']=='n2') echo 'selected'; ?>>نماینده پیشرفته</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label">پنل (لوکیشن)</label>
                        <select name="Location" class="form-control" required>
                            <option value="/all" <?php if ($product['Location'] == '/all') echo 'selected'; ?>>تمامی پنل‌ها</option>
                            <?php
                            $currentLoc = (string)($product['Location'] ?? '');
                            $foundCurrent = ($currentLoc === '/all');
                            foreach ($listpanel as $panel):
                                $pname = (string)($panel['name_panel'] ?? '');
                                if ($pname === $currentLoc) $foundCurrent = true;
                            ?>
                                <option data-panel-type="<?php echo htmlspecialchars((string)($panel['type']??''), ENT_QUOTES, 'UTF-8'); ?>" value="<?php echo htmlspecialchars($pname, ENT_QUOTES, 'UTF-8'); ?>" <?php if ($pname === $currentLoc) echo 'selected'; ?>>
                                    <?php echo htmlspecialchars($pname, ENT_QUOTES, 'UTF-8'); ?>
                                </option>
                            <?php endforeach; ?>
                            <?php if (!$foundCurrent && $currentLoc !== ''): ?>
                                <option value="<?php echo htmlspecialchars($currentLoc, ENT_QUOTES, 'UTF-8'); ?>" selected>
                                    <?php echo htmlspecialchars($currentLoc, ENT_QUOTES, 'UTF-8'); ?> (حذف‌شده)
                                </option>
                            <?php endif; ?>
                        </select>
                    </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">تنظیمات Provisioning نمایندگی PasarGuard</div><div class="form-row"><div class="form-group"><label class="form-label">Role ID</label><input class="form-control" type="number" min="1" name="pg_role_id" value="<?php echo htmlspecialchars((string)($pgMeta['role_id']??0)); ?>"></div><div class="form-group"><label class="form-label">Traffic Limit GB</label><input class="form-control" type="number" min="0" step="0.01" name="pg_data_limit_gb" value="<?php echo htmlspecialchars((string)($pgMeta['data_limit_gb']??0)); ?>"></div></div><div class="form-row"><div class="form-group"><label class="form-label">Password Length</label><input class="form-control" type="number" min="12" max="64" name="pg_password_length" value="<?php echo htmlspecialchars((string)($pgMeta['password_length']??18)); ?>"></div><div class="form-group"><label class="form-label">Profile Title</label><input class="form-control" name="pg_profile_title" value="<?php echo htmlspecialchars((string)($pgMeta['profile_title']??'')); ?>"></div></div><div class="form-row"><div class="form-group"><label class="form-label">Sub Domain</label><input class="form-control" name="pg_sub_domain" value="<?php echo htmlspecialchars((string)($pgMeta['sub_domain']??'')); ?>"></div><div class="form-group"><label class="form-label">Support URL</label><input class="form-control" name="pg_support_url" value="<?php echo htmlspecialchars((string)($pgMeta['support_url']??'')); ?>"></div></div></div>

                    <div class="form-group">
                        <label class="form-label">دسته‌بندی</label>
                        <input type="text" name="category" class="form-control" value="<?php echo htmlspecialchars($product['category'], ENT_QUOTES, 'UTF-8'); ?>">
                    </div>

                    <div class="form-group">
                        <label class="form-label">یادداشت</label>
                        <textarea name="note" class="form-control" rows="3"><?php echo htmlspecialchars($product['note'], ENT_QUOTES, 'UTF-8'); ?></textarea>
                    </div>

                    <button type="submit" class="btn btn-primary btn-block">
                        <?php echo icon('check', 'svg-icon'); ?> ذخیره تغییرات
                    </button>

                </form>
                <?php endif; ?>
            </div>

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

<script>(function(){const k=document.getElementById('productKind'),b=document.getElementById('pgResellerFields'),p=document.querySelector('select[name="Location"]');function sync(){const x=k&&k.value==='pasarguard_reseller';if(b)b.style.display=x?'block':'none';if(p){[...p.options].forEach(o=>{if(o.value==='/all')o.disabled=x;else if(x&&o.dataset.panelType)o.disabled=o.dataset.panelType!=='pasarguard';else if(!x)o.disabled=false;});}}k?.addEventListener('change',sync);sync();})();</script></body>
</html>


