<?php
/**
 * Plugin Name: Shed Agent Rent-to-Own Application
 * Plugin URI:  https://shedagent.com
 * Description: One-page rent-to-own financing application with risk scorecard, CPT storage, and email delivery to help@shedagent.com
 * Version:     1.0.0
 * Author:      Shed Agent
 * License:     GPL-2.0+
 */

if (!defined('ABSPATH')) exit;

// ── Enqueue frontend assets ──────────────────────────────────────────
add_action('wp_enqueue_scripts', function () {
    if (!is_admin() && (is_page() || is_single())) {
        $post = get_post();
        if (has_shortcode($post->post_content, 'shedagent_rent_to_own')) {
            wp_enqueue_script(
                'shedagent-app',
                plugin_dir_url(__FILE__) . 'app.js',
                [],
                '1.0.0',
                true
            );
            wp_localize_script('shedagent-app', 'shedagent_ajax', [
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce'    => wp_create_nonce('shedagent_submit'),
            ]);
            wp_enqueue_style(
                'shedagent-style',
                plugin_dir_url(__FILE__) . 'style.css',
                [],
                '1.0.0'
            );
        }
    }
});

// ── Shortcode ────────────────────────────────────────────────────────
add_shortcode('shedagent_rent_to_own', function () {
    ob_start(); ?>
    <div id="shedagent-app">
        <!-- Form rendered entirely by app.js -->
    </div>
    <?php
    return ob_get_clean();
});

// ── Register CPT for application storage ─────────────────────────────
add_action('init', function () {
    register_post_type('shed_application', [
        'labels'      => [
            'name'          => 'Rent-to-Own Apps',
            'singular_name' => 'Application',
            'menu_name'     => 'Shed Applications',
        ],
        'public'       => false,
        'show_ui'      => true,
        'show_in_menu' => true,
        'menu_icon'    => 'dashicons-clipboard',
        'supports'     => ['title'],
        'capabilities' => ['edit_post' => 'manage_options', 'read_post' => 'manage_options', 'delete_post' => 'manage_options'],
    ]);
});

// ── AJAX handler ──────────────────────────────────────────────────────
add_action('wp_ajax_shedagent_submit', 'shedagent_handle_submit');
add_action('wp_ajax_nopriv_shedagent_submit', 'shedagent_handle_submit');

function shedagent_handle_submit() {
    check_ajax_referer('shedagent_submit', 'nonce');

    $raw = json_decode(file_get_contents('php://input'), true);
    if (!$raw) wp_die('Invalid payload');

    // Sanitize all fields
    $data = [
        'first_name'      => sanitize_text_field($raw['firstName']      ?? ''),
        'last_name'       => sanitize_text_field($raw['lastName']       ?? ''),
        'email'           => sanitize_email($raw['email']               ?? ''),
        'phone'           => sanitize_text_field($raw['phone']          ?? ''),
        'address'         => sanitize_textarea_field($raw['address']    ?? ''),
        'city'            => sanitize_text_field($raw['city']           ?? ''),
        'state'           => sanitize_text_field($raw['state']          ?? ''),
        'zip'             => sanitize_text_field($raw['zip']            ?? ''),
        'employer'        => sanitize_text_field($raw['employer']       ?? ''),
        'job_title'       => sanitize_text_field($raw['jobTitle']       ?? ''),
        'monthly_income'  => floatval($raw['monthlyIncome']             ?? 0),
        'employment_years'=> floatval($raw['employmentYears']           ?? 0),
        'residence_years' => floatval($raw['residenceYears']            ?? 0),
        'landlord_name'   => sanitize_text_field($raw['landlordName']   ?? ''),
        'landlord_phone'  => sanitize_text_field($raw['landlordPhone']  ?? ''),
        'shed_model'      => sanitize_text_field($raw['shedModel']      ?? ''),
        'shed_price'      => floatval($raw['shedPrice']                ?? 0),
        'down_payment'    => floatval($raw['downPayment']               ?? 0),
        'preferred_term'  => intval($raw['preferredTerm']              ?? 36),
        'asset_type'      => sanitize_text_field($raw['assetType']     ?? ''),
        'asset_value'     => floatval($raw['assetValue']               ?? 0),
        'permission_remove'=> !empty($raw['permissionRemove']),
        'signature'       => sanitize_text_field($raw['signature']      ?? ''),
        'agree_terms'     => !empty($raw['agreeTerms']),
    ];

    // ── Server-side risk scorecard ──────────────────────────────────
    $score = 0;
    $reasons = [];

    // Income ratio: monthly payment ≤ 33% of monthly income
    $monthly_payment = $data['down_payment'] > 0
        ? ($data['shed_price'] - $data['down_payment']) / $data['preferred_term']
        : $data['shed_price'] / $data['preferred_term'];

    if ($data['monthly_income'] > 0) {
        $ratio = $monthly_payment / $data['monthly_income'];
        if ($ratio <= 0.20) { $score += 25; }
        elseif ($ratio <= 0.33) { $score += 15; }
        else { $reasons[] = 'Monthly payment exceeds 33% of income'; }
    } else {
        $reasons[] = 'No monthly income provided';
    }

    // Employment stability
    if ($data['employment_years'] >= 3)       { $score += 20; }
    elseif ($data['employment_years'] >= 1)  { $score += 10; }
    else                                      { $reasons[] = 'Less than 1 year at current employer'; }

    // Residence stability
    if ($data['residence_years'] >= 3)        { $score += 15; }
    elseif ($data['residence_years'] >= 1)   { $score += 8; }
    else                                      { $reasons[] = 'Less than 1 year at current residence'; }

    // Down payment
    $dp_pct = $data['shed_price'] > 0 ? ($data['down_payment'] / $data['shed_price']) : 0;
    if ($dp_pct >= 0.20)       { $score += 25; }
    elseif ($dp_pct >= 0.10)   { $score += 15; }
    elseif ($dp_pct >= 0.05)   { $score += 10; }
    else                        { $reasons[] = 'Down payment below 5%'; }

    // Collateral asset
    if ($data['asset_value'] >= $data['shed_price'])       { $score += 15; }
    elseif ($data['asset_value'] >= $data['shed_price'] * 0.5) { $score += 8; }
    else                                                     { $reasons[] = 'Collateral value insufficient'; }

    $approved = $score >= 60;
    $decision = $approved ? 'APPROVED' : 'DENIED';

    // ── Store as CPT ─────────────────────────────────────────────────
    $post_id = wp_insert_post([
        'post_type'   => 'shed_application',
        'post_title'  => $data['first_name'] . ' ' . $data['last_name'] . ' — ' . $decision . ' (' . $score . ' pts)',
        'post_status' => 'publish',
        'meta_input'  => [
            '_shed_data'     => $data,
            '_shed_score'    => $score,
            '_shed_decision' => $decision,
            '_shed_reasons'  => $reasons,
        ],
    ], true);

    if (is_wp_error($post_id)) {
        wp_send_json_error(['message' => 'Failed to save application']);
    }

    // ── Email to help@shedagent.com ──────────────────────────────────
    $subject = 'New Shed RTO Application — ' . $decision . ' (' . $score . ' pts)';

    $body  = "=== SHED RENT-TO-OWN APPLICATION ===\n\n";
    $body .= "Decision: {$decision}  |  Score: {$score}/100\n";
    $body .= str_repeat('-', 40) . "\n\n";
    $body .= "CUSTOMER INFORMATION\n";
    $body .= "Name:    {$data['first_name']} {$data['last_name']}\n";
    $body .= "Email:   {$data['email']}\n";
    $body .= "Phone:   {$data['phone']}\n";
    $body .= "Address: {$data['address']}, {$data['city']}, {$data['state']} {$data['zip']}\n\n";
    $body .= "EMPLOYMENT\n";
    $body .= "Employer:       {$data['employer']}\n";
    $body .= "Job Title:      {$data['job_title']}\n";
    $body .= "Monthly Income: \$" . number_format($data['monthly_income'], 2) . "\n";
    $body .= "Years at Job:   {$data['employment_years']}\n\n";
    $body .= "RESIDENCE\n";
    $body .= "Years at Residence: {$data['residence_years']}\n";
    $body .= "Landlord Name:      {$data['landlord_name']}\n";
    $body .= "Landlord Phone:     {$data['landlord_phone']}\n\n";
    $body .= "SHED DETAILS\n";
    $body .= "Model:        {$data['shed_model']}\n";
    $body .= "Price:        \$" . number_format($data['shed_price'], 2) . "\n";
    $body .= "Down Payment: \$" . number_format($data['down_payment'], 2) . " (" . round($dp_pct * 100) . "%)\n";
    $body .= "Term:         {$data['preferred_term']} months\n";
    $body .= "Monthly Pmt:  \$" . number_format($monthly_payment, 2) . "\n\n";
    $body .= "COLLATERAL\n";
    $body .= "Asset Type:  {$data['asset_type']}\n";
    $body .= "Asset Value: \$" . number_format($data['asset_value'], 2) . "\n\n";
    $body .= "PERMISSIONS\n";
    $body .= "Remove Obstruction Permission: " . ($data['permission_remove'] ? 'YES' : 'NO') . "\n";
    $body .= "Terms Agreed:                 " . ($data['agree_terms'] ? 'YES' : 'NO') . "\n";
    $body .= "Signature:                    {$data['signature']}\n\n";
    if ($reasons) {
        $body .= "SCORECARD NOTES:\n";
        foreach ($reasons as $r) { $body .= "  - {$r}\n"; }
    }
    $body .= "\nView in WP Admin: " . admin_url("post.php?post={$post_id}&action=edit") . "\n";

    $headers = ['Content-Type: text/plain; charset=UTF-8'];

    wp_mail('help@shedagent.com', $subject, $body, $headers);

    // ── Auto-confirmation to applicant ───────────────────────────────
    $cust_subject = 'Your Shed Rent-to-Own Application — ' . $decision;

    $cust_body  = "Hi {$data['first_name']},\n\n";
    $cust_body .= "Thank you for applying for a shed rent-to-own agreement with Shed Agent.\n\n";
    $cust_body .= "Application Result: {$decision}\n";
    $cust_body .= "Risk Score: {$score} / 100\n\n";
    if ($approved) {
        $cust_body .= "Congratulations! Your application has been approved. Our team will contact you shortly to finalize your agreement and schedule delivery.\n";
    } else {
        $cust_body .= "Unfortunately your application did not meet the minimum score threshold at this time. A member of our team will reach out to discuss options — this may include a larger down payment or a co-signer.\n";
    }
    $cust_body .= "\nIf you have questions, reply to this email or call us.\n\n";
    $cust_body .= "— Shed Agent Team\n";

    wp_mail($data['email'], $cust_subject, $cust_body, $headers);

    wp_send_json_success([
        'score'    => $score,
        'decision' => $decision,
        'reasons'  => $reasons,
        'post_id'  => $post_id,
    ]);
}
File 2: app.js
Copy
javascript
(function () {
    'use strict';

    if (document.getElementById('shedagent-app') && !window.__shedagent_loaded) {
        window.__shedagent_loaded = true;
    } else {
        return;
    }

    // ── Render form ──────────────────────────────────────────────────
    const app = document.getElementById('shedagent-app');
    app.innerHTML = `
    <style>
        .sa-form { max-width:720px; margin:0 auto; font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif; }
        .sa-form h2 { margin:24px 0 12px; font-size:1.2rem; border-bottom:2px solid #2563eb; padding-bottom:6px; }
        .sa-row { display:flex; gap:12px; flex-wrap:wrap; }
        .sa-row > * { flex:1 1 200px; }
        .sa-field { margin-bottom:14px; }
        .sa-field label { display:block; font-weight:600; margin-bottom:4px; font-size:0.9rem; }
        .sa-field input, .sa-field select, .sa-field textarea { width:100%; padding:8px 10px; border:1px solid #ccc; border-radius:6px; font-size:0.95rem; box-sizing:border-box; }
        .sa-field textarea { resize:vertical; min-height:60px; }
        .sa-field input:focus, .sa-field select:focus, .sa-field textarea:focus { outline:none; border-color:#2563eb; box-shadow:0 0 0 3px rgba(37,99,235,0.15); }
        .sa-scorecard { background:#f8fafc; border:2px solid #e2e8f0; border-radius:10px; padding:18px; margin:20px 0; text-align:center; }
        .sa-scorecard.pass { border-color:#16a34a; background:#f0fdf4; }
        .sa-scorecard.fail { border-color:#dc2626; background:#fef2f2; }
        .sa-score-big { font-size:2.5rem; font-weight:800; }
        .sa-verdict { font-size:1.1rem; font-weight:700; margin-top:4px; }
        .sa-reasons { list-style:none; padding:0; margin:8px 0 0; font-size:0.85rem; color:#64748b; }
        .sa-submit { background:#2563eb; color:#fff; border:none; padding:14px 32px; font-size:1rem; font-weight:700; border-radius:8px; cursor:pointer; width:100%; }
        .sa-submit:hover { background:#1d4ed8; }
        .sa-submit:disabled { background:#94a3b8; cursor:not-allowed; }
        .sa-msg { margin-top:16px; padding:12px; border-radius:6px; font-weight:600; display:none; }
        .sa-msg.success { background:#dcfce7; color:#166534; display:block; }
        .sa-msg.error { background:#fee2e2; color:#991b1b; display:block; }
        .sa-spinner { display:inline-block; width:18px; height:18px; border:2px solid #fff; border-top-color:transparent; border-radius:50%; animation:sa-spin 0.6s linear infinite; vertical-align:middle; margin-right:8px; }
        @keyframes sa-spin { to { transform:rotate(360deg); } }
    </style>
    <form class="sa-form" id="sa-form">
        <h2>👤 Personal Information</h2>
        <div class="sa-row">
            <div class="sa-field"><label>First Name *</label><input name="firstName" required></div>
            <div class="sa-field"><label>Last Name *</label><input name="lastName" required></div>
        </div>
        <div class="sa-row">
            <div class="sa-field"><label>Email *</label><input name="email" type="email" required></div>
            <div class="sa-field"><label>Phone *</label><input name="phone" type="tel" required></div>
        </div>
        <div class="sa-field"><label>Street Address *</label><input name="address" required></div>
        <div class="sa-row">
            <div class="sa-field"><label>City *</label><input name="city" required></div>
            <div class="sa-field"><label>State *</label><input name="state" required></div>
            <div class="sa-field"><label>ZIP *</label><input name="zip" required></div>
        </div>

        <h2>💼 Employment</h2>
        <div class="sa-row">
            <div class="sa-field"><label>Employer *</label><input name="employer" required></div>
            <div class="sa-field"><label>Job Title</label><input name="jobTitle"></div>
        </div>
        <div class="sa-row">
            <div class="sa-field"><label>Monthly Gross Income ($) *</label><input name="monthlyIncome" type="number" step="0.01" min="0" required></div>
            <div class="sa-field"><label>Years at Employer *</label><input name="employmentYears" type="number" step="0.1" min="0" required></div>
        </div>

        <h2>🏠 Residence History</h2>
        <div class="sa-row">
            <div class="sa-field"><label>Years at Current Residence *</label><input name="residenceYears" type="number" step="0.1" min="0" required></div>
            <div class="sa-field"><label>Landlord / Mortgage Co.</label><input name="landlordName"></div>
        </div>
        <div class="sa-field"><label>Landlord Phone</label><input name="landlordPhone" type="tel"></div>

        <h2>🏚️ Shed Selection</h2>
        <div class="sa-row">
            <div class="sa-field"><label>Shed Model *</label><select name="shedModel" required>
                <option value="">-- Select --</option>
                <option>8×10 Economy</option><option>10×12 Standard</option><option>10×16 Deluxe</option>
                <option>12×20 Premium</option><option>12×24 Grand</option><option>Custom / Other</option>
            </select></div>
            <div class="sa-field"><label>Shed Price ($) *</label><input name="shedPrice" type="number" step="0.01" min="1" required></div>
        </div>
        <div class="sa-row">
            <div class="sa-field"><label>Down Payment ($)</label><input name="downPayment" type="number" step="0.01" min="0" value="0"></div>
            <div class="sa-field"><label>Preferred Term (months)</label><select name="preferredTerm">
                <option value="12">12 mo</option><option value="24">24 mo</option>
                <option value="36" selected>36 mo</option><option value="48">48 mo</option><option value="60">60 mo</option>
            </select></div>
        </div>

        <h2>🔒 Collateral</h2>
        <div class="sa-row">
            <div class="sa-field"><label>Asset Type (vehicle, equipment, etc.)</label><input name="assetType" placeholder="e.g. 2019 Ford F-150"></div>
            <div class="sa-field"><label>Estimated Asset Value ($)</label><input name="assetValue" type="number" step="0.01" min="0" value="0"></div>
        </div>

        <h2>✅ Permissions & Signature</h2>
        <div class="sa-field">
            <label><input type="checkbox" name="permissionRemove" style="width:auto;margin-right:8px;">
            I authorize Shed Agent to remove or relocate objects blocking the shed asset if necessary.</label>
        </div>
        <div class="sa-field"><label>Digital Signature *</label><input name="signature" placeholder="Type your full name" required></div>
        <div class="sa-field">
            <label><input type="checkbox" name="agreeTerms" required style="width:auto;margin-right:8px;">
            I agree to the rent-to-own terms and conditions. *</label>
        </div>

        <!-- Live Scorecard -->
        <div class="sa-scorecard" id="sa-scorecard" style="display:none;">
            <div>Risk Score</div>
            <div class="sa-score-big" id="sa-score-num">0</div>
            <div>/ 100 &nbsp;—&nbsp; <span id="sa-min">60 required</span></div>
            <div class="sa-verdict" id="sa-verdict"></div>
            <ul class="sa-reasons" id="sa-reasons"></ul>
        </div>

        <button type="submit" class="sa-submit" id="sa-submit-btn">Submit Application</button>
        <div class="sa-msg" id="sa-msg"></div>
    </form>
    `;

    // ── Live score preview ───────────────────────────────────────────
    const form         = document.getElementById('sa-form');
    const scorecard    = document.getElementById('sa-scorecard');
    const scoreNum     = document.getElementById('sa-score-num');
    const verdictEl    = document.getElementById('sa-verdict');
    const reasonsEl    = document.getElementById('sa-reasons');
    const msgEl        = document.getElementById('sa-msg');
    const submitBtn    = document.getElementById('sa-submit-btn');

    function calcLiveScore() {
        const fd   = new FormData(form);
        const inc  = parseFloat(fd.get('monthlyIncome'))  || 0;
        const empY = parseFloat(fd.get('employmentYears'))|| 0;
        const resY = parseFloat(fd.get('residenceYears')) || 0;
        const price= parseFloat(fd.get('shedPrice'))       || 0;
        const dp   = parseFloat(fd.get('downPayment'))     || 0;
        const term = parseInt(fd.get('preferredTerm'))     || 36;
        const av   = parseFloat(fd.get('assetValue'))      || 0;

        let score = 0;
        const reasons = [];

        const monthly = price > 0 ? ((price - dp) / term) : 0;
        if (inc > 0) {
            const ratio = monthly / inc;
            if (ratio <= 0.20) score += 25;
            else if (ratio <= 0.33) score += 15;
            else reasons.push('Payment-to-income ratio too high');
        } else { reasons.push('Enter monthly income'); }

        if (empY >= 3) score += 20;
        else if (empY >= 1) score += 10;
        else if (empY > 0) reasons.push('Under 1 year employment');

        if (resY >= 3) score += 15;
        else if (resY >= 1) score += 8;
        else if (resY > 0) reasons.push('Under 1 year residence');

        const dpPct = price > 0 ? (dp / price) : 0;
        if (dpPct >= 0.20) score += 25;
        else if (dpPct >= 0.10) score += 15;
        else if (dpPct >= 0.05) score += 10;
        else if (price > 0) reasons.push('Down payment under 5%');

        if (av >= price) score += 15;
        else if (av >= price * 0.5) score += 8;
        else if (price > 0 && av > 0) reasons.push('Low collateral value');

        return { score, reasons, pass: score >= 60 };
    }

    // Update live card on any change
    form.addEventListener('input', () => {
        const { score, reasons, pass } = calcLiveScore();
        scoreNum.textContent = score;
        scorecard.classList.remove('pass', 'fail');
        if (score >= 60) scorecard.classList.add('pass');
        else if (score > 0) scorecard.classList.add('fail');

        verdictEl.textContent = pass ? '✅ Likely Approved' : (score > 0 ? '❌ Below Threshold' : '');
        verdictEl.style.color = pass ? '#16a34a' : '#dc2626';

        reasonsEl.innerHTML = reasons.map(r => `<li>• ${r}</li>`).join('');
        scorecard.style.display = score > 0 ? '' : 'none';
    });

    // ── Submit handler ───────────────────────────────────────────────
    form.addEventListener('submit', async (e) => {
        e.preventDefault();
        msgEl.className = 'sa-msg';
        msgEl.style.display = 'none';
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="sa-spinner"></span>Submitting...';

        const fd = new FormData(form);
        const payload = Object.fromEntries(fd.entries());
        // Convert checkboxes
        payload.permissionRemove = form.querySelector('[name="permissionRemove"]').checked;
        payload.agreeTerms = form.querySelector('[name="agreeTerms"]').checked;

        try {
            const res = await fetch(shedagent_ajax.ajax_url, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ ...payload, nonce: shedagent_ajax.nonce, action: 'shedagent_submit' }),
            });
            const json = await res.json();

            if (json.success) {
                const d = json.data;
                msgEl.className = 'sa-msg ' + (d.decision === 'APPROVED' ? 'success' : 'error');
                msgEl.innerHTML = `
                    <strong>${d.decision}</strong> — Score: ${d.score}/100<br>
                    A confirmation email has been sent to your address. Our team will contact you shortly.
                `;
                msgEl.style.display = 'block';
                form.style.display = 'none';
            } else {
                msgEl.className = 'sa-msg error';
                msgEl.textContent = json.data?.message || 'Submission failed. Please try again.';
                msgEl.style.display = 'block';
            }
        } catch (err) {
            msgEl.className = 'sa-msg error';
            msgEl.textContent = 'Network error. Please check your connection and try again.';
            msgEl.style.display = 'block';