<?php
// TEMP DEBUG: production php.ini usually has display_errors Off, which
// turns any fatal error on this page into a silent blank page. Force it
// on here so the real error becomes visible instead of a blank screen.
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "header.php"; ?>
<?php
include_once __DIR__ . '/../includes/subscription_lib.php';
include_once __DIR__ . '/../includes/static_paylink_lib.php';

// ---------- CREATE ----------
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['createStaticLink'])) {
    $result = sp_create_link($conn, $userdata['id'], $userdata['user_token'], [
        'title' => $_POST['title'] ?? '',
        'description' => $_POST['description'] ?? '',
        'amount' => $_POST['amount'] ?? 0,
        'validity' => $_POST['validity'] ?? '7d',
        'paylink_type' => $_POST['paylink_type'] ?? 'normal',
        'redirect_url' => $_POST['redirect_url'] ?? '',
        'collect_name' => isset($_POST['collect_name']),
        'collect_mobile' => isset($_POST['collect_mobile']),
        'collect_email' => isset($_POST['collect_email']),
    ]);

    if ($result['ok']) {
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script><script>Swal.fire({title:"Static Paylink Created!", text:"Aap ise ab list me se copy kar sakte hain.", icon:"success", background:"#14141f", color:"#fff", confirmButtonText:"Ok"}).then(()=>{ window.location.href = "static_paylink"; });</script>';
        exit;
    } else {
        $isPlanIssue = stripos($result['message'], 'plan') !== false;
        $redirectTarget = $isPlanIssue ? 'subscription' : 'static_paylink';
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script><script>Swal.fire({title:"'.($isPlanIssue ? 'Plan Required / Limit Reached' : 'Please fix the following').'", text:"'.addslashes($result['message']).'", icon:"error", background:"#14141f", color:"#fff", confirmButtonText:"Ok"}).then(()=>{ window.location.href = "'.$redirectTarget.'"; });</script>';
    }
}

// ---------- TOGGLE / DELETE ----------
if (isset($_GET['toggle'])) {
    $lid = mysqli_real_escape_string($conn, $_GET['toggle']);
    $conn->query("UPDATE static_paylinks SET status = IF(status='Active','Disabled','Active') WHERE link_id = '$lid' AND user_token = '" . mysqli_real_escape_string($conn, $userdata['user_token']) . "'");
    echo '<script>window.location.href = "static_paylink";</script>';
    exit;
}
if (isset($_GET['delete'])) {
    $lid = mysqli_real_escape_string($conn, $_GET['delete']);
    $conn->query("DELETE FROM static_paylinks WHERE link_id = '$lid' AND user_token = '" . mysqli_real_escape_string($conn, $userdata['user_token']) . "'");
    echo '<script>window.location.href = "static_paylink";</script>';
    exit;
}

$myLinksRes = $conn->query("SELECT * FROM static_paylinks WHERE user_token = '" . mysqli_real_escape_string($conn, $userdata['user_token']) . "' ORDER BY id DESC");
$myLinks = [];
$tableMissing = $conn->errno === 1146; // "table doesn't exist"
if ($myLinksRes) { while ($r = $myLinksRes->fetch_assoc()) { $myLinks[] = $r; } }
include_once __DIR__ . '/../includes/white_label_lib.php';
$linkDisplayDomain = get_merchant_domain($conn, $userdata['id']);
$publicBase = 'https://' . $linkDisplayDomain . '/s/';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">

<style>
    :root{ --p:#6c63ff; --p2:#e040fb; --g: linear-gradient(135deg,#6c63ff,#e040fb); --success:#43e97b; --danger:#ff6584; --warning:#f5b93b; }
    *{box-sizing:border-box}
    html, body, .content-wrapper{ background:#0a0a12 !important; }
    body{ font-family:'Inter',sans-serif; color:#fff; }
    .sp-wrap{padding:20px;max-width:1300px;margin:0 auto;animation:pageIn .4s ease both}
    @keyframes pageIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}
    .sp-head{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:14px;margin-bottom:22px}
    .sp-head h1{font-size:1.55rem;font-weight:800;margin:0;color:#fff;display:flex;align-items:center;gap:10px}
    .sp-head h1 .icn{width:38px;height:38px;border-radius:12px;background:var(--g);display:inline-flex;align-items:center;justify-content:center;font-size:16px;box-shadow:0 6px 18px rgba(108,99,255,.35)}
    .sp-head p{font-size:.85rem;color:rgba(255,255,255,.45);margin:4px 0 0 48px}
    .glass-card{background:rgba(255,255,255,.04);backdrop-filter:blur(20px);border:1px solid rgba(255,255,255,.08);border-radius:20px;overflow:hidden;margin-bottom:20px}
    .card-header{padding:18px 22px;border-bottom:1px solid rgba(255,255,255,.07);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px}
    .card-header h3{font-size:1.05rem;font-weight:700;margin:0;color:#fff;display:flex;align-items:center;gap:8px}
    .card-body{padding:22px}
    .btn-primary-cta{background:var(--g);border:none;color:#fff;padding:11px 20px;border-radius:10px;font-size:.85rem;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:8px;transition:.2s;box-shadow:0 6px 18px rgba(108,99,255,.3)}
    .btn-primary-cta:hover{transform:translateY(-1px);color:#fff}
    .form-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px}
    @media(max-width:640px){.form-grid{grid-template-columns:1fr}}
    .form-label{display:block;font-size:.78rem;font-weight:600;color:rgba(255,255,255,.5);margin-bottom:7px;text-transform:uppercase;letter-spacing:.3px}
    .form-control{width:100%;background:rgba(255,255,255,.05);border:1.5px solid rgba(255,255,255,.1);border-radius:10px;padding:11px 13px;color:#fff;font-size:.88rem;outline:none;transition:.2s}
    .form-control:focus{border-color:var(--p);background:rgba(108,99,255,.08)}
    .check-row{display:flex;align-items:center;gap:10px;font-size:.85rem;color:rgba(255,255,255,.7);cursor:pointer}
    .toggle-row-inline{display:flex;gap:18px;flex-wrap:wrap;margin-top:6px}
    .sp-card{background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.07);border-radius:14px;padding:16px 18px;margin-bottom:12px}
    .sp-top{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;flex-wrap:wrap}
    .sp-title{font-weight:700;font-size:.95rem;color:#fff}
    .sp-desc{font-size:.78rem;color:rgba(255,255,255,.4);margin-top:2px}
    .sp-amount{font-weight:800;font-size:1.1rem;color:var(--success)}
    .pill{display:inline-flex;align-items:center;gap:5px;padding:3px 10px;border-radius:20px;font-size:.7rem;font-weight:700}
    .pill-success{background:rgba(67,233,123,.13);color:var(--success)}
    .pill-danger{background:rgba(255,101,132,.13);color:var(--danger)}
    .pill-warning{background:rgba(245,185,59,.13);color:var(--warning)}
    .sp-meta{display:flex;gap:16px;flex-wrap:wrap;font-size:.72rem;color:rgba(255,255,255,.4);margin-top:8px}
    .sp-link-row{display:flex;align-items:center;gap:8px;margin-top:10px;background:rgba(0,0,0,.25);border:1px solid rgba(255,255,255,.08);border-radius:8px;padding:8px 10px;flex-wrap:wrap}
    .sp-link-row code{color:#43e97b;font-size:.75rem;flex:1;word-break:break-all}
    .sp-actions{display:flex;gap:8px;margin-top:10px;flex-wrap:wrap}
    .sp-btn{border:none;border-radius:8px;padding:7px 14px;font-size:.75rem;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:6px}
    .sp-btn-copy{background:var(--g);color:#fff}
    .sp-btn-toggle{background:rgba(255,255,255,.08);color:#fff}
    .sp-btn-delete{background:rgba(255,101,132,.13);color:var(--danger)}
    .empty-state{text-align:center;padding:50px 20px;color:rgba(255,255,255,.35)}
    .empty-state i{font-size:2.2rem;margin-bottom:12px;display:block;color:rgba(255,255,255,.15)}
</style>

<div class="sp-wrap">
    <div class="sp-head">
        <div>
            <h1><span class="icn"><i class="fas fa-link"></i></span>Static Paylinks</h1>
            <p>Ek permanent link banao jo baar-baar use ho sake - poster, WhatsApp status, bio kahin bhi lagao</p>
        </div>
        <button class="btn-primary-cta" onclick="document.getElementById('createForm').style.display='block'; this.style.display='none';"><i class="fas fa-plus"></i> Create Static Paylink</button>
    </div>

    <?php if ($tableMissing): ?>
    <div class="glass-card" style="border-color:rgba(245,185,59,.4)">
        <div class="card-body" style="color:#f5b93b;font-size:.85rem">
            <i class="fas fa-triangle-exclamation"></i> Setup incomplete: <code>static_paylinks</code> table nahi mili. phpMyAdmin me <code>sql/static_paylinks_upgrade.sql</code> run karein, phir page refresh karein.
        </div>
    </div>
    <?php endif; ?>

    <div class="glass-card" id="createForm" style="display:none">
        <div class="card-header"><h3><i class="fas fa-link"></i> Create Static Paylink</h3></div>
        <div class="card-body">
            <form method="POST" action="">
                <div class="form-grid">
                    <div>
                        <label class="form-label">Title</label>
                        <input type="text" name="title" class="form-control" maxlength="60" placeholder="e.g. Course Access Fee" required>
                    </div>
                    <div>
                        <label class="form-label">Amount (₹)</label>
                        <input type="number" name="amount" class="form-control" min="1" max="100000" placeholder="e.g. 499" required>
                    </div>
                </div>
                <div class="form-grid" style="margin-top:16px">
                    <div style="grid-column:1/-1">
                        <label class="form-label">Description (optional)</label>
                        <input type="text" name="description" class="form-control" maxlength="150" placeholder="Kis liye payment hai, briefly likho">
                    </div>
                </div>
                <div class="form-grid" style="margin-top:16px">
                    <div>
                        <label class="form-label">Link Validity</label>
                        <select name="validity" class="form-control">
                            <option value="1d">1 Day</option>
                            <option value="3d">3 Days</option>
                            <option value="7d" selected>7 Days</option>
                            <option value="1m">1 Month</option>
                            <option value="6m">6 Months</option>
                            <option value="12m">12 Months (1 Year)</option>
                            <option value="24m">24 Months (2 Years)</option>
                            <option value="48m">48 Months (4 Years)</option>
                            <option value="lifetime">Lifetime (Never Expires)</option>
                        </select>
                    </div>
                    <div>
                        <label class="form-label">Paylink Type</label>
                        <select name="paylink_type" id="paylinkTypeSelect" class="form-control" onchange="document.getElementById('redirectUrlField').style.display = this.value==='redirect' ? '' : 'none';">
                            <option value="normal">Normal Payment Collect</option>
                            <option value="redirect">Redirect After Payment</option>
                        </select>
                    </div>
                </div>
                <div class="form-grid" style="margin-top:16px;display:none" id="redirectUrlField">
                    <div style="grid-column:1/-1">
                        <label class="form-label">Redirect URL</label>
                        <input type="url" name="redirect_url" class="form-control" placeholder="https://example.com/thank-you">
                    </div>
                </div>
                <div style="margin-top:16px">
                    <label class="form-label">Customer Details to Collect</label>
                    <div class="toggle-row-inline">
                        <label class="check-row"><input type="checkbox" name="collect_name" value="1"> Name</label>
                        <label class="check-row"><input type="checkbox" name="collect_mobile" value="1"> Mobile Number</label>
                        <label class="check-row"><input type="checkbox" name="collect_email" value="1"> Email Address</label>
                    </div>
                </div>
                <div style="margin-top:20px">
                    <button type="submit" name="createStaticLink" class="btn-primary-cta"><i class="fas fa-link"></i> Create Paylink</button>
                    <button type="button" class="btn-primary-cta" style="background:rgba(255,255,255,.08);box-shadow:none" onclick="document.getElementById('createForm').style.display='none'">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <div class="glass-card">
        <div class="card-header"><h3><i class="fas fa-list"></i> Your Static Paylinks</h3></div>
        <div class="card-body">
            <?php if (count($myLinks) === 0): ?>
                <div class="empty-state">
                    <i class="fas fa-link-slash"></i>
                    <h4>Koi Static Paylink Nahi Hai</h4>
                    <p>Upar "Create Static Paylink" pe click karke pehla link banayein.</p>
                </div>
            <?php else: foreach ($myLinks as $link):
                $isExpired = !empty($link['expires_at']) && strtotime($link['expires_at']) < time();
                if ($link['status'] === 'Disabled') { $pillClass = 'pill-warning'; $stLabel = 'Disabled'; }
                elseif ($isExpired) { $pillClass = 'pill-danger'; $stLabel = 'Expired'; }
                else { $pillClass = 'pill-success'; $stLabel = 'Active'; }
                $fullLink = $publicBase . $link['link_id'];
            ?>
            <div class="sp-card">
                <div class="sp-top">
                    <div>
                        <div class="sp-title"><?php echo htmlspecialchars($link['title']); ?></div>
                        <?php if (!empty($link['description'])): ?><div class="sp-desc"><?php echo htmlspecialchars($link['description']); ?></div><?php endif; ?>
                    </div>
                    <div style="text-align:right">
                        <div class="sp-amount">₹<?php echo number_format((float)$link['amount'], 2); ?></div>
                        <span class="pill <?php echo $pillClass; ?>"><?php echo $stLabel; ?></span>
                    </div>
                </div>
                <div class="sp-meta">
                    <span><i class="fas fa-clock"></i> Validity: <?php echo $link['validity'] === 'lifetime' ? 'Lifetime' : htmlspecialchars($link['expires_at']); ?></span>
                    <span><i class="fas fa-receipt"></i> Orders: <?php echo (int)$link['orders_count']; ?></span>
                    <span><i class="fas fa-calendar"></i> Created: <?php echo htmlspecialchars($link['created_at']); ?></span>
                </div>
                <div class="sp-link-row">
                    <code id="spLink-<?php echo htmlspecialchars($link['link_id']); ?>"><?php echo htmlspecialchars($fullLink); ?></code>
                    <button type="button" class="sp-btn sp-btn-copy" onclick="copySpLink('<?php echo htmlspecialchars($link['link_id']); ?>')"><i class="fas fa-copy"></i> Copy</button>
                </div>
                <div class="sp-actions">
                    <a href="static_paylink?toggle=<?php echo htmlspecialchars($link['link_id']); ?>" class="sp-btn sp-btn-toggle"><i class="fas fa-power-off"></i> <?php echo $link['status'] === 'Active' ? 'Disable' : 'Enable'; ?></a>
                    <a href="static_paylink?delete=<?php echo htmlspecialchars($link['link_id']); ?>" class="sp-btn sp-btn-delete" onclick="return confirm('Delete this static paylink? This cannot be undone.')"><i class="fas fa-trash"></i> Delete</a>
                </div>
            </div>
            <?php endforeach; endif; ?>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>
<script>
function copySpLink(id) {
    var text = document.getElementById('spLink-' + id).textContent;
    navigator.clipboard.writeText(text).then(function(){
        Swal.fire({ title: 'Copied!', icon: 'success', background: '#14141f', color: '#fff', timer: 1200, showConfirmButton: false });
    });
}
</script>
