<?php
// test-event.php - manually inserts a fake lead to test dashboard/DB

ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/config.php';

// simple env helper
function envv($k, $d = null) {
    $v = getenv($k);
    if ($v === false) return $d;
    return $v;
}

// DB config
$DB_HOST = envv('DB_HOST', 'localhost');
$DB_PORT = (int)envv('DB_PORT', 3306);
$DB_NAME = envv('DB_NAME', 'servicedirect');
$DB_USER = envv('DB_USER', 'servicedirect');
$DB_PASS = envv('DB_PASS', '');

$LOG_DIR    = envv('LOG_PATH', __DIR__ . '/logs/');
$EVENTS_DIR = envv('EVENTS_DIR', __DIR__ . '/events/');

if (!is_dir($LOG_DIR)) @mkdir($LOG_DIR, 0755, true);
if (!is_dir($EVENTS_DIR)) @mkdir($EVENTS_DIR, 0755, true);
$LOG_FILE = rtrim($LOG_DIR, '/\\') . '/webhook.log';

function tlog($msg) {
    global $LOG_FILE;
    $t = date('Y-m-d H:i:s');
    @file_put_contents($LOG_FILE, "[$t] [TEST] $msg\n", FILE_APPEND | LOCK_EX);
}

// connect DB
try {
    $dsn = "mysql:host={$DB_HOST};port={$DB_PORT};dbname={$DB_NAME};charset=utf8mb4";
    $pdo = new PDO($dsn, $DB_USER, $DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
} catch (Exception $e) {
    tlog("DB connect failed in test-event.php: " . $e->getMessage());
    http_response_code(500);
    echo "DB error: " . htmlspecialchars($e->getMessage());
    exit;
}

// build a fake lead payload
$fakeLeadId = rand(1000000, 9999999);
$now = date('Y-m-d H:i:s');

$payload = [
    'lead_id'                  => $fakeLeadId,
    'lead_creation_timestamp'  => $now,
    'lead_caller_phone_number' => '7150001234',
    'caller_id_name'           => 'TEST LEAD',
    'integration_type'         => 'api',
    'service_category'         => 'Plumbing',
    'zip_code'                 => '78745',
    'payout'                   => 42.50,
    'affiliate_payout_outcome' => 'Payable',
];

// insert into sd_leads
try {
    $sql = "INSERT INTO sd_leads (
                lead_id,
                lead_creation_timestamp,
                lead_caller_phone_number,
                caller_id_name,
                integration_type,
                service_category,
                zip_code,
                payout,
                affiliate_payout_outcome,
                raw_payload
            ) VALUES (
                :lead_id,
                :lead_creation_timestamp,
                :lead_caller_phone_number,
                :caller_id_name,
                :integration_type,
                :service_category,
                :zip_code,
                :payout,
                :affiliate_payout_outcome,
                :raw_payload
            )
            ON DUPLICATE KEY UPDATE
                lead_creation_timestamp = VALUES(lead_creation_timestamp),
                lead_caller_phone_number = VALUES(lead_caller_phone_number),
                caller_id_name          = VALUES(caller_id_name),
                integration_type        = VALUES(integration_type),
                service_category        = VALUES(service_category),
                zip_code                = VALUES(zip_code),
                payout                  = VALUES(payout),
                affiliate_payout_outcome= VALUES(affiliate_payout_outcome),
                raw_payload             = VALUES(raw_payload),
                updated_at              = CURRENT_TIMESTAMP";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':lead_id'                  => $fakeLeadId,
        ':lead_creation_timestamp'  => $now,
        ':lead_caller_phone_number' => $payload['lead_caller_phone_number'],
        ':caller_id_name'           => $payload['caller_id_name'],
        ':integration_type'         => $payload['integration_type'],
        ':service_category'         => $payload['service_category'],
        ':zip_code'                 => $payload['zip_code'],
        ':payout'                   => $payload['payout'],
        ':affiliate_payout_outcome' => $payload['affiliate_payout_outcome'],
        ':raw_payload'              => json_encode($payload),
    ]);

    tlog("Inserted TEST lead_id={$fakeLeadId} into sd_leads");

    // also save a JSON file into events/ for visual inspection
    $fileName = rtrim($EVENTS_DIR, '/\\') . '/TEST_' . date('Ymd_His') . "_lead_{$fakeLeadId}.json";
    @file_put_contents($fileName, json_encode([
        'type' => 'test.lead.ready',
        'data' => $payload,
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

    echo "Inserted test lead_id {$fakeLeadId} successfully.<br>";
    echo "You can now open view-events.php and sd_leads to see it.";

} catch (Exception $e) {
    tlog("DB insert failed in test-event.php: " . $e->getMessage());
    http_response_code(500);
    echo "Insert error: " . htmlspecialchars($e->getMessage());
    exit;
}
