<?php include "header.php"; ?>
<?php
// NOTE: header.php already starts the session, loads config.php ($conn),
// verifies $_SESSION['username'] is set and redirects to index if not,
// and fetches the logged-in user's row into $userdata. We reuse all of
// that instead of re-querying with a separate (and unused) user_id session
// key or a non-existent database_connection.php include.

$success_message = $error_message = '';
$user_id = (int)($userdata['id'] ?? 0);

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update'])) {
    $is_otp          = filter_input(INPUT_POST, 'is_otp', FILTER_UNSAFE_RAW) ?: 'NO';
    $whatsapp_alert  = filter_input(INPUT_POST, 'whatsapp_alert', FILTER_UNSAFE_RAW) ?: 'NO';
    $email_alert     = filter_input(INPUT_POST, 'email_alert', FILTER_UNSAFE_RAW) ?: 'NO';
    $mobile          = filter_input(INPUT_POST, 'mobile', FILTER_UNSAFE_RAW);

    if (!preg_match('/^[0-9]{10}$/', $mobile)) {
        $error_message = "Please enter a valid 10-digit mobile number";
    } else {
        $query = "UPDATE users SET is_otp = ?, whatsapp_alert = ?, email_alert = ?, mobile = ? WHERE id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("ssssi", $is_otp, $whatsapp_alert, $email_alert, $mobile, $user_id);

        if ($stmt->execute()) {
            $success_message = "Profile updated successfully!";
            $_SESSION['username'] = $mobile; // header.php looks up the user by this session key
            $userdata['mobile'] = $mobile;
            $userdata['is_otp'] = $is_otp;
            $userdata['whatsapp_alert'] = $whatsapp_alert;
            $userdata['email_alert'] = $email_alert;
        } else {
            $error_message = "Error updating profile";
        }
        $stmt->close();
    }
}

// ---- Real account stats (replacing the old rand()-based placeholders) ----
$totalTxn = 0;
$txnRes = $conn->query("SELECT COUNT(id) as cnt FROM orders WHERE user_id='$user_id'");
if ($txnRes) { $totalTxn = (int)($txnRes->fetch_assoc()['cnt'] ?? 0); }

$expiry = $userdata['expiry'] ?? null;
$accountStatus = 'No Expiry';
$statusClass = 'st-active';
if ($expiry) {
    $daysLeft = (strtotime($expiry) - strtotime(date('Y-m-d'))) / 86400;
    if ($daysLeft < 0) { $accountStatus = 'Expired'; $statusClass = 'st-expired'; }
    elseif ($daysLeft <= 7) { $accountStatus = 'Expiring Soon'; $statusClass = 'st-soon'; }
    else { $accountStatus = 'Active'; $statusClass = 'st-active'; }
}
?>

<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&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">

<style>
    :root{
        --p:#6c63ff; --p2:#e040fb;
        --g: linear-gradient(135deg,#6c63ff,#e040fb);
        --success:#43e97b; --danger:#ff6584; --warning:#f5b93b; --info:#3ea6ff;
    }
    *{box-sizing:border-box}
    html, body, .content-wrapper{ background:#0a0a12 !important; }
    body{ font-family:'Inter',sans-serif; color:#fff; }
    .content-wrapper{min-height:100vh}

    .pf-wrap{padding:20px;max-width:1200px;margin:0 auto;animation:pageIn .4s ease both}
    @keyframes pageIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}

    .pf-head{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:14px;margin-bottom:22px}
    .pf-head h1{font-size:1.55rem;font-weight:800;margin:0;color:#fff;display:flex;align-items:center;gap:10px}
    .pf-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);
    }
    .btn-ghost{
        background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);color:#fff;
        padding:9px 16px;border-radius:10px;font-size:.82rem;font-weight:600;cursor:pointer;
        display:inline-flex;align-items:center;gap:7px;transition:.2s;text-decoration:none;
    }
    .btn-ghost:hover{background:rgba(255,255,255,.1);border-color:rgba(255,255,255,.2);color:#fff;transform:translateY(-1px)}
    .btn-primary-cta{
        background:var(--g);border:none;color:#fff;padding:11px 22px;border-radius:10px;
        font-size:.85rem;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:8px;
        transition:.2s;box-shadow:0 6px 18px rgba(108,99,255,.3);
    }
    .btn-primary-cta:hover{transform:translateY(-1px);box-shadow:0 10px 24px rgba(108,99,255,.45);color:#fff}

    .pf-grid{display:grid;grid-template-columns:300px 1fr;gap:20px}
    @media(max-width:900px){.pf-grid{grid-template-columns:1fr}}

    .glass-card{
        background:rgba(255,255,255,.04);backdrop-filter:blur(20px);
        border:1px solid rgba(255,255,255,.08);border-radius:20px;padding:26px;
    }
    .pf-avatar{
        width:96px;height:96px;border-radius:24px;background:var(--g);margin:0 auto 16px;
        display:flex;align-items:center;justify-content:center;color:#fff;font-size:2.4rem;font-weight:800;
        box-shadow:0 12px 30px rgba(108,99,255,.35);
    }
    .pf-name{text-align:center;font-size:1.2rem;font-weight:800;color:#fff;margin-bottom:4px}
    .pf-company{text-align:center;color:rgba(255,255,255,.45);font-size:.85rem;margin-bottom:18px}

    .status-pill{
        display:flex;align-items:center;justify-content:center;gap:6px;padding:7px 14px;border-radius:20px;
        font-size:.78rem;font-weight:700;margin:0 auto 20px;width:fit-content;
    }
    .st-active{background:rgba(67,233,123,.13);color:var(--success)}
    .st-soon{background:rgba(245,185,59,.15);color:var(--warning)}
    .st-expired{background:rgba(255,101,132,.13);color:var(--danger)}

    .pf-stats{display:flex;justify-content:space-between;padding-top:18px;border-top:1px solid rgba(255,255,255,.08)}
    .stat-item{text-align:center;flex:1}
    .stat-item .val{font-size:1.15rem;font-weight:800;color:#fff}
    .stat-item .lbl{font-size:.7rem;color:rgba(255,255,255,.4);margin-top:2px}

    .section-title{
        font-size:1rem;font-weight:700;margin:0 0 16px;color:#fff;display:flex;align-items:center;gap:9px;
        padding-bottom:12px;border-bottom:1px solid rgba(255,255,255,.07);
    }
    .section-title i{color:var(--p)}
    .pf-section{margin-bottom:26px}
    .pf-section:last-of-type{margin-bottom:0}

    .form-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:16px}
    @media(max-width:600px){.form-grid{grid-template-columns:1fr}}
    .form-group{margin-bottom:2px}
    .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}
    /* The site's own theme CSS (loaded earlier, in <head>) has some rules
       aimed at .card .form-control with !important that don't match our
       .glass-card wrapper — and on some pages a plain Bootstrap default
       (white background) was winning. Pinning every state here with
       !important + a scoped selector guarantees this page is never at the
       mercy of upstream CSS load order again. */
    .pf-wrap .form-control,
    .pf-wrap input.form-control,
    .pf-wrap input.form-control[readonly],
    .pf-wrap input.form-control[disabled]{
        width:100% !important;background:rgba(255,255,255,.05) !important;
        border:1.5px solid rgba(255,255,255,.1) !important;border-radius:10px !important;
        padding:11px 13px !important;color:#fff !important;font-size:.88rem !important;
        outline:none !important;transition:.2s;font-family:'Inter',sans-serif !important;
        -webkit-text-fill-color:#fff !important;opacity:1 !important;box-shadow:none !important;
    }
    .pf-wrap .form-control:focus{
        border-color:var(--p) !important;background:rgba(108,99,255,.08) !important;
        box-shadow:0 0 0 3px rgba(108,99,255,.15) !important;
    }
    .pf-wrap .form-control[readonly]{color:rgba(255,255,255,.45) !important;cursor:not-allowed}
    .pf-wrap .form-control::placeholder{color:rgba(255,255,255,.3) !important}
    /* Chrome/Android autofill paints its own light-yellow/white background
       via an internal UA layer that ignores background-color entirely —
       this is the only combination that actually beats it. */
    .pf-wrap input:-webkit-autofill,
    .pf-wrap input:-webkit-autofill:hover,
    .pf-wrap input:-webkit-autofill:focus{
        -webkit-text-fill-color:#fff !important;
        -webkit-box-shadow:0 0 0 1000px #14141f inset !important;
        box-shadow:0 0 0 1000px #14141f inset !important;
        caret-color:#fff;
    }
    .iw{position:relative}
    .iw i{position:absolute;left:13px;top:50%;transform:translateY(-50%);color:rgba(255,255,255,.3);font-size:13px}
    .iw .form-control{padding-left:36px}

    .toggle-row{
        display:flex;align-items:center;justify-content:space-between;gap:14px;padding:14px 16px;
        background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.07);border-radius:12px;margin-bottom:10px;
    }
    .toggle-row:last-child{margin-bottom:0}
    .toggle-info .t-name{font-size:.86rem;font-weight:700;color:#fff}
    .toggle-info .t-hint{font-size:.74rem;color:rgba(255,255,255,.4);margin-top:2px}
    .toggle-switch{position:relative;display:inline-block;width:46px;height:25px;flex-shrink:0}
    .toggle-switch input{opacity:0;width:0;height:0}
    .toggle-slider{position:absolute;inset:0;background:rgba(255,255,255,.12);transition:.3s;border-radius:34px}
    .toggle-slider:before{position:absolute;content:"";height:19px;width:19px;left:3px;bottom:3px;background:#fff;transition:.3s;border-radius:50%}
    input:checked + .toggle-slider{background:var(--g)}
    input:checked + .toggle-slider:before{transform:translateX(21px)}

    .form-actions{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;margin-top:24px;padding-top:20px;border-top:1px solid rgba(255,255,255,.07)}
    .last-updated{font-size:.76rem;color:rgba(255,255,255,.35)}
</style>

<div class="pf-wrap">
    <div class="pf-head">
        <h1><span class="icn"><i class="fas fa-user-gear"></i></span>My Profile</h1>
        <a href="dashboard" class="btn-ghost"><i class="fas fa-arrow-left"></i> Back to Dashboard</a>
    </div>

    <div class="pf-grid">
        <!-- Sidebar summary -->
        <div class="glass-card">
            <div class="pf-avatar"><?php echo strtoupper(substr($userdata['name'] ?? '?', 0, 1)); ?></div>
            <div class="pf-name"><?php echo htmlspecialchars($userdata['name'] ?? ''); ?></div>
            <div class="pf-company"><?php echo htmlspecialchars($userdata['company'] ?? ''); ?></div>

            <div class="status-pill <?php echo $statusClass; ?>">
                <i class="fas fa-circle" style="font-size:8px"></i> <?php echo $accountStatus; ?>
            </div>

            <div class="pf-stats">
                <div class="stat-item">
                    <div class="val"><?php echo number_format($totalTxn); ?></div>
                    <div class="lbl">Transactions</div>
                </div>
                <div class="stat-item">
                    <div class="val"><?php echo htmlspecialchars($userdata['role'] ?? '-'); ?></div>
                    <div class="lbl">Role</div>
                </div>
                <div class="stat-item">
                    <div class="val"><?php echo $expiry ? date('d M Y', strtotime($expiry)) : '—'; ?></div>
                    <div class="lbl">Plan Expiry</div>
                </div>
            </div>
        </div>

        <!-- Main form -->
        <div class="glass-card">
            <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">

                <div class="pf-section">
                    <div class="section-title"><i class="fas fa-user"></i> Personal Information</div>
                    <div class="form-grid">
                        <div class="form-group">
                            <label class="form-label">Full Name</label>
                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($userdata['name'] ?? ''); ?>" readonly>
                        </div>
                        <div class="form-group">
                            <label for="mobile" class="form-label">Mobile Number *</label>
                            <div class="iw">
                                <i class="fas fa-phone"></i>
                                <input type="text" name="mobile" id="mobile" class="form-control"
                                       value="<?php echo htmlspecialchars($userdata['mobile'] ?? ''); ?>" required
                                       pattern="[0-9]{10}" title="10 digit mobile number">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Email Address</label>
                            <div class="iw">
                                <i class="fas fa-envelope"></i>
                                <input type="email" class="form-control" value="<?php echo htmlspecialchars($userdata['email'] ?? ''); ?>" readonly>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Company Name</label>
                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($userdata['company'] ?? ''); ?>" readonly>
                        </div>
                    </div>
                </div>

                <div class="pf-section">
                    <div class="section-title"><i class="fas fa-id-card"></i> Account Details</div>
                    <div class="form-grid">
                        <div class="form-group">
                            <label class="form-label">Instance ID</label>
                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($userdata['instance_id'] ?? ''); ?>" readonly>
                        </div>
                        <div class="form-group">
                            <label class="form-label">PAN Number</label>
                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($userdata['pan'] ?? ''); ?>" readonly>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Aadhaar Number</label>
                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($userdata['aadhaar'] ?? ''); ?>" readonly>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Location</label>
                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($userdata['location'] ?? ''); ?>" readonly>
                        </div>
                    </div>
                </div>

                <div class="pf-section">
                    <div class="section-title"><i class="fas fa-bell"></i> Notification Settings</div>

                    <div class="toggle-row">
                        <div class="toggle-info">
                            <div class="t-name">OTP Verification</div>
                            <div class="t-hint">Require OTP for important actions</div>
                        </div>
                        <label class="toggle-switch">
                            <input type="checkbox" name="is_otp" value="YES" <?php echo (($userdata['is_otp'] ?? '') === 'YES') ? 'checked' : ''; ?>>
                            <span class="toggle-slider"></span>
                        </label>
                    </div>

                    <div class="toggle-row">
                        <div class="toggle-info">
                            <div class="t-name">WhatsApp Alerts</div>
                            <div class="t-hint">Receive notifications on WhatsApp</div>
                        </div>
                        <label class="toggle-switch">
                            <input type="checkbox" name="whatsapp_alert" value="YES" <?php echo (($userdata['whatsapp_alert'] ?? '') === 'YES') ? 'checked' : ''; ?>>
                            <span class="toggle-slider"></span>
                        </label>
                    </div>

                    <div class="toggle-row">
                        <div class="toggle-info">
                            <div class="t-name">Email Alerts</div>
                            <div class="t-hint">Receive notifications via email</div>
                        </div>
                        <label class="toggle-switch">
                            <input type="checkbox" name="email_alert" value="YES" <?php echo (($userdata['email_alert'] ?? '') === 'YES') ? 'checked' : ''; ?>>
                            <span class="toggle-slider"></span>
                        </label>
                    </div>
                </div>

                <div class="form-actions">
                    <div class="last-updated">
                        <?php if (!empty($userdata['updated_at'])): ?>
                            Last updated: <?php echo date('d M Y, h:i A', strtotime($userdata['updated_at'])); ?>
                        <?php endif; ?>
                    </div>
                    <button type="submit" name="update" class="btn-primary-cta"><i class="fas fa-save"></i> Save Changes</button>
                </div>
            </form>
        </div>
    </div>

    <div class="dashboard-card" style="margin-top:20px">
        <div class="card-body" style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:12px">
            <div>
                <div style="font-weight:700;color:#fff">Logout</div>
                <div style="font-size:.82rem;color:rgba(255,255,255,.45)">Aap jab tak khud logout nahi karte, tab tak logged in rahenge.</div>
            </div>
            <a href="logout" onclick="return confirm('Kya aap sach me logout karna chahte hain?')" class="btn-primary-cta" style="background:#e04e4e;text-decoration:none"><i class="fas fa-right-from-bracket"></i> Logout</a>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var mobileInput = document.getElementById('mobile');
    if (mobileInput) {
        mobileInput.addEventListener('input', function() {
            this.value = this.value.replace(/[^0-9]/g, '').slice(0, 10);
        });
    }

    <?php if ($success_message): ?>
    Swal.fire({
        title: 'Success!', text: '<?php echo addslashes($success_message); ?>', icon: 'success',
        confirmButtonText: 'OK', timer: 3000, background: '#14141f', color: '#fff'
    });
    <?php endif; ?>

    <?php if ($error_message): ?>
    Swal.fire({
        title: 'Error!', text: '<?php echo addslashes($error_message); ?>', icon: 'error',
        confirmButtonText: 'OK', background: '#14141f', color: '#fff'
    });
    <?php endif; ?>
});
</script>
</body>
</html>
