<?php
// sales/webhook.php - Stripe Webhook receiver to process payments and generate licenses
require_once __DIR__ . '/config.php';

$payload = file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';

// 1. Signature Verification Helper (Pure PHP HMAC-SHA256)
function verify_stripe_signature($payload, $sig_header, $secret) {
    if (empty($sig_header) || empty($secret) || $secret === 'whsec_CHANGE_ME_AFTER_CREATING_WEBHOOK') {
        return false;
    }
    
    $parts = explode(',', $sig_header);
    $t = '';
    $v1 = '';
    foreach ($parts as $part) {
        $subparts = explode('=', $part, 2);
        if (count($subparts) === 2) {
            if (trim($subparts[0]) === 't') $t = trim($subparts[1]);
            if (trim($subparts[0]) === 'v1') $v1 = trim($subparts[1]);
        }
    }
    
    if (empty($t) || empty($v1)) return false;
    
    // Prevent replay attacks (5 minute threshold)
    if (abs(time() - intval($t)) > 300) return false;
    
    $signed_payload = $t . '.' . $payload;
    $expected_signature = hash_hmac('sha256', $signed_payload, $secret);
    
    return hash_equals($expected_signature, $v1);
}

// 2. Email Helper (sends actual email & writes to local backup log)
function send_email($to, $subject, $body) {
    // Local backup log
    $log_dir = __DIR__ . '/data';
    if (!file_exists($log_dir)) {
        mkdir($log_dir, 0777, true);
    }
    file_put_contents($log_dir . '/emails.log', "[EMAIL TO $to] " . date('Y-m-d H:i:s') . "\nSubject: $subject\n" . $body . "\n\n", FILE_APPEND);

    // Actual PHP Mail
    $headers = "From: Team Mania <noreply@team-mania.de>\r\n" .
               "Reply-To: support@team-mania.de\r\n" .
               "Content-Type: text/plain; charset=UTF-8\r\n" .
               "X-Mailer: PHP/" . phpversion();
               
    return @mail($to, $subject, $body, $headers);
}

// Check signature
if (!verify_stripe_signature($payload, $sig_header, STRIPE_WEBHOOK_SECRET)) {
    http_response_code(400);
    echo json_encode(['error' => 'Ungültige Webhook-Signatur']);
    exit;
}

$event = json_decode($payload, true);
$event_type = $event['type'] ?? '';

if ($event_type === 'checkout.session.completed') {
    $session = $event['data']['object'] ?? [];
    $meta = $session['metadata'] ?? [];
    $type = $meta['type'] ?? '';
    
    $email = $session['customer_details']['email'] ?? ($meta['email'] ?? '');
    $total_amount = floatval($session['amount_total'] ?? 0) / 100;
    
    try {
        if ($type === 'core_license') {
            $club_name = $meta['club_name'] ?? 'Musterverein';
            $max_members = intval($meta['max_members'] ?? 50);
            
            // Generate Core License Key
            $license_key = 'TMP-CORE-' . strtoupper(bin2hex(random_bytes(6)));
            
            $stmt = $sales_pdo->prepare("INSERT INTO licenses (license_key, club_name, email, max_members, modules) VALUES (:key, :club, :email, :max, '[]')");
            $stmt->execute([
                ':key' => $license_key,
                ':club' => $club_name,
                ':email' => $email,
                ':max' => $max_members
            ]);
            
            // Save generated key to session for success page fallback
            $_SESSION['new_license_key'] = $license_key;
            
            // Send License Email (Actual mail + backup log)
            $subject = "Ihr Team Mania PRO Lizenzschlüssel";
            $mail_content = "Hallo Vorstand von $club_name,\n\n"
                          . "Vielen Dank für Ihre Bestellung von Team Mania PRO!\n"
                          . "Ihr monatliches Grundabo für bis zu $max_members Mitglieder wurde erfolgreich aktiviert.\n\n"
                          . "Ihr Lizenzschlüssel: $license_key\n\n"
                          . "Tragen Sie diesen Schlüssel bei der Installation ein.\n\n"
                          . "Viele Grüße,\nIhr Team von team-mania.de";
            send_email($email, $subject, $mail_content);
            
        } elseif ($type === 'addon_license') {
            $club_name = $meta['club_name'] ?? 'Musterverein';
            $addon_name = $meta['addon_name'] ?? '';
            
            // Generate Addon License Key (TMP-FORUM-... or TMP-PLAYRIGHT-...)
            $prefix = ($addon_name === 'forum') ? 'TMP-FORUM-' : 'TMP-PLAYRIGHT-';
            $license_key = $prefix . strtoupper(bin2hex(random_bytes(6)));
            
            $stmt = $sales_pdo->prepare("INSERT INTO licenses (license_key, club_name, email, max_members, modules) VALUES (:key, :club, :email, 999999, :modules)");
            $stmt->execute([
                ':key' => $license_key,
                ':club' => $club_name,
                ':email' => $email,
                ':modules' => json_encode([$addon_name])
            ]);
            
            $_SESSION['new_license_key'] = $license_key;
            
            // Send Addon License Email (Actual mail + backup log)
            $subject = "Ihr Zusatzmodul '$addon_name' wurde freigeschaltet";
            $mail_content = "Hallo Vorstand von $club_name,\n\n"
                          . "Ihr Zusatzmodul '$addon_name' für Team Mania PRO wurde erfolgreich bezahlt.\n\n"
                          . "Lizenzschlüssel zur Freischaltung: $license_key\n\n"
                          . "Tragen Sie diesen Schlüssel im Adminbereich unter Lizenzen ein.\n\n"
                          . "Viele Grüße,\nIhr Team von team-mania.de";
            send_email($email, $subject, $mail_content);

        } elseif ($type === 'clothing_order') {
            // Save clothing order details
            // Fetch session items (Stripe line items require API query to get full details)
            $ch = curl_init("https://api.stripe.com/v1/checkout/sessions/" . $session['id'] . "/line_items");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_USERPWD, STRIPE_SECRET_KEY . ':');
            $res = curl_exec($ch);
            curl_close($ch);
            
            $items_list = [];
            $res_arr = json_decode($res, true);
            if (isset($res_arr['data'])) {
                foreach ($res_arr['data'] as $item) {
                    $items_list[] = [
                        'name' => $item['description'],
                        'qty' => $item['quantity'],
                        'price' => $item['amount_total'] / 100
                    ];
                }
            }
            
            $stmt = $sales_pdo->prepare("INSERT INTO clothing_orders (stripe_session_id, email, item_details, total_amount) VALUES (:session, :email, :details, :total)");
            $stmt->execute([
                ':session' => $session['id'],
                ':email' => $email,
                ':details' => json_encode($items_list),
                ':total' => $total_amount
            ]);
            
            // Send Order Confirmation Email (Actual mail + backup log)
            $subject = "Bestellbestätigung - Vereinskleidung";
            $mail_content = "Hallo Admin,\n\nVielen Dank für Ihre Vereinskleidungs-Bestellung!\n\n"
                          . "Bestellte Artikel:\n";
            foreach ($items_list as $it) {
                $mail_content .= "- " . $it['name'] . " (Menge: " . $it['qty'] . ") - " . number_format($it['price'], 2, ',', '.') . " €\n";
            }
            $mail_content .= "\nGesamtbetrag: " . number_format($total_amount, 2, ',', '.') . " € (Bezahlt via Stripe)\n\n"
                           . "Die Bestellung wird an unseren On-Demand-Partner zur Produktion übermittelt.\n\n"
                           . "Viele Grüße,\nIhr Team von team-mania.de";
            send_email($email, $subject, $mail_content);
        }
    } catch (Exception $e) {
        // Log database/file failures
        file_put_contents(__DIR__ . '/data/errors.log', date('Y-m-d H:i:s') . " - Webhook Error: " . $e->getMessage() . "\n", FILE_APPEND);
    }
}

http_response_code(200);
echo json_encode(['status' => 'success']);
