<?php
// ============================================================
//  member/complete-profile.php
// ============================================================
//
//  Step 4 of the signup flow: fill in company details + upload
//  logo. Creates the directory listing and makes it live.
//
//  Only accessible to members with an active subscription.
//  Members can also access this later to update their listing.
//
// ============================================================

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/mailchimp.php';

auth_require_login();
$member = auth_user();

// Guard: must have active subscription
if ($member['status'] !== 'active') {
    header('Location: checkout-membership.php?blocked=1'); exit;
}

$categories = db_all('SELECT slug, name FROM categories ORDER BY sort_order, name');

// Check if listing already exists
$listing = db_row(
    'SELECT * FROM listings WHERE member_id=:m LIMIT 1',
    ['m' => $member['id']]
);
$is_update = !empty($listing);

$errors  = [];
$success = false;

// ── Handle POST ──────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();

    $business_name = trim($_POST['business_name'] ?? $member['business_name']);
    $tagline       = trim($_POST['tagline']       ?? '');
    $description   = trim($_POST['description']   ?? '');
    $category      = trim($_POST['category']      ?? $member['industry'] ?? '');
    $address       = trim($_POST['address']        ?? '');
    $phone         = trim($_POST['phone']          ?? $member['phone'] ?? '');
    $website       = trim($_POST['website']        ?? '');
    $facebook      = trim($_POST['facebook']       ?? '');
    $instagram     = trim($_POST['instagram']      ?? '');

    // Validate
    if (!$business_name) $errors[] = 'Business name is required.';
    if (!$description)   $errors[] = 'A description is required.';
    if (!$category)      $errors[] = 'Please select a category.';

    // Handle 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'];
        $max_bytes = 2 * 1024 * 1024; // 2MB

        if (!in_array($file['type'], $allowed, true)) {
            $errors[] = 'Logo must be a JPG, PNG, GIF, or WebP image.';
        } elseif ($file['size'] > $max_bytes) {
            $errors[] = 'Logo must be under 2MB.';
        } elseif ($file['error'] !== UPLOAD_ERR_OK) {
            $errors[] = 'Logo upload failed (error ' . $file['error'] . '). Please try again.';
        } else {
            $upload_dir = __DIR__ . '/../assets/uploads/logos/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);

            $ext       = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $filename  = 'member-' . $member['id'] . '-' . time() . '.' . $ext;
            $dest      = $upload_dir . $filename;

            if (move_uploaded_file($file['tmp_name'], $dest)) {
                // Delete old logo if replacing
                if ($logo_path) {
                    $old = __DIR__ . '/../' . ltrim($logo_path, '/');
                    if (file_exists($old)) @unlink($old);
                }
                $logo_path = 'assets/uploads/logos/' . $filename;
            } else {
                $errors[] = 'Could not save the logo. Check folder permissions.';
            }
        }
    }

    if (empty($errors)) {
        // Generate unique slug from business name
        $slug = slug_unique($business_name, $listing['slug'] ?? null);

        $listing_data = [
            'member_id'     => $member['id'],
            'slug'          => $slug,
            'name'          => $business_name,
            'category_slug' => $category,
            'tier'          => $member['tier'],
            'description'   => $description,
            'tagline'       => $tagline ?: null,
            'phone'         => $phone   ?: null,
            'email'         => $member['email'],
            'website'       => $website ?: null,
            'address'       => $address ?: null,
            'logo_path'     => $logo_path,
            'published'     => 1,
            'profile_complete' => 1,
        ];

        if ($is_update) {
            // Remove slug from update (can't change slug once set — URLs break)
            unset($listing_data['slug'], $listing_data['member_id']);
            db_update('listings', (int)$listing['id'], $listing_data);
        } else {
            // Check if a listing with this member already snuck in
            $existing_listing = db_row(
                'SELECT id FROM listings WHERE member_id=:m LIMIT 1',
                ['m' => $member['id']]
            );
            if ($existing_listing) {
                unset($listing_data['slug'], $listing_data['member_id']);
                db_update('listings', (int)$existing_listing['id'], $listing_data);
            } else {
                db_insert('listings', $listing_data);
            }
        }

        // Update member phone if changed
        if ($phone && $phone !== $member['phone']) {
            db_exec('UPDATE members SET phone=:p WHERE id=:id',
                    ['p' => $phone, 'id' => $member['id']]);
        }

        // Update business name if changed
        if ($business_name !== $member['business_name']) {
            db_exec('UPDATE members SET business_name=:b WHERE id=:id',
                    ['b' => $business_name, 'id' => $member['id']]);
        }

        // Sync to Mailchimp
        $fresh_member = db_row('SELECT * FROM members WHERE id=:id', ['id'=>$member['id']]);
        mc_sync_member_from_db($fresh_member, 'profile_complete');

        // Reload listing for display
        $listing = db_row('SELECT * FROM listings WHERE member_id=:m LIMIT 1',
                          ['m' => $member['id']]);
        $member  = $fresh_member;
        $is_update = true;
        $success = true;
    }
}

// ── Slug helper ──────────────────────────────────────────────
function slug_unique(string $name, ?string $existing_slug): string {
    $base = preg_replace('/[^a-z0-9]+/', '-', strtolower($name));
    $base = trim($base, '-') ?: 'member';

    // If the existing slug starts with this base, keep it
    if ($existing_slug && strpos($existing_slug, $base) === 0) {
        return $existing_slug;
    }

    $slug = $base;
    $n    = 2;
    while (db_value('SELECT id FROM listings WHERE slug=:s', ['s' => $slug])) {
        $slug = $base . '-' . $n++;
    }
    return $slug;
}

// Prefill values
$v = [
    'business_name' => $_POST['business_name'] ?? $listing['name']      ?? $member['business_name'],
    'tagline'       => $_POST['tagline']        ?? $listing['tagline']   ?? '',
    'description'   => $_POST['description']    ?? $listing['description'] ?? '',
    'category'      => $_POST['category']       ?? $listing['category_slug'] ?? $member['industry'] ?? '',
    'address'       => $_POST['address']        ?? $listing['address']   ?? '',
    'phone'         => $_POST['phone']          ?? $listing['phone']     ?? $member['phone'] ?? '',
    'website'       => $_POST['website']        ?? $listing['website']   ?? '',
];

$page_title = $is_update ? 'Update your listing' : 'Complete your profile';
require __DIR__ . '/_guard.php';
?>

<style>
.profile-wrap { max-width: 820px; margin: 0 auto; }
.upload-area {
    border: 2px dashed var(--line); border-radius: var(--radius);
    padding: 1.5rem; text-align: center; cursor: pointer;
    transition: border-color .2s, background .2s; position: relative;
}
.upload-area:hover, .upload-area.dragover {
    border-color: var(--brand-primary); background: rgba(34,139,34,.03);
}
.upload-area input[type=file] {
    position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%;
}
.logo-preview { max-height: 100px; max-width: 200px; border-radius: 4px;
                display: none; margin: .5rem auto 0; }
.live-badge {
    display: inline-flex; align-items: center; gap: .4rem;
    background: #d4f4dd; color: #1b5e20; padding: .35rem .85rem;
    border-radius: 999px; font-size: .82rem; font-weight: 700;
}
.live-badge::before { content: '●'; font-size: .65rem; }
</style>

<section class="section">
<div class="container profile-wrap">

    <?php if ($success): ?>
        <!-- ── Success state ── -->
        <div style="text-align:center;padding:2rem 0 1rem;">
            <div style="font-size:3.5rem;">✅</div>
            <h1>Your listing is live!</h1>
            <span class="live-badge">Live on the directory</span>
            <p class="muted mt-2">
                Your business is now visible to everyone browsing the Buy Local Lowveld directory.
            </p>
        </div>

        <?php if ($listing): ?>
        <div class="card" style="text-align:center;">
            <?php if (!empty($listing['logo_path'])): ?>
                <img src="<?= htmlspecialchars('../' . $listing['logo_path']) ?>"
                     alt="logo" style="max-height:80px;max-width:180px;margin-bottom:1rem;">
            <?php endif; ?>
            <h2 style="margin:.5rem 0 .25rem;"><?= htmlspecialchars($listing['name']) ?></h2>
            <?php if ($listing['tagline']): ?>
                <p class="muted" style="margin:0 0 1rem;"><?= htmlspecialchars($listing['tagline']) ?></p>
            <?php endif; ?>

            <div style="display:flex;gap:1rem;justify-content:center;flex-wrap:wrap;margin-top:1rem;">
                <a href="../directory-item.php?id=<?= $listing['id'] ?>"
                   class="btn" target="_blank">View my listing →</a>
                <a href="welcome.php" class="btn btn-outline">Go to dashboard</a>
                <a href="complete-profile.php" class="btn btn-outline">Edit listing</a>
            </div>
        </div>
        <?php endif; ?>

    <?php else: ?>
        <!-- ── Form ── -->
        <?php if (!$is_update): ?>
            <div style="text-align:center;margin-bottom:2rem;">
                <div style="font-size:2.5rem;">🏢</div>
                <h1>Complete your listing</h1>
                <p class="muted">
                    This creates your public page on the Buy Local Lowveld directory.
                    Takes about 2 minutes.
                </p>
            </div>
        <?php else: ?>
            <h1><?= $page_title ?></h1>
        <?php endif; ?>

        <?php if (!empty($errors)): ?>
            <div class="alert alert-error" style="margin-bottom:1.5rem;">
                <?= implode('<br>', array_map('htmlspecialchars', $errors)) ?>
            </div>
        <?php endif; ?>

        <form method="post" action="complete-profile.php"
              enctype="multipart/form-data">
            <?= csrf_field() ?>

            <div class="card mb-3">
                <h2 style="margin-top:0;">Business details</h2>

                <div style="display:grid;grid-template-columns:1fr 1fr;gap:0 1.25rem;">
                    <div>
                        <label>Business name *</label>
                        <input type="text" name="business_name" required
                               value="<?= htmlspecialchars($v['business_name']) ?>">
                        <p class="muted" style="font-size:.78rem;margin-top:.25rem;">
                            This becomes part of your directory URL.
                        </p>
                    </div>
                    <div>
                        <label>Category *</label>
                        <select name="category" required>
                            <option value="">— choose —</option>
                            <?php foreach ($categories as $c): ?>
                                <option value="<?= htmlspecialchars($c['slug']) ?>"
                                        <?= $v['category']===$c['slug']?'selected':'' ?>>
                                    <?= htmlspecialchars($c['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <label>Tagline <small>(one punchy sentence — shown under your business name)</small></label>
                <input type="text" name="tagline" maxlength="200"
                       value="<?= htmlspecialchars($v['tagline']) ?>"
                       placeholder="e.g. The Lowveld's favourite family butcher since 1988">

                <label>Description * <small>(2–4 sentences about your business)</small></label>
                <textarea name="description" rows="4" required
                          placeholder="Tell potential customers who you are, what you do, and what makes you different."><?= htmlspecialchars($v['description']) ?></textarea>
            </div>

            <div class="card mb-3">
                <h2 style="margin-top:0;">Contact &amp; location</h2>

                <div style="display:grid;grid-template-columns:1fr 1fr;gap:0 1.25rem;">
                    <div>
                        <label>Phone</label>
                        <input type="tel" name="phone"
                               value="<?= htmlspecialchars($v['phone']) ?>"
                               placeholder="013 000 0000">
                    </div>
                    <div>
                        <label>Website</label>
                        <input type="url" name="website"
                               value="<?= htmlspecialchars($v['website']) ?>"
                               placeholder="https://yourbusiness.co.za">
                    </div>
                </div>

                <label>Physical address</label>
                <input type="text" name="address"
                       value="<?= htmlspecialchars($v['address']) ?>"
                       placeholder="26 Main Road, Nelspruit, 1200">
            </div>

            <div class="card mb-3">
                <h2 style="margin-top:0;">Business logo</h2>
                <p class="muted" style="margin-top:0;font-size:.9rem;">
                    JPG, PNG, or WebP. Max 2MB. Square or landscape works best.
                </p>

                <?php if (!empty($listing['logo_path'])): ?>
                    <div style="margin-bottom:1rem;">
                        <p class="muted" style="font-size:.8rem;margin-bottom:.4rem;">Current logo:</p>
                        <img src="<?= htmlspecialchars('../' . $listing['logo_path']) ?>"
                             alt="current logo"
                             style="max-height:80px;max-width:200px;border-radius:4px;border:1px solid var(--line);">
                    </div>
                <?php endif; ?>

                <div class="upload-area" id="upload-area">
                    <input type="file" name="logo" id="logo-input"
                           accept="image/jpeg,image/png,image/gif,image/webp">
                    <div id="upload-prompt">
                        <div style="font-size:2rem;">📁</div>
                        <p style="margin:.5rem 0 .25rem;">
                            <strong>Click to upload</strong> or drag and drop
                        </p>
                        <p class="muted" style="font-size:.82rem;margin:0;">PNG, JPG, WebP up to 2MB</p>
                    </div>
                    <img id="logo-preview" class="logo-preview" src="" alt="preview">
                </div>
            </div>

            <div style="display:flex;gap:.75rem;align-items:center;margin-top:1.5rem;">
                <button type="submit" class="btn">
                    <?= $is_update ? 'Update listing' : 'Publish my listing →' ?>
                </button>
                <a href="welcome.php" class="btn btn-outline">
                    <?= $is_update ? 'Cancel' : 'Skip for now' ?>
                </a>
                <?php if ($is_update && $listing): ?>
                    <a href="../directory-item.php?id=<?= $listing['id'] ?>"
                       class="muted" style="font-size:.85rem;" target="_blank">
                        View live listing →
                    </a>
                <?php endif; ?>
            </div>

            <p class="muted mt-2" style="font-size:.82rem;">
                <?= $is_update
                    ? 'Changes go live immediately on the directory.'
                    : 'Your listing publishes immediately. You can edit it any time from your dashboard.' ?>
            </p>
        </form>
    <?php endif; ?>

</div>
</section>

<script>
// Drag and drop + preview
const area  = document.getElementById('upload-area');
const input = document.getElementById('logo-input');
const prev  = document.getElementById('logo-preview');
const prom  = document.getElementById('upload-prompt');

if (input) {
    input.addEventListener('change', function () {
        if (this.files && this.files[0]) {
            const reader = new FileReader();
            reader.onload = e => {
                prev.src = e.target.result;
                prev.style.display = 'block';
                prom.style.display = 'none';
            };
            reader.readAsDataURL(this.files[0]);
        }
    });
}
if (area) {
    area.addEventListener('dragover',  e => { e.preventDefault(); area.classList.add('dragover'); });
    area.addEventListener('dragleave', () => area.classList.remove('dragover'));
    area.addEventListener('drop', e => {
        e.preventDefault();
        area.classList.remove('dragover');
        if (e.dataTransfer.files[0]) {
            const dt = new DataTransfer();
            dt.items.add(e.dataTransfer.files[0]);
            input.files = dt.files;
            input.dispatchEvent(new Event('change'));
        }
    });
}
</script>

<?php require __DIR__ . '/_footer.php'; ?>