<?php
$page_title = 'Growth Partner';
require __DIR__ . '/_guard.php';

$action = $_GET['action'] ?? 'edit';
$id     = (int)($_GET['id'] ?? 0);
$errors = [];

// ── Ensure table exists ───────────────────────────────────────────────────────
$table_ok = false;
try { db_value('SELECT 1 FROM growth_partners LIMIT 1'); $table_ok = true; } catch (Throwable $e) {}

if (!$table_ok) {
    echo '<section class="section"><div class="container"><div class="alert alert-error">';
    echo 'Table <code>growth_partners</code> not found. Run <code>db/growth-partners.sql</code> first.';
    echo '</div></div></section>';
    require __DIR__ . '/_footer.php'; exit;
}

// ── Load all published listings for the picker ────────────────────────────────
$listings = db_all(
    'SELECT id, name, logo_path, website, tier FROM listings WHERE published = 1 ORDER BY name'
);

// ── Load existing record (edit mode) ─────────────────────────────────────────
$partner = [
    'id' => 0, 'listing_id' => null, 'name' => '',
    'logo_path' => null, 'website_url' => '', 'sort_order' => 0, 'active' => 1,
];
if ($id) {
    $row = db_row('SELECT * FROM growth_partners WHERE id=:id', ['id' => $id]);
    if (!$row) { header('Location: growth-partners.php'); exit; }
    $partner = $row;
    $action  = 'edit';
}
$is_new = ($action === 'add');

// ── Handle POST ───────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();

    $listing_id  = (int)($_POST['listing_id'] ?? 0) ?: null;
    $name        = trim($_POST['name']        ?? '');
    $website_url = trim($_POST['website_url'] ?? '');
    $sort_order  = (int)($_POST['sort_order'] ?? 0);
    $active      = isset($_POST['active']) ? 1 : 0;
    $logo_path   = $partner['logo_path'];

    // If a listing is chosen and name left blank, auto-use listing name
    if ($listing_id && $name === '') {
        foreach ($listings as $l) {
            if ((int)$l['id'] === $listing_id) { $name = $l['name']; break; }
        }
    }

    if ($name === '') $errors[] = 'Partner name is required.';

    // Logo upload (custom override)
    if (!empty($_FILES['logo']['name'])) {
        $file    = $_FILES['logo'];
        $allowed = ['image/jpeg','image/png','image/webp','image/gif','image/svg+xml'];
        $finfo   = new finfo(FILEINFO_MIME_TYPE);
        $mime    = $finfo->file($file['tmp_name']);
        if (!in_array($mime, $allowed, true)) {
            $errors[] = 'Logo must be JPG, PNG, WebP, GIF or SVG.';
        } elseif ($file['size'] > 2 * 1024 * 1024) {
            $errors[] = 'Logo must be under 2 MB.';
        } elseif ($file['error'] !== UPLOAD_ERR_OK) {
            $errors[] = 'Upload failed (error ' . $file['error'] . ').';
        } else {
            $dir = __DIR__ . '/../assets/uploads/partners/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $ext       = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $name_safe = 'partner-' . ($id ?: 'new') . '-' . substr(md5(uniqid('', true)), 0, 6) . '.' . $ext;
            if (move_uploaded_file($file['tmp_name'], $dir . $name_safe)) {
                if ($logo_path) {
                    $old = __DIR__ . '/../' . ltrim($logo_path, '/');
                    if (file_exists($old)) @unlink($old);
                }
                $logo_path = 'assets/uploads/partners/' . $name_safe;
            } else {
                $errors[] = 'Could not save logo. Check folder permissions on assets/uploads/partners/.';
            }
        }
    }

    // Remove custom logo
    if (!empty($_POST['remove_logo']) && $logo_path) {
        $old = __DIR__ . '/../' . ltrim($logo_path, '/');
        if (file_exists($old)) @unlink($old);
        $logo_path = null;
    }

    if (empty($errors)) {
        // Detect whether listing_id column exists (ALTER may not have been run yet)
        $has_listing_col = false;
        try { db_value('SELECT listing_id FROM growth_partners LIMIT 1'); $has_listing_col = true; }
        catch (Throwable $e) {}

        try {
            if ($is_new) {
                if ($has_listing_col) {
                    db_exec(
                        'INSERT INTO growth_partners (listing_id, name, logo_path, website_url, sort_order, active)
                         VALUES (:lid, :n, :l, :w, :s, :a)',
                        ['lid'=>$listing_id,'n'=>$name,'l'=>$logo_path,'w'=>$website_url?:null,'s'=>$sort_order,'a'=>$active]
                    );
                } else {
                    db_exec(
                        'INSERT INTO growth_partners (name, logo_path, website_url, sort_order, active)
                         VALUES (:n, :l, :w, :s, :a)',
                        ['n'=>$name,'l'=>$logo_path,'w'=>$website_url?:null,'s'=>$sort_order,'a'=>$active]
                    );
                }
                $new_id = (int)db_value('SELECT LAST_INSERT_ID()');
                if ($logo_path && str_contains($logo_path, '-new-')) {
                    $new_path = str_replace('partner-new-', 'partner-'.$new_id.'-', $logo_path);
                    $old_full = __DIR__ . '/../' . $logo_path;
                    $new_full = __DIR__ . '/../' . $new_path;
                    if (file_exists($old_full)) {
                        rename($old_full, $new_full);
                        db_exec('UPDATE growth_partners SET logo_path=:l WHERE id=:id',
                                ['l'=>$new_path,'id'=>$new_id]);
                    }
                }
            } else {
                if ($has_listing_col) {
                    db_exec(
                        'UPDATE growth_partners
                            SET listing_id=:lid, name=:n, logo_path=:l, website_url=:w, sort_order=:s, active=:a
                          WHERE id=:id',
                        ['lid'=>$listing_id,'n'=>$name,'l'=>$logo_path,'w'=>$website_url?:null,'s'=>$sort_order,'a'=>$active,'id'=>$id]
                    );
                } else {
                    db_exec(
                        'UPDATE growth_partners
                            SET name=:n, logo_path=:l, website_url=:w, sort_order=:s, active=:a
                          WHERE id=:id',
                        ['n'=>$name,'l'=>$logo_path,'w'=>$website_url?:null,'s'=>$sort_order,'a'=>$active,'id'=>$id]
                    );
                }
            }
        } catch (Throwable $e) {
            $errors[] = 'Database error: ' . $e->getMessage();
        }

        if (empty($errors)) {
            header('Location: growth-partners.php?msg=saved');
            exit;
        }
    }

    // Re-populate for re-render
    $partner = array_merge($partner, [
        'listing_id' => $listing_id, 'name' => $name, 'logo_path' => $logo_path,
        'website_url' => $website_url, 'sort_order' => $sort_order, 'active' => $active,
    ]);
}

// Build a JS-safe map of listing data for auto-fill
$listing_map = [];
foreach ($listings as $l) {
    $listing_map[(int)$l['id']] = [
        'name'      => $l['name'],
        'logo_path' => $l['logo_path'] ?? '',
        'website'   => $l['website']   ?? '',
        'tier'      => $l['tier'],
    ];
}
?>

<style>
.upload-zone{border:2px dashed var(--line);border-radius:var(--radius);padding:1.5rem;text-align:center;cursor:pointer;position:relative;transition:border-color .2s,background .2s;}
.upload-zone:hover,.upload-zone.dragover{border-color:var(--brand-primary);background:rgba(122,157,71,.05);}
.upload-zone input{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%;}
.logo-preview-wrap{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:1rem;margin-bottom:.75rem;text-align:center;}
.logo-preview-wrap img{max-width:160px;max-height:100px;object-fit:contain;margin:0 auto;display:block;}
.listing-pill{display:inline-flex;align-items:center;gap:.4rem;background:var(--surface-alt);border:1px solid var(--line);border-radius:999px;padding:.25rem .75rem;font-size:.8rem;margin-top:.4rem;}
.listing-pill .tier-dot{width:8px;height:8px;border-radius:50%;display:inline-block;}
.search-box{width:100%;padding:.45rem .75rem;border:1px solid var(--line);border-radius:var(--radius);font-size:.875rem;margin-bottom:.5rem;box-sizing:border-box;}
.listing-list{max-height:220px;overflow-y:auto;border:1px solid var(--line);border-radius:var(--radius);background:#fff;}
.listing-opt{display:flex;align-items:center;gap:.65rem;padding:.55rem .85rem;cursor:pointer;font-size:.875rem;border-bottom:1px solid var(--line);transition:background .15s;}
.listing-opt:last-child{border-bottom:none;}
.listing-opt:hover{background:var(--surface-alt);}
.listing-opt.selected{background:rgba(122,157,71,.1);font-weight:600;}
.listing-opt img{width:32px;height:32px;object-fit:contain;border-radius:3px;border:1px solid var(--line);background:#fff;flex-shrink:0;}
.listing-opt .initials{width:32px;height:32px;border-radius:3px;background:var(--brand-primary);color:#fff;display:flex;align-items:center;justify-content:center;font-size:.75rem;font-weight:700;flex-shrink:0;}
.divider{display:flex;align-items:center;gap:.75rem;margin:1.25rem 0;color:var(--ink-muted);font-size:.8rem;}
.divider::before,.divider::after{content:'';flex:1;border-top:1px solid var(--line);}
</style>

<section class="section">
<div class="container" style="max-width:680px;">

<div style="margin-bottom:1.25rem;">
    <a href="growth-partners.php" style="color:var(--ink-muted);font-size:.875rem;">← Back to Growth Partners</a>
</div>

<h1 style="margin:0 0 1.5rem;"><?= $is_new ? 'Add Growth Partner' : 'Edit Growth Partner' ?></h1>

<?php foreach ($errors as $err): ?>
    <div class="alert alert-error"><?= htmlspecialchars($err) ?></div>
<?php endforeach; ?>

<div class="card">
<form method="post" enctype="multipart/form-data">
    <?= csrf_field() ?>

    <!-- ── Directory listing picker ───────────────────────────────────── -->
    <div class="field">
        <label class="label">Link to a Directory Listing</label>
        <p class="field-hint" style="margin-bottom:.6rem;">
            Choose a listing to pull their name and logo automatically.
            Leave blank to enter details manually.
        </p>

        <!-- Hidden field holds the selected ID -->
        <input type="hidden" name="listing_id" id="listing_id"
               value="<?= (int)($partner['listing_id'] ?? 0) ?>">

        <?php
        $sel_listing = null;
        if (!empty($partner['listing_id'])) {
            foreach ($listings as $l) {
                if ((int)$l['id'] === (int)$partner['listing_id']) { $sel_listing = $l; break; }
            }
        }
        ?>

        <!-- Currently selected pill -->
        <div id="selected-listing-display" style="<?= $sel_listing ? '' : 'display:none;' ?> margin-bottom:.6rem;">
            <span class="listing-pill" id="selected-pill">
                <span id="selected-listing-name">
                    <?= $sel_listing ? htmlspecialchars($sel_listing['name']) : '' ?>
                </span>
                <button type="button" id="clear-listing"
                        style="background:none;border:none;cursor:pointer;color:var(--ink-muted);font-size:.9rem;line-height:1;padding:0 0 0 .25rem;"
                        title="Remove link">✕</button>
            </span>
        </div>

        <!-- Search + list (hidden when a listing is selected) -->
        <div id="listing-picker" style="<?= $sel_listing ? 'display:none;' : '' ?>">
            <input type="search" class="search-box" id="listing-search"
                   placeholder="Search listings by name…" autocomplete="off">
            <div class="listing-list" id="listing-list">
                <?php foreach ($listings as $l): ?>
                <div class="listing-opt <?= (int)($partner['listing_id'] ?? 0) === (int)$l['id'] ? 'selected' : '' ?>"
                     data-id="<?= $l['id'] ?>"
                     data-name="<?= htmlspecialchars($l['name'], ENT_QUOTES) ?>"
                     data-logo="<?= htmlspecialchars($l['logo_path'] ?? '', ENT_QUOTES) ?>"
                     data-website="<?= htmlspecialchars($l['website'] ?? '', ENT_QUOTES) ?>"
                     data-tier="<?= htmlspecialchars($l['tier'], ENT_QUOTES) ?>">
                    <?php if (!empty($l['logo_path'])): ?>
                        <img src="../<?= htmlspecialchars($l['logo_path']) ?>"
                             alt="<?= htmlspecialchars($l['name']) ?>">
                    <?php else: ?>
                        <div class="initials">
                            <?= htmlspecialchars(strtoupper(mb_substr($l['name'], 0, 2))) ?>
                        </div>
                    <?php endif; ?>
                    <span><?= htmlspecialchars($l['name']) ?></span>
                    <span style="margin-left:auto;font-size:.75rem;color:var(--ink-muted);">
                        <?= htmlspecialchars($l['tier']) ?>
                    </span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <div class="divider">or enter details manually</div>

    <!-- ── Name ───────────────────────────────────────────────────────── -->
    <div class="field">
        <label class="label" for="name">
            Company Name <span style="color:#b91c1c;">*</span>
        </label>
        <input type="text" id="name" name="name" class="input"
               value="<?= htmlspecialchars($partner['name']) ?>"
               placeholder="Auto-filled from listing, or type manually" required>
        <p class="field-hint" id="name-hint" style="display:none;">
            Editing this overrides the listing name on the homepage.
        </p>
    </div>

    <!-- ── Website URL ────────────────────────────────────────────────── -->
    <div class="field">
        <label class="label" for="website_url">Website URL</label>
        <input type="url" id="website_url" name="website_url" class="input"
               value="<?= htmlspecialchars($partner['website_url'] ?? '') ?>"
               placeholder="Auto-filled from listing, or enter manually">
        <p class="field-hint">
            When linked to a listing, the homepage card links to their directory page.
            A URL here overrides that.
        </p>
    </div>

    <!-- ── Logo ───────────────────────────────────────────────────────── -->
    <div class="field">
        <label class="label">Logo</label>

        <!-- Listing logo preview (shown when listing is selected and no custom logo) -->
        <div id="listing-logo-preview" class="logo-preview-wrap"
             style="<?= ($sel_listing && empty($partner['logo_path'])) ? '' : 'display:none;' ?>">
            <img id="listing-logo-img"
                 src="<?= ($sel_listing && !empty($sel_listing['logo_path'])) ? '../'.htmlspecialchars($sel_listing['logo_path']) : '' ?>"
                 alt="Listing logo">
            <p style="font-size:.8rem;margin:.5rem 0 0;color:var(--ink-muted);">
                Using directory listing logo
            </p>
        </div>

        <!-- Custom logo (uploaded override) -->
        <?php if (!empty($partner['logo_path'])): ?>
            <div class="logo-preview-wrap" id="logo-preview-current">
                <img src="../<?= htmlspecialchars($partner['logo_path']) ?>" alt="Custom logo">
                <p style="font-size:.8rem;margin:.5rem 0 0;color:var(--ink-muted);">Custom logo (overrides listing logo)</p>
            </div>
            <label style="display:flex;align-items:center;gap:.5rem;font-size:.875rem;margin-bottom:.75rem;cursor:pointer;">
                <input type="checkbox" name="remove_logo" value="1"> Remove custom logo
            </label>
        <?php else: ?>
            <div id="logo-preview-new" style="display:none;" class="logo-preview-wrap">
                <img id="logo-img-new" src="" alt="New logo">
            </div>
        <?php endif; ?>

        <div class="upload-zone" id="upload-zone">
            <input type="file" name="logo" id="logo-file"
                   accept="image/jpeg,image/png,image/webp,image/gif,image/svg+xml">
            <p style="margin:0;font-size:.875rem;color:var(--ink-muted);">
                Upload a custom logo to override the listing logo<br>
                <small>JPG, PNG, WebP, GIF or SVG — max 2 MB</small>
            </p>
        </div>
    </div>

    <!-- ── Sort order ─────────────────────────────────────────────────── -->
    <div class="field">
        <label class="label" for="sort_order">Sort Order</label>
        <input type="number" id="sort_order" name="sort_order" class="input"
               value="<?= (int)$partner['sort_order'] ?>" style="width:120px;" min="0" step="10">
        <p class="field-hint">Lower numbers appear first. You can also drag-to-reorder on the list page.</p>
    </div>

    <!-- ── Active ─────────────────────────────────────────────────────── -->
    <div class="field">
        <label style="display:flex;align-items:center;gap:.6rem;cursor:pointer;font-size:.9rem;">
            <input type="checkbox" name="active" value="1"
                   <?= $partner['active'] ? 'checked' : '' ?>>
            Show on homepage
        </label>
        <p class="field-hint">Uncheck to hide without deleting.</p>
    </div>

    <div style="display:flex;gap:.75rem;padding-top:.5rem;">
        <button type="submit" class="btn">
            <?= $is_new ? 'Add Partner' : 'Save Changes' ?>
        </button>
        <a href="growth-partners.php" class="btn btn-outline">Cancel</a>
    </div>
</form>
</div>

</div>
</section>

<script>
(function () {
    // ── Listing data map ──────────────────────────────────────────────────
    const listingMap = <?= json_encode($listing_map, JSON_HEX_TAG) ?>;

    const hiddenId      = document.getElementById('listing_id');
    const nameInput     = document.getElementById('name');
    const websiteInput  = document.getElementById('website_url');
    const nameHint      = document.getElementById('name-hint');
    const picker        = document.getElementById('listing-picker');
    const selDisplay    = document.getElementById('selected-listing-display');
    const selName       = document.getElementById('selected-listing-name');
    const clearBtn      = document.getElementById('clear-listing');
    const searchBox     = document.getElementById('listing-search');
    const listingList   = document.getElementById('listing-list');
    const listingLogoWrap = document.getElementById('listing-logo-preview');
    const listingLogoImg  = document.getElementById('listing-logo-img');
    const opts          = listingList ? [...listingList.querySelectorAll('.listing-opt')] : [];

    // ── Select a listing ─────────────────────────────────────────────────
    function selectListing(id) {
        const data = listingMap[id];
        if (!data) return;

        hiddenId.value = id;

        // Auto-fill name if blank
        if (!nameInput.value.trim()) {
            nameInput.value = data.name;
        }
        nameHint.style.display = '';

        // Auto-fill website if blank
        if (!websiteInput.value.trim() && data.website) {
            websiteInput.value = data.website;
        }

        // Show listing logo preview (only if no custom logo uploaded)
        const hasCustom = document.getElementById('logo-preview-current');
        if (!hasCustom && listingLogoWrap) {
            if (data.logo_path) {
                listingLogoImg.src = '../' + data.logo_path;
                listingLogoWrap.style.display = '';
            } else {
                listingLogoWrap.style.display = 'none';
            }
        }

        // Show selected pill, hide picker
        selName.textContent = data.name;
        selDisplay.style.display = '';
        picker.style.display = 'none';
    }

    // ── Clear selection ───────────────────────────────────────────────────
    function clearListing() {
        hiddenId.value = '';
        nameHint.style.display = 'none';
        if (listingLogoWrap) listingLogoWrap.style.display = 'none';
        selDisplay.style.display = 'none';
        picker.style.display = '';
        opts.forEach(o => o.classList.remove('selected'));
        searchBox.value = '';
        filterOpts('');
        searchBox.focus();
    }

    if (clearBtn) clearBtn.addEventListener('click', clearListing);

    // ── Click a listing row ───────────────────────────────────────────────
    opts.forEach(opt => {
        opt.addEventListener('click', () => {
            opts.forEach(o => o.classList.remove('selected'));
            opt.classList.add('selected');
            selectListing(parseInt(opt.dataset.id, 10));
        });
    });

    // If a listing is already set on load, show the name hint
    if (hiddenId.value && parseInt(hiddenId.value, 10) > 0) {
        nameHint.style.display = '';
    }

    // ── Search filter ─────────────────────────────────────────────────────
    function filterOpts(q) {
        const lq = q.toLowerCase();
        opts.forEach(opt => {
            const match = opt.dataset.name.toLowerCase().includes(lq);
            opt.style.display = match ? '' : 'none';
        });
    }

    if (searchBox) {
        searchBox.addEventListener('input', () => filterOpts(searchBox.value));
    }

    // ── Logo file preview ─────────────────────────────────────────────────
    const logoFile = document.getElementById('logo-file');
    if (logoFile) {
        logoFile.addEventListener('change', function () {
            if (!this.files[0]) return;
            const reader = new FileReader();
            reader.onload = e => {
                let wrap = document.getElementById('logo-preview-new');
                if (!wrap) {
                    wrap = document.createElement('div');
                    wrap.id = 'logo-preview-new';
                    wrap.className = 'logo-preview-wrap';
                    wrap.innerHTML = '<img id="logo-img-new" src="" alt="New logo">'
                                   + '<p style="font-size:.8rem;margin:.5rem 0 0;color:var(--ink-muted);">Custom logo (overrides listing logo)</p>';
                    document.getElementById('upload-zone').before(wrap);
                }
                wrap.style.display = '';
                wrap.querySelector('img').src = e.target.result;
                // Hide listing logo preview since custom takes priority
                if (listingLogoWrap) listingLogoWrap.style.display = 'none';
            };
            reader.readAsDataURL(this.files[0]);
        });

        const zone = document.getElementById('upload-zone');
        ['dragover','dragenter'].forEach(ev => zone.addEventListener(ev, () => zone.classList.add('dragover')));
        ['dragleave','drop'].forEach(ev => zone.addEventListener(ev, () => zone.classList.remove('dragover')));
    }
})();
</script>

<?php require __DIR__ . '/_footer.php'; ?>