<?php
// POST handling before _guard so header() redirects work
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/member_history.php';
auth_require_login();

$member = auth_user();
if (!$member) { auth_logout(); header('Location: ../login.php'); exit; }

// Load member's listing
$listing = db_row('SELECT * FROM listings WHERE member_id = :m LIMIT 1', ['m' => $member['id']]);

// Load categories + current selection
$categories = db_all('SELECT slug, name FROM categories ORDER BY sort_order, name');
$selected_cats = [];
$primary_cat   = null;
if ($listing) {
    try {
        $rows = db_all(
            'SELECT category_slug, is_primary FROM listing_categories WHERE listing_id = :id',
            ['id' => $listing['id']]
        );
        foreach ($rows as $r) {
            $selected_cats[] = $r['category_slug'];
            if ($r['is_primary']) $primary_cat = $r['category_slug'];
        }
    } catch (Throwable $e) { /* junction not migrated */ }
    // Fallback to legacy single category
    if (empty($selected_cats) && !empty($listing['category_slug'])) {
        $selected_cats = [$listing['category_slug']];
        $primary_cat   = $listing['category_slug'];
    }
}

$saved = false;
$errors = [];

function listing_slug_for(string $name, ?int $exclude_id = null): string {
    $base = preg_replace('/[^a-z0-9]+/', '-', strtolower($name));
    $base = trim($base, '-') ?: 'listing';
    $slug = $base; $n = 2;
    while (true) {
        $existing = db_row('SELECT id FROM listings WHERE slug=:s', ['s'=>$slug]);
        if (!$existing || (int)$existing['id'] === (int)$exclude_id) break;
        $slug = $base . '-' . $n++;
    }
    return $slug;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();

    $first_name    = trim($_POST['first_name']    ?? '');
    $last_name     = trim($_POST['last_name']     ?? '');
    $phone         = trim($_POST['phone']         ?? '');
    $business_name = trim($_POST['business_name'] ?? '');
    $description   = trim($_POST['description']   ?? '');
    $tagline       = trim($_POST['tagline']       ?? '');
    $website       = trim($_POST['website']       ?? '');
    $address       = trim($_POST['address']       ?? '');
    $cats_posted   = $_POST['categories']         ?? [];
    $primary       = trim($_POST['primary_category'] ?? '');

    if (!is_array($cats_posted)) $cats_posted = [];
    $cats_posted = array_values(array_unique(array_filter($cats_posted, fn($s) =>
        is_string($s) && preg_match('/^[a-z0-9\-]+$/', $s)
    )));

    // Validation
    if (!$first_name || !$last_name) $errors[] = 'Please fill in your first and last name.';
    if (!$business_name)             $errors[] = 'Business name is required.';
    if (!$description)               $errors[] = 'Business description is required.';
    if (empty($cats_posted))         $errors[] = 'Please pick at least one category.';

    if ($primary && !in_array($primary, $cats_posted, true)) $primary = $cats_posted[0] ?? '';
    if (!$primary && !empty($cats_posted)) $primary = $cats_posted[0];

    // ── Pre-flight: validate + dupe check against local DB and Zoho ─────
    // Members can't change their own email (security), so we don't dupe-check it.
    if (empty($errors)) {
        require_once __DIR__ . '/../includes/zoho.php';
        $check = zoho_validate_member_changes((int)$member['id'], [
            'first_name'    => $first_name,
            'last_name'     => $last_name,
            'business_name' => $business_name,
            'phone'         => $phone ?: null,
        ]);
        if (!$check['ok']) {
            $errors[] = $check['error'];
        }
    }

    // Logo upload
    $logo_path = $listing['logo_path'] ?? null;
    if (!empty($_FILES['logo']['name'])) {
        $file    = $_FILES['logo'];
        $allowed = ['image/jpeg','image/png','image/gif','image/webp'];
        if (!in_array($file['type'], $allowed, true))      $errors[] = 'Logo must be JPG, PNG, GIF or WebP.';
        elseif ($file['size'] > 2*1024*1024)               $errors[] = 'Logo must be under 2MB.';
        elseif ($file['error'] !== UPLOAD_ERR_OK)          $errors[] = 'Logo upload failed.';
        else {
            $dir = __DIR__ . '/../assets/uploads/logos/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $name_safe = 'listing-' . ($listing['id'] ?? time()) . '-' . bin2hex(random_bytes(2)) . '.' . $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/logos/' . $name_safe;
            } else {
                $errors[] = 'Could not save logo.';
            }
        }
    }
    if (!empty($_POST['remove_logo']) && $logo_path) {
        $old = __DIR__ . '/../' . ltrim($logo_path, '/');
        if (file_exists($old)) @unlink($old);
        $logo_path = null;
    }

    // Banner upload
    $banner_path = $listing['banner_path'] ?? null;
    if (!empty($_FILES['banner']['name'])) {
        $file    = $_FILES['banner'];
        $allowed = ['image/jpeg','image/png','image/gif','image/webp'];
        if (!in_array($file['type'], $allowed, true))      $errors[] = 'Banner must be JPG, PNG, GIF or WebP.';
        elseif ($file['size'] > 5*1024*1024)               $errors[] = 'Banner must be under 5MB.';
        elseif ($file['error'] !== UPLOAD_ERR_OK)          $errors[] = 'Banner upload failed.';
        else {
            $dir = __DIR__ . '/../assets/uploads/banners/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $name_safe = 'listing-' . ($listing['id'] ?? time()) . '-' . bin2hex(random_bytes(2)) . '.' . $ext;
            if (move_uploaded_file($file['tmp_name'], $dir . $name_safe)) {
                if ($banner_path) {
                    $old = __DIR__ . '/../' . ltrim($banner_path, '/');
                    if (file_exists($old)) @unlink($old);
                }
                $banner_path = 'assets/uploads/banners/' . $name_safe;
            } else {
                $errors[] = 'Could not save banner.';
            }
        }
    }
    if (!empty($_POST['remove_banner']) && $banner_path) {
        $old = __DIR__ . '/../' . ltrim($banner_path, '/');
        if (file_exists($old)) @unlink($old);
        $banner_path = null;
    }

    if (empty($errors)) {
        // ── Push to Zoho FIRST (only if member is linked to a Zoho contact) ──
        // If Zoho rejects, we abort before changing the local DB so we never
        // end up with local data drifted from Zoho.
        if (!empty($member['zoho_contact_id']) && zoho_is_configured()) {
            $r = zoho_update_contact((string)$member['zoho_contact_id'], [
                'first_name'    => $first_name,
                'last_name'     => $last_name,
                'business_name' => $business_name,
                'phone'         => $phone ?: null,
            ], (int)$member['id']);
            if (!$r['ok']) {
                $errors[] = 'We couldn\'t save your changes — our accounting system rejected them: '
                          . ($r['error'] ?? 'unknown error') . '. Please try again, or contact us if it keeps happening.';
            }
        }
    }

    if (empty($errors)) {
        $member_before = $member;  // snapshot for diff

        // Update member row
        db_update('members', (int)$member['id'], [
            'first_name'    => $first_name,
            'last_name'     => $last_name,
            'phone'         => $phone ?: null,
            'business_name' => $business_name,
            'industry'      => $primary,
        ]);

        // Upsert the listing
        $listing_fields = [
            'name'          => $business_name,
            'category_slug' => $primary,
            'description'   => $description,
            'tagline'       => $tagline ?: null,
            'phone'         => $phone ?: null,
            'email'         => $member['email'],
            'website'       => $website ?: null,
            'address'       => $address ?: null,
            'logo_path'     => $logo_path,
            'banner_path'   => $banner_path,
        ];

        if ($listing) {
            db_update('listings', (int)$listing['id'], $listing_fields);
            $listing_id = (int)$listing['id'];
        } else {
            $listing_fields['slug']      = listing_slug_for($business_name);
            $listing_fields['member_id'] = $member['id'];
            $listing_fields['tier']      = $member['tier'] ?? 'Bronze';
            $listing_fields['featured']  = 0;
            $listing_fields['published'] = 1;
            $listing_fields['profile_complete'] = 1;
            $listing_id = db_insert('listings', $listing_fields);
        }

        // Reset + rewrite categories in junction
        try {
            db_exec('DELETE FROM listing_categories WHERE listing_id = :id', ['id' => $listing_id]);
            foreach ($cats_posted as $c) {
                db_exec(
                    'INSERT IGNORE INTO listing_categories (listing_id, category_slug, is_primary)
                     VALUES (:l, :c, :p)',
                    ['l' => $listing_id, 'c' => $c, 'p' => $c === $primary ? 1 : 0]
                );
            }
        } catch (Throwable $e) { /* junction not migrated — fine */ }

        // Refresh state
        $fresh_member = db_row('SELECT * FROM members WHERE id = :id', ['id' => $member['id']]);

        // Log to member history (member-side edits)
        member_history_log_changes(
            (int)$member['id'],
            $member_before,
            $fresh_member,
            ['first_name','last_name','phone','business_name','industry']
        );

        app_log("Profile update: member {$member['id']} ({$fresh_member['email']})");
        $member  = $fresh_member;
        $listing = db_row('SELECT * FROM listings WHERE member_id = :m LIMIT 1', ['m' => $member['id']]);
        $selected_cats = $cats_posted;
        $primary_cat   = $primary;
        $saved = true;
    } else {
        // Keep what user typed on re-render
        $selected_cats = $cats_posted;
        $primary_cat   = $primary;
    }
}

// Values for the form
$v = [
    'first_name'    => $_POST['first_name']    ?? $member['first_name']    ?? '',
    'last_name'     => $_POST['last_name']     ?? $member['last_name']     ?? '',
    'phone'         => $_POST['phone']         ?? $member['phone']         ?? '',
    'business_name' => $_POST['business_name'] ?? $member['business_name'] ?? '',
    'description'   => $_POST['description']   ?? $listing['description']  ?? '',
    'tagline'       => $_POST['tagline']       ?? $listing['tagline']      ?? '',
    'website'       => $_POST['website']       ?? $listing['website']      ?? '',
    'address'       => $_POST['address']       ?? $listing['address']      ?? '',
];

$page_title = 'Edit Business';
require __DIR__ . '/_guard.php';
?>

<style>
.m-page{padding:2rem 0 3rem;}
.m-card{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:1.5rem;margin-bottom:1.25rem;}
.m-card h2{margin-top:0;font-size:1rem;}
.form-2col{display:grid;grid-template-columns:1fr 1fr;gap:0 1.25rem;}
@media(max-width:600px){.form-2col{grid-template-columns:1fr;}}

.cat-picker{
    border:1px solid var(--line);
    border-radius:var(--radius);
    max-height:260px;
    overflow-y:auto;
    background:#fff;
    margin-bottom:1rem;
}
.cat-row{display:flex;align-items:center;gap:.65rem;padding:.45rem .8rem;border-bottom:1px solid var(--line);cursor:pointer;font-size:.88rem;font-weight:400;margin:0;}
.cat-row:last-child{border-bottom:none;}
.cat-row:hover{background:#fafafa;}
.cat-row .cat-label{flex:1;}
.cat-row .cat-primary-wrap{display:flex;align-items:center;gap:.3rem;opacity:.3;transition:opacity .15s;}
.cat-row .cat-primary-lbl{font-size:.7rem;text-transform:uppercase;letter-spacing:.04em;color:var(--ink-muted);}
.cat-row.has-check .cat-primary-wrap{opacity:1;}

.upload-zone{border:2px dashed var(--line);border-radius:var(--radius);padding:1.25rem;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:140px;max-height:140px;object-fit:contain;margin:0 auto;display:block;}

.banner-preview-wrap{border-radius:var(--radius);margin-bottom:.75rem;overflow:hidden;background:var(--surface-alt);border:1px solid var(--line);}
.banner-preview-wrap img{width:100%;height:auto;display:block;aspect-ratio:16/9;object-fit:cover;}

.upload-grid{display:grid;grid-template-columns:1fr 1fr;gap:1.25rem;}
@media(max-width:700px){.upload-grid{grid-template-columns:1fr;}}
</style>

<div class="m-page">
<div class="container" style="max-width:860px;">

    <a href="welcome.php" style="font-size:.88rem;color:var(--ink-muted);">← Back to dashboard</a>
    <h1 style="margin:.75rem 0 .25rem;">Edit Business</h1>
    <p style="margin:0 0 1.5rem;color:var(--ink-muted);">Update your contact details and what appears on your public directory page.</p>

    <?php if ($saved): ?>
        <div class="alert alert-success" data-autohide>
            <strong>Saved.</strong> Changes are live on the directory.
        </div>
    <?php endif; ?>
    <?php if (!empty($errors)): ?>
        <div class="alert alert-error"><?= implode('<br>', array_map('htmlspecialchars', $errors)) ?></div>
    <?php endif; ?>

    <form method="post" action="edit-business.php" enctype="multipart/form-data">
        <?= csrf_field() ?>

        <!-- Contact info -->
        <div class="m-card">
            <h2>Your contact details</h2>
            <div class="form-2col">
                <div>
                    <label>First name *</label>
                    <input type="text" name="first_name" required value="<?= htmlspecialchars($v['first_name']) ?>">
                </div>
                <div>
                    <label>Last name *</label>
                    <input type="text" name="last_name" required value="<?= htmlspecialchars($v['last_name']) ?>">
                </div>
            </div>
            <div class="form-2col">
                <div>
                    <label>Email <small>(cannot change)</small></label>
                    <input type="email" value="<?= htmlspecialchars($member['email']) ?>" disabled
                           style="background:var(--surface-alt);color:var(--ink-muted);">
                </div>
                <div>
                    <label>Phone</label>
                    <input type="tel" name="phone" value="<?= htmlspecialchars($v['phone']) ?>"
                           placeholder="013 000 0000">
                </div>
            </div>
        </div>

        <!-- Business info -->
        <div class="m-card">
            <h2>Business listing</h2>
            <p style="margin:0 0 1rem;font-size:.85rem;color:var(--ink-muted);">
                This is what appears on your public directory page.
            </p>

            <label>Business name *</label>
            <input type="text" name="business_name" required value="<?= htmlspecialchars($v['business_name']) ?>">

            <label>Tagline <small>(one short line shown under your name)</small></label>
            <input type="text" name="tagline" maxlength="200" value="<?= htmlspecialchars($v['tagline']) ?>"
                   placeholder="e.g. Family-run since 1995">

            <label>Description * <small>2–3 sentences about your business</small></label>
            <textarea name="description" rows="4" required
                      placeholder="Tell customers who you are and what makes you different."><?= htmlspecialchars($v['description']) ?></textarea>

            <label>Categories * <small>(tick all that apply — pick a primary with the radio)</small></label>
            <div class="cat-picker">
                <?php foreach ($categories as $c):
                    $slug = $c['slug'];
                    $checked = in_array($slug, $selected_cats, true);
                    $is_pri  = ($primary_cat ?? '') === $slug;
                ?>
                    <label class="cat-row">
                        <input type="checkbox" name="categories[]" value="<?= htmlspecialchars($slug) ?>"
                               <?= $checked ? 'checked' : '' ?> class="cat-check">
                        <span class="cat-label"><?= htmlspecialchars($c['name']) ?></span>
                        <span class="cat-primary-wrap">
                            <input type="radio" name="primary_category" value="<?= htmlspecialchars($slug) ?>"
                                   <?= $is_pri ? 'checked' : '' ?> class="cat-primary">
                            <span class="cat-primary-lbl">primary</span>
                        </span>
                    </label>
                <?php endforeach; ?>
            </div>

            <div class="form-2col">
                <div>
                    <label>Physical address</label>
                    <input type="text" name="address" value="<?= htmlspecialchars($v['address']) ?>"
                           placeholder="26 Main Road, Nelspruit">
                </div>
                <div>
                    <label>Website</label>
                    <input type="url" name="website" value="<?= htmlspecialchars($v['website']) ?>"
                           placeholder="https://yourbusiness.co.za">
                </div>
            </div>
        </div>

        <!-- Uploads -->
        <div class="m-card">
            <h2>Photos</h2>
            <p style="margin:0 0 1rem;font-size:.85rem;color:var(--ink-muted);">
                Your <strong>logo</strong> is shown on the directory cards and on your public page header.
                Your <strong>banner photo</strong> (a photo of your storefront, team, or premises) shows at the top of your public page.
                If you don't upload a banner, your logo is shown there instead.
            </p>

            <div class="upload-grid">
                <!-- Logo -->
                <div>
                    <label>Logo</label>
                    <?php if (!empty($listing['logo_path'])): ?>
                        <div class="logo-preview-wrap" id="logo-preview-current">
                            <img src="../<?= htmlspecialchars($listing['logo_path']) ?>" alt="current logo">
                        </div>
                        <label style="display:flex;align-items:center;gap:.4rem;font-size:.8rem;font-weight:400;margin-bottom:.5rem;cursor:pointer;">
                            <input type="checkbox" name="remove_logo" value="1">
                            Remove current logo
                        </label>
                    <?php endif; ?>
                    <div class="logo-preview-wrap" id="logo-preview-new" style="display:none;">
                        <img id="logo-preview-new-src" src="" alt="new logo preview">
                    </div>
                    <p id="logo-preview-new-label" style="display:none;font-size:.78rem;color:var(--brand-primary);margin:0 0 .5rem;font-weight:600;">
                        ✓ New logo selected.
                    </p>
                    <div class="upload-zone" id="logo-zone">
                        <input type="file" name="logo" id="logo-input"
                               accept="image/jpeg,image/png,image/gif,image/webp">
                        <div>
                            <div style="font-size:1.3rem;">🖼</div>
                            <p style="font-size:.8rem;margin:.3rem 0 0;color:var(--ink-muted);">
                                Click or drag · JPG/PNG, max 2MB
                            </p>
                        </div>
                    </div>
                </div>

                <!-- Banner -->
                <div>
                    <label>Banner / business photo</label>
                    <?php if (!empty($listing['banner_path'])): ?>
                        <div class="banner-preview-wrap" id="banner-preview-current">
                            <img src="../<?= htmlspecialchars($listing['banner_path']) ?>" alt="current banner">
                        </div>
                        <label style="display:flex;align-items:center;gap:.4rem;font-size:.8rem;font-weight:400;margin-bottom:.5rem;cursor:pointer;">
                            <input type="checkbox" name="remove_banner" value="1">
                            Remove current banner
                        </label>
                    <?php endif; ?>
                    <div class="banner-preview-wrap" id="banner-preview-new" style="display:none;">
                        <img id="banner-preview-new-src" src="" alt="new banner preview">
                    </div>
                    <p id="banner-preview-new-label" style="display:none;font-size:.78rem;color:var(--brand-primary);margin:0 0 .5rem;font-weight:600;">
                        ✓ New banner selected.
                    </p>
                    <div class="upload-zone" id="banner-zone">
                        <input type="file" name="banner" id="banner-input"
                               accept="image/jpeg,image/png,image/gif,image/webp">
                        <div>
                            <div style="font-size:1.3rem;">🏢</div>
                            <p style="font-size:.8rem;margin:.3rem 0 0;color:var(--ink-muted);">
                                Click or drag · JPG/PNG, max 5MB
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div style="display:flex;gap:.75rem;align-items:center;flex-wrap:wrap;">
            <button type="submit" class="btn">Save changes</button>
            <a href="welcome.php" class="btn btn-outline">Cancel</a>
            <?php if ($listing): ?>
                <a href="../directory-item.php?id=<?= $listing['id'] ?>"
                   style="font-size:.85rem;color:var(--ink-muted);margin-left:auto;" target="_blank">
                    View live listing →
                </a>
            <?php endif; ?>
        </div>
    </form>

</div>
</div>

<script>
// Category picker: only enable "primary" radio for checked rows
(function () {
    const rows = document.querySelectorAll('.cat-row');
    function syncRows() {
        let anyPrimaryChecked = false;
        rows.forEach(r => {
            const ck = r.querySelector('.cat-check');
            r.classList.toggle('has-check', ck.checked);
            const pri = r.querySelector('.cat-primary');
            pri.disabled = !ck.checked;
            if (pri.checked && ck.checked) anyPrimaryChecked = true;
        });
        if (!anyPrimaryChecked) {
            for (const r of rows) {
                const ck = r.querySelector('.cat-check');
                if (ck.checked) { r.querySelector('.cat-primary').checked = true; break; }
            }
        }
    }
    rows.forEach(r => {
        r.querySelector('.cat-check').addEventListener('change', syncRows);
        r.querySelector('.cat-primary').addEventListener('change', () => {
            r.querySelector('.cat-check').checked = true;
            syncRows();
        });
    });
    syncRows();
})();

// Logo preview
(function () {
    const zone = document.getElementById('logo-zone');
    const input = document.getElementById('logo-input');
    const box = document.getElementById('logo-preview-new');
    const img = document.getElementById('logo-preview-new-src');
    const lbl = document.getElementById('logo-preview-new-label');
    const cur = document.getElementById('logo-preview-current');
    function preview(file) {
        if (!file) return;
        const r = new FileReader();
        r.onload = e => {
            img.src = e.target.result;
            box.style.display = 'block';
            if (lbl) lbl.style.display = 'block';
            if (cur) cur.style.opacity = '0.35';
        };
        r.readAsDataURL(file);
    }
    if (zone && input) {
        zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('dragover'); });
        zone.addEventListener('dragleave', () => zone.classList.remove('dragover'));
        zone.addEventListener('drop', e => {
            e.preventDefault(); zone.classList.remove('dragover');
            if (e.dataTransfer.files[0]) {
                const dt = new DataTransfer(); dt.items.add(e.dataTransfer.files[0]);
                input.files = dt.files;
                preview(e.dataTransfer.files[0]);
            }
        });
        input.addEventListener('change', () => { if (input.files[0]) preview(input.files[0]); });
    }
})();

// Banner preview
(function () {
    const zone = document.getElementById('banner-zone');
    const input = document.getElementById('banner-input');
    const box = document.getElementById('banner-preview-new');
    const img = document.getElementById('banner-preview-new-src');
    const lbl = document.getElementById('banner-preview-new-label');
    const cur = document.getElementById('banner-preview-current');
    function preview(file) {
        if (!file) return;
        const r = new FileReader();
        r.onload = e => {
            img.src = e.target.result;
            box.style.display = 'block';
            if (lbl) lbl.style.display = 'block';
            if (cur) cur.style.opacity = '0.35';
        };
        r.readAsDataURL(file);
    }
    if (zone && input) {
        zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('dragover'); });
        zone.addEventListener('dragleave', () => zone.classList.remove('dragover'));
        zone.addEventListener('drop', e => {
            e.preventDefault(); zone.classList.remove('dragover');
            if (e.dataTransfer.files[0]) {
                const dt = new DataTransfer(); dt.items.add(e.dataTransfer.files[0]);
                input.files = dt.files;
                preview(e.dataTransfer.files[0]);
            }
        });
        input.addEventListener('change', () => { if (input.files[0]) preview(input.files[0]); });
    }
})();
</script>

<?php require __DIR__ . '/_footer.php'; ?>