<?php
require_once __DIR__ . '/../config/bootstrap.php';
$user = Auth::requireLogin();
$pageTitle = 'My Profile';
$activeNav = 'profile';
$showSearch = false;
require __DIR__ . '/../includes/partials/dashboard-head.php';
?>

<div class="page-header">
    <div class="page-header-left">
        <h4>My Profile</h4>
        <p>Manage your account, preferences, and personal information</p>
    </div>
</div>

<div class="content-wrapper" id="profileRoot">
    <div class="text-center py-5 text-muted">
        <div class="spinner-border me-2"></div> Loading profile…
    </div>
</div>

<style>
.profile-section {
    background: white;
    border-radius: 20px;
    margin-bottom: 16px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.04);
    overflow: hidden;
}
.profile-section-header {
    padding: 18px 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
    border-bottom: 1px solid var(--card-border);
    user-select: none;
}
.profile-section-header h5 { margin: 0; font-weight: 700; color: var(--text-primary); font-size: 16px; }
.profile-section-body { padding: 24px; display: none; }
.profile-section.open .profile-section-body { display: block; }
.profile-section.open .collapse-toggle i { transform: rotate(180deg); }
.collapse-toggle i { transition: transform 0.2s ease; color: var(--primary); }

.my-profile-card { display: flex; align-items: center; gap: 20px; flex-wrap: wrap; }
.profile-avatar-large {
    width: 88px; height: 88px; border-radius: 50%;
    background: linear-gradient(135deg,#1B7A43,#2D9B5A); color: white;
    display: flex; align-items: center; justify-content: center;
    font-size: 36px; font-weight: 700; flex-shrink: 0;
}
.profile-name { font-size: 22px; font-weight: 700; color: var(--text-primary); margin-bottom: 4px; }
.profile-email { font-size: 14px; color: var(--text-secondary); margin-bottom: 8px; }
.profile-role-badge {
    display: inline-flex; align-items: center; gap: 6px;
    background: var(--bg-light-green); color: var(--primary);
    padding: 4px 12px; border-radius: 20px;
    font-size: 12px; font-weight: 600;
}
.profile-action-btns { margin-left: auto; display: flex; gap: 8px; flex-wrap: wrap; }

.account-settings-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 12px; }
.setting-card {
    background: var(--bg-cream);
    border: 1px solid var(--card-border);
    border-radius: 16px;
    padding: 16px;
    display: flex; align-items: center; gap: 12px;
    text-decoration: none; color: var(--text-primary);
    transition: all 0.15s ease;
}
.setting-card:hover { border-color: var(--primary); transform: translateY(-2px); color: var(--primary); }
.setting-icon {
    width: 38px; height: 38px; border-radius: 12px;
    background: white; display: flex; align-items: center; justify-content: center;
    color: var(--primary); font-size: 18px;
}
.setting-label { font-weight: 600; font-size: 14px; flex: 1; }
.setting-arrow { color: var(--primary); }

.profile-edit-form { display: none; }
.profile-edit-form.open { display: block; }
.profile-form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
@media (max-width: 600px) { .profile-form-grid { grid-template-columns: 1fr; } }
.form-input {
    width: 100%; padding: 12px 16px; border-radius: 12px;
    border: 1.5px solid var(--card-border); font-size: 14px;
    background: white;
}
.form-input:focus { outline: none; border-color: var(--primary); }
.form-label { font-size: 12px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px; display: block; }
</style>

<script>
(async function () {
    const root = document.getElementById('profileRoot');
    function escapeHtml(s) {
        return String(s ?? '').replace(/[&<>"']/g, c =>
            ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c]));
    }

    try {
        const resp = await window.api('/api/profile/get');
        if (resp.status !== 'success') throw new Error(resp.message);
        const p = resp.data.profile;
        const s = resp.data.stats;

        root.innerHTML = `
            <!-- ── My Profile ── -->
            <div class="profile-section open" id="sec1">
                <div class="profile-section-header" data-toggle="sec1">
                    <h5>My Profile</h5>
                    <div class="collapse-toggle"><i class="bi bi-chevron-down"></i></div>
                </div>
                <div class="profile-section-body">
                    <div class="my-profile-card">
                        ${p.profile_pic
                            ? `<img src="${escapeHtml(p.profile_pic)}" alt="" class="profile-avatar-large" style="object-fit:cover">`
                            : `<div class="profile-avatar-large">${escapeHtml(p.initials)}</div>`}
                        <div>
                            <div class="profile-name">${escapeHtml(p.name)}</div>
                            <div class="profile-email">${escapeHtml(p.email)}</div>
                            <span class="profile-role-badge">
                                <i class="bi bi-globe"></i> Publisher · Member since ${escapeHtml(p.member_since)}
                            </span>
                        </div>
                        <div class="profile-action-btns">
                            <button class="btn-primary-custom" id="editProfileBtn" style="font-size:13px;padding:10px 18px">
                                <i class="bi bi-pencil-fill"></i> Edit Profile
                            </button>
                            <button class="btn-dark-custom" data-modal="logout" style="font-size:13px;padding:10px 18px">
                                <i class="bi bi-box-arrow-right"></i> Logout
                            </button>
                        </div>
                    </div>

                    <!-- Edit form -->
                    <div class="profile-edit-form" id="editForm" style="margin-top:24px;border-top:1px solid var(--card-border);padding-top:20px">
                        <form id="profileForm">
                            <div class="profile-form-grid">
                                <div>
                                    <label class="form-label">Full Name</label>
                                    <input type="text" name="name" id="pfName" class="form-input" value="${escapeHtml(p.name)}" required>
                                </div>
                                <div>
                                    <label class="form-label">Email (read-only)</label>
                                    <input type="email" class="form-input" value="${escapeHtml(p.email)}" readonly style="background:#f9f9f9;cursor:not-allowed">
                                </div>
                                <div>
                                    <label class="form-label">Phone</label>
                                    <input type="tel" name="phone" id="pfPhone" class="form-input" value="${escapeHtml(p.phone || '')}" placeholder="e.g. +91 9876543210">
                                </div>
                                <div>
                                    <label class="form-label">Country</label>
                                    <input type="text" name="country" id="pfCountry" class="form-input" value="${escapeHtml(p.country)}">
                                </div>
                                <div>
                                    <label class="form-label">Country Code</label>
                                    <input type="text" name="country_code" id="pfCC" class="form-input" value="${escapeHtml(p.country_code)}" placeholder="+91" maxlength="5">
                                </div>
                                <div>
                                    <label class="form-label">Company Name (optional)</label>
                                    <input type="text" name="company_name" id="pfCompany" class="form-input" value="${escapeHtml(p.company_name || '')}">
                                </div>
                            </div>
                            <div style="display:flex;gap:8px;margin-top:20px">
                                <button type="submit" class="btn-primary-custom">Save Changes</button>
                                <button type="button" class="btn-dark-custom" id="cancelEditBtn">Cancel</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- ── Stats ── -->
            <div class="profile-section open" id="sec2">
                <div class="profile-section-header" data-toggle="sec2">
                    <h5>Quick Stats</h5>
                    <div class="collapse-toggle"><i class="bi bi-chevron-down"></i></div>
                </div>
                <div class="profile-section-body">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <div class="stat-card" style="opacity:1">
                                <div class="stat-arrow"><i class="bi bi-arrow-up-right"></i></div>
                                <div class="stat-value">${s.total_campaigns}</div>
                                <div class="stat-title">Total Campaigns</div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="stat-card" style="opacity:1">
                                <div class="stat-arrow"><i class="bi bi-arrow-up-right"></i></div>
                                <div class="stat-value">${s.active_campaigns}</div>
                                <div class="stat-title">Active</div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="stat-card" style="opacity:1">
                                <div class="stat-arrow"><i class="bi bi-arrow-up-right"></i></div>
                                <div class="stat-value">${s.completed_campaigns}</div>
                                <div class="stat-title">Completed</div>
                            </div>
                        </div>
                    </div>
                    <div style="margin-top:16px;padding:16px;background:var(--bg-cream);border-radius:12px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:12px">
                        <div>
                            <div style="font-size:13px;color:var(--text-secondary)">Available Credits</div>
                            <div style="font-size:28px;font-weight:800;color:var(--primary)">₹${p.credits.toFixed(2)}</div>
                        </div>
                        <a href="/dashboard/credit-history" class="btn-dark-custom" style="padding:10px 20px;text-decoration:none">
                            <i class="bi bi-clock-history"></i> View History
                        </a>
                    </div>
                </div>
            </div>

            <!-- ── Settings ── -->
            <div class="profile-section open" id="sec3">
                <div class="profile-section-header" data-toggle="sec3">
                    <h5>Account Settings</h5>
                    <div class="collapse-toggle"><i class="bi bi-chevron-down"></i></div>
                </div>
                <div class="profile-section-body">
                    <div class="account-settings-grid">
                        <a href="/dashboard/credit-history" class="setting-card">
                            <div class="setting-icon"><i class="bi bi-clock-history"></i></div>
                            <div class="setting-label">Credit History</div>
                            <div class="setting-arrow"><i class="bi bi-arrow-right"></i></div>
                        </a>
                        <a href="/dashboard/campaigns" class="setting-card">
                            <div class="setting-icon"><i class="bi bi-collection-fill"></i></div>
                            <div class="setting-label">Campaign History</div>
                            <div class="setting-arrow"><i class="bi bi-arrow-right"></i></div>
                        </a>
                        <a href="/forgot-password" class="setting-card">
                            <div class="setting-icon"><i class="bi bi-key-fill"></i></div>
                            <div class="setting-label">Change Password</div>
                            <div class="setting-arrow"><i class="bi bi-arrow-right"></i></div>
                        </a>
                        <a href="mailto:support@droidtester.com" class="setting-card">
                            <div class="setting-icon"><i class="bi bi-headset"></i></div>
                            <div class="setting-label">Contact Support</div>
                            <div class="setting-arrow"><i class="bi bi-arrow-right"></i></div>
                        </a>
                        <a href="/privacy-policy" class="setting-card">
                            <div class="setting-icon"><i class="bi bi-shield-check"></i></div>
                            <div class="setting-label">Privacy Policy</div>
                            <div class="setting-arrow"><i class="bi bi-arrow-right"></i></div>
                        </a>
                        <a href="/terms-condition" class="setting-card">
                            <div class="setting-icon"><i class="bi bi-file-text-fill"></i></div>
                            <div class="setting-label">Terms &amp; Condition</div>
                            <div class="setting-arrow"><i class="bi bi-arrow-right"></i></div>
                        </a>
                    </div>

                    <div style="margin-top:24px;padding-top:20px;border-top:1px solid var(--card-border)">
                        <h6 style="color:var(--danger);font-weight:700">Danger Zone</h6>
                        <p style="font-size:13px;color:var(--text-secondary);margin-bottom:12px">
                            Deleting your account is permanent. All your data will be hidden.
                        </p>
                        <button class="btn-primary-custom" data-modal="deleteAccount" style="background:var(--danger);font-size:13px;padding:10px 18px">
                            <i class="bi bi-trash-fill"></i> Delete Account
                        </button>
                    </div>
                </div>
            </div>
        `;

        // ── Wire interactions ──
        document.querySelectorAll('.profile-section-header').forEach(h => {
            h.addEventListener('click', function () {
                this.parentElement.classList.toggle('open');
            });
        });

        document.getElementById('editProfileBtn').addEventListener('click', () => {
            document.getElementById('editForm').classList.add('open');
        });
        document.getElementById('cancelEditBtn').addEventListener('click', () => {
            document.getElementById('editForm').classList.remove('open');
        });

        document.getElementById('profileForm').addEventListener('submit', async function (e) {
            e.preventDefault();
            const btn = this.querySelector('button[type="submit"]');
            const orig = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Saving…';
            try {
                const fd = new FormData(this);
                const res = await window.api('/api/profile/update', { method: 'POST', body: fd });
                if (res.status === 'success') {
                    window.Toast.fire({ icon: 'success', title: res.message });
                    setTimeout(() => location.reload(), 800);
                } else {
                    window.Toast.fire({ icon: 'error', title: res.message });
                    btn.disabled = false;
                    btn.innerHTML = orig;
                }
            } catch {
                window.Toast.fire({ icon: 'error', title: 'Network error.' });
                btn.disabled = false;
                btn.innerHTML = orig;
            }
        });

        // Re-bind modal triggers since we injected new buttons
        document.querySelectorAll('[data-modal]').forEach(btn => {
            btn.addEventListener('click', function (e) {
                e.preventDefault();
                const target = this.dataset.modal;
                const id = target === 'logout' ? 'logoutModal'
                         : target === 'deleteAccount' ? 'deleteAccountModal' : null;
                if (id) {
                    const el = document.getElementById(id);
                    if (el && typeof bootstrap !== 'undefined') new bootstrap.Modal(el).show();
                }
            });
        });
    } catch (err) {
        root.innerHTML = `<div class="text-center py-5 text-muted">Failed to load profile. ${escapeHtml(err.message || '')}</div>`;
    }
})();
</script>

<?php require __DIR__ . '/../includes/partials/dashboard-foot.php'; ?>
