<?php
// kpi-calculator.php

// Silent n8n Webhook
$WEBHOOK_URL = "https://n8n.1522irondome.synology.me/webhook/f8a42b8d-28c0-4509-8d79-01118394b221";

function safe_divide($numerator, $denominator) {
    if ($denominator == 0 || $denominator === null || $denominator === '') {
        return null;
    }
    return $numerator / $denominator;
}

$results = null;

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

    // User info
    $name  = isset($_POST['name']) ? trim($_POST['name']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';

    // New Inputs (Context)
    $duration  = isset($_POST['duration']) ? trim($_POST['duration']) : '';
    $campaigns = isset($_POST['campaigns']) ? intval($_POST['campaigns']) : 0;
    $inputCpm  = isset($_POST['inputCpm']) ? floatval($_POST['inputCpm']) : 0;

    // Metrics Inputs
    $adSpend     = isset($_POST['adSpend']) ? floatval($_POST['adSpend']) : 0;
    $impressions = isset($_POST['impressions']) ? floatval($_POST['impressions']) : 0;
    $clicks      = isset($_POST['clicks']) ? floatval($_POST['clicks']) : 0;
    $leads       = isset($_POST['leads']) ? floatval($_POST['leads']) : 0;
    $sales       = isset($_POST['sales']) ? floatval($_POST['sales']) : 0;
    $revenue     = isset($_POST['revenue']) ? floatval($_POST['revenue']) : 0;

    // KPI calculations
    $ctr    = safe_divide($clicks * 100, $impressions);
    $cpc    = safe_divide($adSpend, $clicks);
    $calculatedCpm = safe_divide($adSpend * 1000, $impressions); // Calculated based on spend
    $cpl    = safe_divide($adSpend, $leads);
    $cpa    = safe_divide($adSpend, $sales);
    $roas   = safe_divide($revenue, $adSpend);
    $profit = $revenue - $adSpend;

    $results = [
        'name'        => $name,
        'email'       => $email,
        'duration'    => $duration,
        'campaigns'   => $campaigns,
        'inputCpm'    => $inputCpm,
        'adSpend'     => $adSpend,
        'impressions' => $impressions,
        'clicks'      => $clicks,
        'leads'       => $leads,
        'sales'       => $sales,
        'revenue'     => $revenue,
        'ctr'         => $ctr,
        'cpc'         => $cpc,
        'cpm'         => $calculatedCpm, // We send the calculated true CPM
        'cpl'         => $cpl,
        'cpa'         => $cpa,
        'roas'        => $roas,
        'profit'      => $profit,
        'meta'        => [
            'timestamp' => date('c'),
            'ip'        => $_SERVER['REMOTE_ADDR'] ?? null,
            'userAgent' => $_SERVER['HTTP_USER_AGENT'] ?? null,
        ],
    ];

    // Send silently to webhook
    $payload = json_encode($results);

    $ch = curl_init($WEBHOOK_URL);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Content-Length: ' . strlen($payload)
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_exec($ch);
    curl_close($ch);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ad KPI Calculator | The Secret Matt Show</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <!-- Meta Pixel Code: MOVED TO HEAD to fix Event Setup Tool detection -->
    <script>
    !function(f,b,e,v,n,t,s)
    {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
    n.callMethod.apply(n,arguments):n.queue.push(arguments)};
    if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
    n.queue=[];t=b.createElement(e);t.async=!0;
    t.src=v;s=b.getElementsByTagName(e)[0];
    s.parentNode.insertBefore(t,s)}(window, document,'script',
    'https://connect.facebook.net/en_US/fbevents.js');
    fbq('init', '1388478492261123');
    fbq('track', 'PageView');
    </script>
    <noscript><img height="1" width="1" style="display:none"
    src="https://www.facebook.com/tr?id=1388478492261123&ev=PageView&noscript=1"
    /></noscript>
    <!-- End Meta Pixel Code -->

    <style>
        :root {
            --primary: #2563eb;
            --primary-dark: #1d4ed8;
            --bg: #f3f4f6;
            --card-bg: #ffffff;
            --text-main: #1f2937;
            --text-muted: #6b7280;
            --instagram: linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            background: var(--bg);
            margin: 0;
            padding: 20px 16px;
            color: var(--text-main);
            line-height: 1.5;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: var(--card-bg);
            border-radius: 20px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            overflow: hidden;
        }

        .header {
            background: var(--primary);
            color: white;
            padding: 32px 20px;
            text-align: center;
        }

        h1 {
            margin: 0;
            font-size: 28px;
            font-weight: 700;
            letter-spacing: -0.02em;
        }

        .subtitle {
            margin-top: 8px;
            font-size: 15px;
            opacity: 0.9;
        }

        form {
            padding: 30px 24px;
        }

        .section-label {
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            color: var(--text-muted);
            font-weight: 700;
            margin-bottom: 12px;
            margin-top: 24px;
            border-bottom: 1px solid #e5e7eb;
            padding-bottom: 6px;
        }
        
        .section-label:first-of-type {
            margin-top: 0;
        }

        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
        }

        .field {
            display: flex;
            flex-direction: column;
            gap: 6px;
        }

        label {
            font-size: 14px;
            font-weight: 500;
            color: #374151;
        }

        /* Prevent zoom on mobile by using 16px font */
        input[type="number"], input[type="text"], input[type="email"] {
            padding: 12px;
            border-radius: 8px;
            border: 1px solid #d1d5db;
            font-size: 16px;
            width: 100%;
            box-sizing: border-box;
            transition: border-color 0.2s, box-shadow 0.2s;
            background: #f9fafb;
        }

        input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
            background: #fff;
        }

        .btn-submit {
            margin-top: 32px;
            width: 100%;
            padding: 16px;
            border-radius: 12px;
            border: none;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            background: var(--primary);
            color: #ffffff;
            transition: background 0.2s;
            box-shadow: 0 4px 6px rgba(37, 99, 235, 0.2);
        }

        .btn-submit:hover {
            background: var(--primary-dark);
        }

        /* Results Area */
        .results-container {
            padding: 0 24px 30px;
            animation: fadeIn 0.5s ease-out;
        }

        .insta-cta {
            background: var(--instagram);
            color: white;
            padding: 24px 20px;
            border-radius: 12px;
            text-align: center;
            margin-bottom: 0;
            margin-top: 32px;
            box-shadow: 0 4px 15px rgba(220, 39, 67, 0.25);
        }

        .insta-cta h3 {
            margin: 0 0 8px 0;
            font-size: 20px;
            font-weight: 800;
        }

        .insta-cta p {
            margin: 0 0 20px 0;
            font-size: 15px;
            line-height: 1.5;
            opacity: 0.95;
            max-width: 90%;
            margin-left: auto;
            margin-right: auto;
        }

        .insta-btn {
            display: inline-block;
            background: white;
            color: #cc2366;
            text-decoration: none;
            padding: 12px 24px;
            border-radius: 99px;
            font-weight: 700;
            font-size: 15px;
            transition: transform 0.2s, box-shadow 0.2s;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .insta-btn:hover {
            transform: scale(1.05);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }

        .results-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
            gap: 16px;
        }

        .kpi-card {
            background: #f9fafb;
            border: 1px solid #e5e7eb;
            border-radius: 12px;
            padding: 16px;
            text-align: center;
            transition: transform 0.2s;
        }
        
        .kpi-card:hover {
            transform: translateY(-2px);
            border-color: var(--primary);
        }

        .kpi-label {
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
            color: var(--text-muted);
            letter-spacing: 0.05em;
            margin-bottom: 4px;
        }

        .kpi-value {
            font-size: 20px;
            font-weight: 800;
            color: var(--text-main);
        }
        
        .kpi-desc {
            font-size: 10px;
            color: #9ca3af;
            margin-top: 4px;
        }

        .kpi-card.highlight {
            background: #eff6ff;
            border-color: #bfdbfe;
        }
        
        .kpi-card.highlight .kpi-value {
            color: var(--primary);
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body>

<div class="container">
    <div class="header">
        <h1>Ad KPI Calculator | Matt Makes Money</h1>
        <div class="subtitle">Analyze your campaign performance</div>
    </div>

    <form method="post">
        
        <div class="section-label">Your Details</div>
        <div class="grid">
            <div class="field">
                <label for="name">Name</label>
                <input type="text" id="name" name="name" required placeholder="John Doe"
                       value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''; ?>">
            </div>
            <div class="field">
                <label for="email">Email</label>
                <input type="email" id="email" name="email" required placeholder="john@example.com"
                       value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>">
            </div>
        </div>

        <div class="section-label">Campaign Scope</div>
        <div class="grid">
            <div class="field">
                <label for="duration">Run Duration</label>
                <input type="text" id="duration" name="duration" placeholder="e.g. 2 Weeks"
                       value="<?php echo isset($_POST['duration']) ? htmlspecialchars($_POST['duration']) : ''; ?>">
            </div>
            <div class="field">
                <label for="campaigns"># of Campaigns</label>
                <input type="number" id="campaigns" name="campaigns" placeholder="1"
                       value="<?php echo isset($_POST['campaigns']) ? htmlspecialchars($_POST['campaigns']) : ''; ?>">
            </div>
            <div class="field">
                <label for="inputCpm">Estimated CPM ($)</label>
                <input type="number" step="0.01" id="inputCpm" name="inputCpm" placeholder="Target CPM"
                       value="<?php echo isset($_POST['inputCpm']) ? htmlspecialchars($_POST['inputCpm']) : ''; ?>">
            </div>
        </div>

        <div class="section-label">Performance Metrics</div>
        <div class="grid">
            <div class="field">
                <label for="adSpend">Total Ad Spend ($)</label>
                <input type="number" step="0.01" min="0" id="adSpend" name="adSpend" required
                       value="<?php echo isset($_POST['adSpend']) ? htmlspecialchars($_POST['adSpend']) : ''; ?>">
            </div>
            <div class="field">
                <label for="impressions">Impressions</label>
                <input type="number" step="1" min="0" id="impressions" name="impressions" required
                       value="<?php echo isset($_POST['impressions']) ? htmlspecialchars($_POST['impressions']) : ''; ?>">
            </div>
            <div class="field">
                <label for="clicks">Link Clicks</label>
                <input type="number" step="1" min="0" id="clicks" name="clicks" required
                       value="<?php echo isset($_POST['clicks']) ? htmlspecialchars($_POST['clicks']) : ''; ?>">
            </div>
            <div class="field">
                <label for="leads">Leads Generated</label>
                <input type="number" step="1" min="0" id="leads" name="leads"
                       value="<?php echo isset($_POST['leads']) ? htmlspecialchars($_POST['leads']) : ''; ?>">
            </div>
            <div class="field">
                <label for="sales">Total Sales (Count)</label>
                <input type="number" step="1" min="0" id="sales" name="sales"
                       value="<?php echo isset($_POST['sales']) ? htmlspecialchars($_POST['sales']) : ''; ?>">
            </div>
            <div class="field">
                <label for="revenue">Total Revenue ($)</label>
                <input type="number" step="0.01" min="0" id="revenue" name="revenue"
                       value="<?php echo isset($_POST['revenue']) ? htmlspecialchars($_POST['revenue']) : ''; ?>">
            </div>
        </div>

        <button type="submit" class="btn-submit" id="btn-calculate-kpi" onclick="fbq('track', 'SubmitApplication');">Calculate Results</button>
    </form>

    <?php if ($results !== null): ?>
        <div class="results-container">
            
            <div class="section-label" style="text-align:center; margin-bottom:16px;">Your KPIs</div>

            <div class="results-grid">
                <div class="kpi-card highlight">
                    <div class="kpi-label">ROAS</div>
                    <div class="kpi-value">
                        <?php echo $results['roas'] === null ? 'N/A' : number_format($results['roas'], 2) . 'x'; ?>
                    </div>
                    <div class="kpi-desc">Return on Ad Spend</div>
                </div>

                <div class="kpi-card highlight">
                    <div class="kpi-label">Profit</div>
                    <div class="kpi-value">
                        <?php echo '$' . number_format($results['profit'], 2); ?>
                    </div>
                    <div class="kpi-desc">Revenue - Spend</div>
                </div>

                <div class="kpi-card">
                    <div class="kpi-label">Actual CPM</div>
                    <div class="kpi-value">
                        <?php echo $results['cpm'] === null ? 'N/A' : '$' . number_format($results['cpm'], 2); ?>
                    </div>
                    <div class="kpi-desc">Cost per 1k views</div>
                </div>

                <div class="kpi-card">
                    <div class="kpi-label">CTR</div>
                    <div class="kpi-value">
                        <?php echo $results['ctr'] === null ? 'N/A' : number_format($results['ctr'], 2) . '%'; ?>
                    </div>
                    <div class="kpi-desc">Click-Through Rate</div>
                </div>

                <div class="kpi-card">
                    <div class="kpi-label">CPC</div>
                    <div class="kpi-value">
                        <?php echo $results['cpc'] === null ? 'N/A' : '$' . number_format($results['cpc'], 2); ?>
                    </div>
                    <div class="kpi-desc">Cost per Click</div>
                </div>

                <div class="kpi-card">
                    <div class="kpi-label">CPL</div>
                    <div class="kpi-value">
                        <?php echo $results['cpl'] === null ? 'N/A' : '$' . number_format($results['cpl'], 2); ?>
                    </div>
                    <div class="kpi-desc">Cost per Lead</div>
                </div>

                <div class="kpi-card">
                    <div class="kpi-label">CPA</div>
                    <div class="kpi-value">
                        <?php echo $results['cpa'] === null ? 'N/A' : '$' . number_format($results['cpa'], 2); ?>
                    </div>
                    <div class="kpi-desc">Cost per Sale</div>
                </div>
            </div>

            <!-- Instagram CTA Moved to Bottom -->
            <div class="insta-cta">
                <h3>What's Next?</h3>
                <p>
                    <br>
                    <strong>DM me</strong> a screenshot of these results so I can help diagnose your campaigns and <br><strong>Follow</strong> @thesecretmattshow for more ad help.
                </p>
                <a href="https://www.instagram.com/thesecretmattshow/" target="_blank" class="insta-btn">
                    DM @thesecretmattshow
                </a>
            </div>

        </div>
    <?php endif; ?>
</div>

</body>
</html>