<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $vertical = htmlspecialchars(trim($_POST['vertical'] ?? $_POST['category'] ?? 'General Dispatch'));
    $name = htmlspecialchars(trim($_POST['name'] ?? 'Maryland Resident'));
    $phone = htmlspecialchars(trim($_POST['phone'] ?? ''));
    $email = htmlspecialchars(trim($_POST['email'] ?? ''));
    $zip = htmlspecialchars(trim($_POST['zip'] ?? $_POST['county'] ?? 'MD'));
    $role = htmlspecialchars(trim($_POST['role'] ?? 'Homeowner Lead'));
    $notes = htmlspecialchars(trim($_POST['notes'] ?? $_POST['description'] ?? ''));
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';

    // 1. Log to MDTaskForce SQLite DB
    try {
        $db = new PDO('sqlite:/var/www/databases/mdtaskforce.sqlite');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db->exec("CREATE TABLE IF NOT EXISTS leads (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
            vertical TEXT,
            name TEXT,
            phone TEXT,
            email TEXT,
            zip_code TEXT,
            status TEXT DEFAULT 'NEW',
            ip_address TEXT
        )");
        $stmt = $db->prepare("INSERT INTO leads (vertical, name, phone, email, zip_code, status, ip_address) VALUES (:vertical, :name, :phone, :email, :zip, :role, :ip)");
        $stmt->execute([
            ':vertical' => $vertical . ($notes ? " | " . $notes : ""),
            ':name' => $name,
            ':phone' => $phone,
            ':email' => $email,
            ':zip' => $zip,
            ':role' => $role,
            ':ip' => $ip
        ]);
    } catch (Exception $e) {}

    // 2. Log to Unified Fan & Community Infrastructure DB
    try {
        $fdb = new PDO('sqlite:/var/www/shared/noobo_unified_fan_infrastructure.sqlite');
        $fdb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $fstmt = $fdb->prepare("INSERT INTO unified_fan_members (full_name, email, phone, source_domain, member_role, county_or_zip, vertical_or_interest, notes, ip_address) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $fstmt->execute([$name, $email, $phone, $_SERVER['HTTP_HOST'] ?? 'mdtaskforce.com', $role, $zip, $vertical, $notes, $ip]);
    } catch (Exception $e) {}

    // 3. Send Email Notification
    $to = 'icodiaq@me.com, outreach@noobogroup.org';
    $subject = "🦀 [MD TASK FORCE - $role] $vertical in $zip ($name)";
    $message = "=== MARYLAND TASK FORCE & FAN INFRASTRUCTURE ALERT ===\n\n" .
               "ROLE:      $role\n" .
               "VERTICAL:  $vertical\n" .
               "COUNTY/ZIP:$zip\n" .
               "NAME:      $name\n" .
               "PHONE:     $phone\n" .
               "EMAIL:     $email\n" .
               "NOTES:     $notes\n" .
               "IP:        $ip\n";
    $headers = "From: MD-TaskForce Dispatch <outreach@noobogroup.org>\r\n";
    @mail($to, $subject, $message, $headers);

    if (!empty($_POST['redirect'])) {
        header("Location: " . $_POST['redirect']);
        exit();
    }
    echo json_encode(["status" => "success", "message" => "Captured in Maryland Task Force & Unified Fan Ledger"]);
    exit();
}
echo json_encode(["status" => "ready"]);
?>