<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /templates/setup.php
// Description: Setup tab -- onboarding steps, activation, channel connection -- NUCLEAR+++
// Last Edited: 2026-05-23
// ==================================================
if (!defined('ABSPATH')) {
    exit;
}

$is_inactive   = ($license_status === 'inactive' || $license_status === 'deactivated');
$is_free       = ($license_status === 'free');
$is_paid       = ($license_status === 'active');
$has_license   = !$is_inactive;
$has_ai        = ($active_ai_count > 0);
$current_plan  = get_option('automarketer_ai_plan_id', 'free');

// Business profile state
$bp              = new \AutoMarketerAI\BusinessProfile();
$profile_row     = $bp->get();
$has_profile     = is_array($profile_row)
    && trim((string) ($profile_row['business_category'] ?? '')) !== ''
    && trim((string) ($profile_row['differentiator'] ?? '')) !== '';
$profile_category     = is_array($profile_row) ? (string) ($profile_row['business_category'] ?? '') : '';
$profile_differentiator = is_array($profile_row) ? (string) ($profile_row['differentiator'] ?? '') : '';

// Facebook connection state
$fb_connection = \AutoMarketerAI\FacebookAuth::getConnection();
$has_facebook  = $fb_connection !== null;
$fb_page_name  = $has_facebook ? esc_html((string) ($fb_connection['page_name'] ?? '')) : '';

$plan_labels = [
    'free'         => 'Free Plan',
    'starter'      => 'Starter',
    'starter_pro'  => 'Starter Pro',
    'unlimited_ai' => 'Unlimited AI',
    'agency'       => 'Agency',
];
$plan_label = $plan_labels[$current_plan] ?? ucfirst($current_plan);

// Setup state -- drive the hero copy
// Steps: 1=Plan, 2=Profile, 3=AI, 4=Facebook
if ($is_inactive) {
    $setup_state = 'inactive';
} elseif (!$has_profile) {
    $setup_state = 'need_profile';
} elseif (!$has_ai) {
    $setup_state = 'ready_for_ai';
} elseif (!$has_facebook) {
    $setup_state = 'ready_for_fb';
} else {
    $setup_state = 'all_done';
}
?>

<!-- PAGE HEADER -->
<div id="amai-setup-header">
    <div class="amai-setup-title">Setup</div>
    <p class="amai-setup-sub">Get AutoMarketer AI connected and ready to post</p>
    <?php include AMAI_PLUGIN_DIR . 'templates/partials/tabs.php'; ?>
</div>

<div id="amai-setup">

    <!-- HERO -->

    <?php if ($setup_state === 'inactive'): ?>
        <div class="am-setup-hero">
            <div class="am-setup-eyebrow">Welcome to AutoMarketer AI</div>
            <h2 class="am-setup-hero-title">Built fair. Priced fair.<br>Does the heavy lifting so you don't have to.</h2>
            <button class="am-setup-cta" id="am-open-license-modal">Get started free - no card needed</button>
            <span class="am-setup-cta-sub">Free forever &nbsp;&middot;&nbsp; Upgrade anytime</span>
        </div>

    <?php elseif ($setup_state === 'need_profile'): ?>
        <div class="am-setup-hero is-active">
            <div class="am-setup-eyebrow">You're in - let's get you set up</div>
            <h2 class="am-setup-hero-title">First, tell us about your business.</h2>
            <p class="am-setup-hero-desc">The more we know about what you do and what makes you different, the better your posts will sound. Takes about two minutes.</p>
        </div>

    <?php elseif ($setup_state === 'ready_for_ai'): ?>
        <div class="am-setup-hero is-active">
            <div class="am-setup-eyebrow">Profile saved - next step</div>
            <h2 class="am-setup-hero-title">Now pick your AI.</h2>
            <p class="am-setup-hero-desc">Choose which AI provider you want to use. Each one runs on your own API key so you stay in control of your data and costs. Not sure which? Start with Claude.</p>
            <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-modules&from=setup')); ?>" class="am-setup-cta am-setup-cta--green">Choose your AI &rarr;</a>
        </div>

    <?php elseif ($setup_state === 'ready_for_fb'): ?>
        <div class="am-setup-hero is-active">
            <div class="am-setup-eyebrow">AI is ready - one more step</div>
            <h2 class="am-setup-hero-title">Now let's connect Facebook.</h2>
            <p class="am-setup-hero-desc">Your AI provider is all set. Connect your Facebook Business Page and we'll start writing and scheduling posts for you - Monday through Friday, every week.</p>
            <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-social&channel=facebook')); ?>" class="am-setup-cta am-setup-cta--green">Connect Facebook &rarr;</a>
        </div>

    <?php else:
        $has_instagram   = \AutoMarketerAI\FacebookAuth::getInstagramAccountId() !== null;
        $channel_phrase  = ($has_facebook && $has_instagram)
            ? 'Your Facebook and Instagram are connected.'
            : ($has_instagram ? 'Your Instagram is connected.' : 'Your Facebook page is connected.');
        $dashboard_url   = ($has_instagram && !$has_facebook)
            ? admin_url('admin.php?page=automarketer-ai-social&channel=instagram')
            : admin_url('admin.php?page=automarketer-ai-social&channel=facebook');
        $dashboard_label = ($has_instagram && !$has_facebook)
            ? 'Go to your Instagram dashboard &rarr;'
            : 'Go to your Facebook dashboard &rarr;';
    ?>
        <div class="am-setup-hero is-active">
            <div class="am-setup-eyebrow">Setup complete</div>
            <h2 class="am-setup-hero-title">You're all set.</h2>
            <p class="am-setup-hero-desc">Your AI is writing. <?php echo esc_html($channel_phrase); ?> Posts go out every weekday. Approve each one or let it run on autopilot.</p>
            <a href="<?php echo esc_url($dashboard_url); ?>" class="am-setup-cta am-setup-cta--green"><?php echo $dashboard_label; ?></a>
        </div>
    <?php endif; ?>

    <!-- STEPS -->
    <div class="am-setup-steps">

        <!-- STEP 1: PLAN -->
        <div class="am-setup-step <?php echo $has_license ? 'is-done' : ''; ?>">
            <div class="am-setup-step-num"><?php echo $has_license ? '&#10003;' : '1'; ?></div>
            <div class="am-setup-step-title"><?php echo $has_license ? 'Plan activated' : 'Activate your plan'; ?></div>
            <div class="am-setup-step-desc">
                <?php echo $has_license
                    ? 'You\'re on the ' . esc_html($plan_label) . '.'
                    : 'Start free - no credit card, no catch. Takes about 30 seconds.'; ?>
            </div>
            <?php if (!$has_license): ?>
                <button class="am-setup-step-link am-btn-reset" id="am-open-license-modal-2">Get started free &rarr;</button>
            <?php endif; ?>
        </div>

        <!-- STEP 2: BUSINESS PROFILE -->
        <div class="am-setup-step <?php echo (!$has_license) ? 'is-locked' : ($has_profile ? 'is-done' : 'is-active-step'); ?>">
            <div class="am-setup-step-num">
                <?php if (!$has_license): ?>
                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none"><rect x="2" y="5.5" width="9" height="6.5" rx="1.5" stroke="currentColor" stroke-width="1.3"/><path d="M4.5 5.5V3.5a2 2 0 014 0v2" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg>
                <?php elseif ($has_profile): ?>
                    &#10003;
                <?php else: ?>
                    2
                <?php endif; ?>
            </div>
            <div class="am-setup-step-title"><?php echo $has_profile ? 'Business profile saved' : 'Tell us about your business'; ?></div>
            <div class="am-setup-step-desc">
                <?php if ($has_profile): ?>
                    Your profile is saved. Your AI knows what to write about.
                <?php elseif (!$has_license): ?>
                    We'll use this to write posts that actually sound like you.
                <?php else: ?>
                    Two quick questions and your AI will know exactly what to write. No fluff, just what matters.
                <?php endif; ?>
            </div>
            <?php if (!$has_license): ?>
                <span class="am-setup-step-lock-badge">Complete step 1 first</span>
            <?php elseif ($has_profile): ?>
                <button type="button" class="am-setup-step-link am-btn-reset" id="am-profile-edit-btn">Edit profile &rarr;</button>
            <?php endif; ?>

            <?php if ($has_license && !$has_profile): ?>
            <div class="am-setup-profile-form" id="am-setup-profile-form">
                <div class="am-spf-error" id="am-spf-error" style="display:none;"></div>
                <div class="am-spf-field">
                    <label class="am-spf-label" for="am-spf-category">What kind of business do you run? <span class="am-required">*</span></label>
                    <select class="am-spf-select" id="am-spf-category" name="business_category">
                        <option value="">-- Pick the closest match --</option>
                        <?php foreach (\AutoMarketerAI\BusinessProfile::BUSINESS_CATEGORIES as $val => $label): ?>
                            <option value="<?php echo esc_attr($val); ?>" <?php selected($profile_category, $val); ?>><?php echo esc_html($label); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="am-spf-field">
                    <label class="am-spf-label" for="am-spf-differentiator">What makes your business different? <span class="am-required">*</span></label>
                    <textarea class="am-spf-textarea" id="am-spf-differentiator" name="differentiator" rows="3" placeholder="e.g. We're the only family-owned bakery in town that sources everything locally and still uses my grandmother's recipes."><?php echo esc_textarea($profile_differentiator); ?></textarea>
                    <div class="am-spf-hint">Be specific. The AI uses this directly when writing your posts.</div>
                </div>
                <button type="button" class="am-spf-submit" id="am-spf-submit">Save and continue &rarr;</button>
            </div>
            <?php endif; ?>

            <?php if ($has_license && $has_profile): ?>
            <div class="am-setup-profile-form" id="am-setup-profile-form" style="display:none;">
                <div class="am-spf-error" id="am-spf-error" style="display:none;"></div>
                <div class="am-spf-field">
                    <label class="am-spf-label" for="am-spf-category">What kind of business do you run? <span class="am-required">*</span></label>
                    <select class="am-spf-select" id="am-spf-category" name="business_category">
                        <option value="">-- Pick the closest match --</option>
                        <?php foreach (\AutoMarketerAI\BusinessProfile::BUSINESS_CATEGORIES as $val => $label): ?>
                            <option value="<?php echo esc_attr($val); ?>" <?php selected($profile_category, $val); ?>><?php echo esc_html($label); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="am-spf-field">
                    <label class="am-spf-label" for="am-spf-differentiator">What makes your business different? <span class="am-required">*</span></label>
                    <textarea class="am-spf-textarea" id="am-spf-differentiator" name="differentiator" rows="3" placeholder="e.g. We're the only family-owned bakery in town that sources everything locally and still uses my grandmother's recipes."><?php echo esc_textarea($profile_differentiator); ?></textarea>
                    <div class="am-spf-hint">Be specific. The AI uses this directly when writing your posts.</div>
                </div>
                <div class="am-spf-actions">
                    <button type="button" class="am-spf-submit" id="am-spf-submit">Save changes &rarr;</button>
                    <button type="button" class="am-spf-cancel am-btn-reset" id="am-profile-cancel-btn">Cancel</button>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- STEP 3: AI PROVIDER -->
        <div class="am-setup-step <?php echo (!$has_license || !$has_profile) ? 'is-locked' : ($has_ai ? 'is-done' : ''); ?>">
            <div class="am-setup-step-num">
                <?php if (!$has_license || !$has_profile): ?>
                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none"><rect x="2" y="5.5" width="9" height="6.5" rx="1.5" stroke="currentColor" stroke-width="1.3"/><path d="M4.5 5.5V3.5a2 2 0 014 0v2" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg>
                <?php elseif ($has_ai): ?>
                    &#10003;
                <?php else: ?>
                    3
                <?php endif; ?>
            </div>
            <div class="am-setup-step-title"><?php echo $has_ai ? 'AI provider connected' : 'Choose your AI'; ?></div>
            <div class="am-setup-step-desc">
                <?php echo $has_ai
                    ? 'Your AI provider is ready to write your content.'
                    : 'Connect Claude, Gemini, Grok, or OpenAI using your own API key - you keep full control.'; ?>
            </div>
            <?php if (!$has_license || !$has_profile): ?>
                <span class="am-setup-step-lock-badge">Complete step 2 first</span>
            <?php elseif ($has_ai): ?>
                <a class="am-setup-step-link" href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-modules')); ?>">Go to Modules &rarr;</a>
            <?php else: ?>
                <a class="am-setup-step-link" href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-modules&from=setup')); ?>">Choose your AI &rarr;</a>
            <?php endif; ?>
        </div>

        <!-- STEP 4: FACEBOOK -->
        <div class="am-setup-step <?php echo (!$has_license || !$has_profile || !$has_ai) ? 'is-locked' : ($has_facebook ? 'is-done' : ''); ?>">
            <div class="am-setup-step-num">
                <?php if (!$has_license || !$has_profile || !$has_ai): ?>
                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none"><rect x="2" y="5.5" width="9" height="6.5" rx="1.5" stroke="currentColor" stroke-width="1.3"/><path d="M4.5 5.5V3.5a2 2 0 014 0v2" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg>
                <?php elseif ($has_facebook): ?>
                    &#10003;
                <?php else: ?>
                    4
                <?php endif; ?>
            </div>
            <div class="am-setup-step-title">
                <?php
                $has_ig_step = \AutoMarketerAI\FacebookAuth::getInstagramAccountId() !== null;
                if ($has_facebook && $has_ig_step):
                    echo 'Facebook &amp; Instagram connected';
                elseif ($has_facebook):
                    echo 'Facebook connected';
                else:
                    echo 'Connect Facebook';
                endif;
                ?>
            </div>
            <div class="am-setup-step-desc">
                <?php if ($has_facebook && $has_ig_step): ?>
                    Posts are going out on Facebook and Instagram every weekday.
                <?php elseif ($has_facebook): ?>
                    Posts are going out on <?php echo esc_html($fb_page_name); ?> every weekday.
                <?php else: ?>
                    Connect your Facebook Business Page and we'll write and schedule your posts every weekday.
                <?php endif; ?>
            </div>
            <?php if (!$has_license || !$has_profile || !$has_ai): ?>
                <span class="am-setup-step-lock-badge">Complete step 3 first</span>
            <?php elseif ($has_facebook): ?>
                <a class="am-setup-step-link" href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-social&channel=facebook')); ?>">Go to dashboard &rarr;</a>
            <?php else: ?>
                <a class="am-setup-step-link" href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-social&channel=facebook')); ?>">Connect Facebook &rarr;</a>
            <?php endif; ?>
        </div>

    </div>

    <div class="am-setup-reset-wrap">
        <button type="button" id="am-setup-reset-btn" class="am-setup-reset-link">Reset setup checklist</button>
    </div>
</div><!-- /#amai-setup -->

<!-- LICENSE ACTIVATION MODAL -->
<?php if ($is_inactive): ?>
<div id="amai-license-modal">
    <div class="am-lic-wrap">
        <div class="am-lic-header">
            <div>
                <div class="am-lic-eyebrow">Free Plan</div>
                <div class="am-lic-title">Let's get you started</div>
            </div>
            <button class="am-lic-close" id="am-lic-close">&#10005;</button>
        </div>
        <div class="am-lic-body">
            <div class="am-lic-error" id="am-lic-error"></div>
            <div class="am-lic-privacy">
                We'll send you the occasional tip to help you get more out of AutoMarketer AI.
            </div>
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" id="am-lic-form">
                <input type="hidden" name="action" value="amai_activate_free_license">
                <?php wp_nonce_field('amai_activate_free_license', '_wpnonce'); ?>
                <div class="am-lic-field">
                    <label class="am-lic-label" for="am-first-name">First Name <span class="am-required">*</span></label>
                    <input type="text" class="am-lic-input" name="first_name" id="am-first-name" placeholder="Your first name">
                </div>
                <div class="am-lic-field">
                    <label class="am-lic-label" for="am-email">Email Address <span class="am-required">*</span></label>
                    <input type="email" class="am-lic-input" name="email" id="am-email" placeholder="you@example.com">
                </div>
                <div class="am-lic-consent">
                    <input type="checkbox" name="consent" id="am-consent">
                    <label for="am-consent">Send me occasional tips and product updates.</label>
                </div>
            </form>
        </div>
        <div class="am-lic-footer">
            <button class="am-lic-btn-cancel" id="am-lic-cancel">Maybe later</button>
            <button class="am-lic-btn-submit" id="am-lic-submit">Activate Free Plan &rarr;</button>
        </div>
    </div>
</div>
<?php endif; ?>

<script>
(function() {
    var ajaxUrl = window.ajaxurl || '<?php echo esc_js(admin_url('admin-ajax.php')); ?>';
    var nonce   = '<?php echo esc_js(wp_create_nonce('amai_setup_profile')); ?>';

    // Profile edit toggle (when profile is already saved)
    var editBtn   = document.getElementById('am-profile-edit-btn');
    var cancelBtn = document.getElementById('am-profile-cancel-btn');
    var form      = document.getElementById('am-setup-profile-form');

    if (editBtn && form) {
        editBtn.addEventListener('click', function() {
            form.style.display = 'block';
            editBtn.style.display = 'none';
        });
    }
    if (cancelBtn && form && editBtn) {
        cancelBtn.addEventListener('click', function() {
            form.style.display = 'none';
            editBtn.style.display = '';
        });
    }

    // Profile form save
    var submitBtn = document.getElementById('am-spf-submit');
    if (submitBtn) {
        submitBtn.addEventListener('click', function() {
            var category       = document.getElementById('am-spf-category');
            var differentiator = document.getElementById('am-spf-differentiator');
            var errorBox       = document.getElementById('am-spf-error');

            if (!category || !differentiator) {
                return;
            }

            errorBox.style.display = 'none';
            errorBox.textContent   = '';

            if (category.value === '' || differentiator.value.trim() === '') {
                errorBox.textContent   = 'Please fill in both fields before continuing.';
                errorBox.style.display = 'block';
                return;
            }

            submitBtn.disabled      = true;
            submitBtn.textContent   = 'Saving...';

            var fd = new FormData();
            fd.append('action',            'amai_save_setup_profile');
            fd.append('_ajax_nonce',       nonce);
            fd.append('business_category', category.value);
            fd.append('differentiator',    differentiator.value.trim());

            fetch(ajaxUrl, { method: 'POST', body: fd })
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    if (data.success) {
                        window.location.reload();
                    } else {
                        var msg = (data.data && data.data.message) ? data.data.message : 'Save failed. Please try again.';
                        errorBox.textContent   = msg;
                        errorBox.style.display = 'block';
                        submitBtn.disabled     = false;
                        submitBtn.textContent  = 'Save and continue \u2192';
                    }
                })
                .catch(function() {
                    errorBox.textContent   = 'Connection error. Please try again.';
                    errorBox.style.display = 'block';
                    submitBtn.disabled     = false;
                    submitBtn.textContent  = 'Save and continue \u2192';
                });
        });
    }
})();
</script>