<?= $this->extend('layouts/panel') ?>
<?= $this->section('sidebar') ?>
<?= $this->include('panel/_sidebar') ?>
<?= $this->endSection() ?>

<?= $this->section('content') ?>
<h5 class="mb-3">Company Profile</h5>

<div class="li-card mb-3">
    <div class="li-card-body">
        <h6 class="mb-3">Logo &amp; Cover Image</h6>
        <div class="row g-3">
            <div class="col-md-6">
                <label class="form-label small text-muted">Company Logo</label>
                <div class="d-flex align-items-center gap-3 mb-2">
                    <img id="logoPreview" src="" class="rounded d-none" style="width:64px;height:64px;object-fit:cover;">
                    <span id="logoInitial" class="job-card-logo" style="width:64px;height:64px;border-radius:8px;background:var(--li-blue);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:22px;"></span>
                </div>
                <input type="file" id="logoFile" accept=".jpg,.jpeg,.png,.webp" class="form-control form-control-sm mb-2">
                <button class="btn btn-li-primary btn-sm" onclick="uploadLogo()">Upload Logo</button>
            </div>
            <div class="col-md-6">
                <label class="form-label small text-muted">Cover Image</label>
                <div class="mb-2">
                    <img id="coverPreview" src="" class="rounded d-none w-100" style="height:64px;object-fit:cover;">
                    <div id="coverPlaceholder" class="rounded bg-light d-flex align-items-center justify-content-center text-muted small" style="height:64px;">No cover image</div>
                </div>
                <input type="file" id="coverFile" accept=".jpg,.jpeg,.png,.webp" class="form-control form-control-sm mb-2">
                <button class="btn btn-li-primary btn-sm" onclick="uploadCover()">Upload Cover</button>
            </div>
        </div>
    </div>
</div>

<div class="li-card mb-3">
    <div class="li-card-body">
        <h6 class="mb-2">Public Profile URL</h6>
        <div class="d-flex align-items-center gap-2 mb-2">
            <span class="text-muted small"><?= rtrim(base_url(), '/') ?>/profile/</span>
            <input type="text" id="usernameInput" class="form-control form-control-sm" style="max-width:220px;">
            <button class="btn btn-li-outline btn-sm" onclick="saveUsername()">Update</button>
            <a id="viewProfileLink" href="#" target="_blank" class="btn btn-li-primary btn-sm">View Public Profile</a>
        </div>
        <div id="usernameStatus" class="small text-muted"></div>
    </div>
</div>

<div class="li-card">
    <div class="li-card-body">
        <form id="companyForm">
            <div class="row g-3">
                <div class="col-12">
                    <label class="form-label">Company Name</label>
                    <input type="text" class="form-control" name="company_name" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Website</label>
                    <input type="url" class="form-control" name="website">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Industry</label>
                    <input type="text" class="form-control" name="industry">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Company Email</label>
                    <input type="email" class="form-control" name="email">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Phone</label>
                    <input type="text" class="form-control" name="phone">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Company Size</label>
                    <input type="text" class="form-control" name="company_size" placeholder="e.g. 11-50">
                </div>
                <div class="col-12">
                    <label class="form-label">Description</label>
                    <textarea class="form-control" name="description" rows="4"></textarea>
                </div>
                <div class="col-12">
                    <label class="form-label">Services Offered</label>
                    <textarea class="form-control" name="services" rows="3" placeholder="e.g. IT Staffing, Executive Search, Recruitment Process Outsourcing"></textarea>
                </div>
                <div class="col-md-4">
                    <label class="form-label">LinkedIn URL</label>
                    <input type="url" class="form-control" name="social_linkedin">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Facebook URL</label>
                    <input type="url" class="form-control" name="social_facebook">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Twitter/X URL</label>
                    <input type="url" class="form-control" name="social_twitter">
                </div>
                <div class="col-12">
                    <label class="form-label">Address</label>
                    <textarea class="form-control" name="address" rows="2"></textarea>
                </div>
            </div>
            <button type="button" class="btn btn-li-primary mt-3" onclick="saveCompany()">Save Changes</button>
        </form>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
const BASE = "<?= rtrim(base_url(), '/') ?>";
async function loadUsername() {
    try {
        const res = await apiFetch('/account/username/status');
        document.getElementById('usernameInput').value = res.data.current_username || '';
        document.getElementById('viewProfileLink').href = "<?= rtrim(base_url(), '/') ?>/profile/" + (res.data.current_username || '');
        const lim = res.data.change_limit;
        document.getElementById('usernameStatus').textContent = `${lim.remaining} of ${lim.limit} change(s) remaining in the next ${lim.period_days} days.`;
    } catch (e) { /* non-fatal */ }
}

async function saveUsername() {
    const username = document.getElementById('usernameInput').value.trim();
    if (!username) { showToast('Enter a username.', true); return; }
    try {
        await apiFetch('/account/username', { method: 'PUT', body: JSON.stringify({ username }) });
        showToast('Username updated.');
        loadUsername();
    } catch (e) { showToast(e.message, true); }
}

async function loadCompany() {
    try {
        const res = await apiFetch('/agencies/me');
        const a = res.data.agency;
        const form = document.getElementById('companyForm');
        form.company_name.value = a.company_name || '';
        form.website.value = a.website || '';
        form.industry.value = a.industry || '';
        form.email.value = a.email || '';
        form.phone.value = a.phone || '';
        form.company_size.value = a.company_size || '';
        form.description.value = a.description || '';
        form.services.value = a.services || '';
        const social = a.social_links || {};
        form.social_linkedin.value = social.linkedin || '';
        form.social_facebook.value = social.facebook || '';
        form.social_twitter.value = social.twitter || '';
        form.address.value = a.address || '';

        renderLogo(a.logo_path ? `${BASE}/${a.logo_path}` : null, a.company_name);
        renderCover(a.cover_image_path ? `${BASE}/${a.cover_image_path}` : null);
    } catch (e) { showToast(e.message, true); }
}

function renderLogo(url, companyName) {
    const img = document.getElementById('logoPreview');
    const initial = document.getElementById('logoInitial');
    if (url) {
        img.src = url + '?t=' + Date.now();
        img.classList.remove('d-none');
        initial.classList.add('d-none');
    } else {
        img.classList.add('d-none');
        initial.classList.remove('d-none');
        initial.textContent = (companyName || 'C')[0].toUpperCase();
    }
}

function renderCover(url) {
    const img = document.getElementById('coverPreview');
    const placeholder = document.getElementById('coverPlaceholder');
    if (url) {
        img.src = url + '?t=' + Date.now();
        img.classList.remove('d-none');
        placeholder.classList.add('d-none');
    } else {
        img.classList.add('d-none');
        placeholder.classList.remove('d-none');
    }
}

async function uploadLogo() {
    const fileInput = document.getElementById('logoFile');
    if (!fileInput.files.length) { showToast('Choose a logo file first.', true); return; }
    const fd = new FormData();
    fd.append('image', fileInput.files[0]);
    try {
        const res = await fetch(`${API_BASE}/agencies/me/logo`, { method: 'POST', body: fd, credentials: 'include' });
        const json = await res.json();
        if (!json.success) throw new Error(json.errors?.[0]?.message || 'Upload failed.');
        showToast('Logo updated.');
        renderLogo(json.data.logo_path, document.getElementById('companyForm').company_name.value);
    } catch (e) { showToast(e.message, true); }
}

async function uploadCover() {
    const fileInput = document.getElementById('coverFile');
    if (!fileInput.files.length) { showToast('Choose a cover image first.', true); return; }
    const fd = new FormData();
    fd.append('image', fileInput.files[0]);
    try {
        const res = await fetch(`${API_BASE}/agencies/me/cover`, { method: 'POST', body: fd, credentials: 'include' });
        const json = await res.json();
        if (!json.success) throw new Error(json.errors?.[0]?.message || 'Upload failed.');
        showToast('Cover image updated.');
        renderCover(json.data.cover_image_path);
    } catch (e) { showToast(e.message, true); }
}

async function saveCompany() {
    const form = document.getElementById('companyForm');
    const fd = new FormData(form);
    const payload = Object.fromEntries(fd.entries());

    payload.social_links = {
        linkedin: payload.social_linkedin || '',
        facebook: payload.social_facebook || '',
        twitter: payload.social_twitter || '',
    };
    delete payload.social_linkedin;
    delete payload.social_facebook;
    delete payload.social_twitter;

    try {
        await apiFetch('/agencies/me', { method: 'PUT', body: JSON.stringify(payload) });
        showToast('Company profile updated.');
    } catch (e) { showToast(e.message, true); }
}

loadCompany();
loadUsername();
</script>
<?= $this->endSection() ?>
