<?php
// view-events.php - SD leads dashboard with simple session login

session_start();

// Try to load config.php (which should load .env)
if (file_exists(__DIR__ . '/config.php')) {
    require_once __DIR__ . '/config.php';
}

// Fallback .env loader in case config.php didn't set env vars
$envFile = __DIR__ . '/.env';
if (file_exists($envFile)) {
    $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || strpos($line, '#') === 0) continue;
        if (strpos($line, '=') === false) continue;
        list($k, $v) = explode('=', $line, 2);
        $k = trim($k); $v = trim($v);
        $v = preg_replace('/^["\'](.*)["\']$/', '$1', $v);
        putenv("$k=$v");
        $_ENV[$k] = $v;
        $_SERVER[$k] = $v;
    }
}

function envv($k, $d = null) {
    if (getenv($k) !== false) return getenv($k);
    if (isset($_ENV[$k])) return $_ENV[$k];
    if (isset($_SERVER[$k])) return $_SERVER[$k];
    return $d;
}

// Read admin credentials from env
$ADMIN_USER = envv('ADMIN_USER', 'admin');
$ADMIN_PASS = envv('ADMIN_PASS', 'ChangeMeNow!');

// Handle logout
if (isset($_GET['logout'])) {
    unset($_SESSION['sd_logged_in']);
    header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
    exit;
}

// Handle login form submit
$login_error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['username'], $_POST['password'])) {
    $u = trim($_POST['username']);
    $p = (string)$_POST['password'];

    if ($u === $ADMIN_USER && $p === $ADMIN_PASS) {
        $_SESSION['sd_logged_in'] = true;
        $_SESSION['sd_user'] = $u;
        header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
        exit;
    } else {
        $login_error = 'Invalid username or password.';
    }
}

// If not logged in, show login form
if (empty($_SESSION['sd_logged_in'])) {
    ?>
    <!doctype html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>ServiceDirect Dashboard Login</title>
        <style>
            body{font-family:system-ui,Segoe UI,Roboto,Arial;background:#f8fafc;margin:0;padding:0}
            .wrap{max-width:360px;margin:60px auto;background:#fff;padding:24px;border-radius:10px;
                  box-shadow:0 10px 25px rgba(15,23,42,0.12);border:1px solid #e2e8f0}
            h1{font-size:20px;margin:0 0 12px;color:#111827;text-align:center}
            label{display:block;font-size:13px;margin:10px 0 4px;color:#4b5563}
            input[type=text],input[type=password]{width:100%;padding:8px 10px;border-radius:6px;
                  border:1px solid #cbd5f5;font-size:14px;box-sizing:border-box}
            button{margin-top:14px;width:100%;padding:8px 10px;border-radius:6px;border:none;
                   font-size:14px;font-weight:500;cursor:pointer;background:#2563eb;color:#fff}
            .err{margin-top:10px;background:#fef2f2;border:1px solid #fecaca;color:#b91c1c;
                 padding:8px 10px;border-radius:6px;font-size:13px}
            .small{text-align:center;font-size:12px;color:#6b7280;margin-top:8px}
        </style>
    </head>
    <body>
    <div class="wrap">
        <h1>SD Leads Login</h1>
        <?php if ($login_error): ?>
            <div class="err"><?php echo htmlspecialchars($login_error, ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8'); ?></div>
        <?php endif; ?>
        <form method="post">
            <label for="username">Username</label>
            <input id="username" name="username" type="text" autocomplete="username" required>

            <label for="password">Password</label>
            <input id="password" name="password" type="password" autocomplete="current-password" required>

            <button type="submit">Sign in</button>
        </form>
        <div class="small">Use your ADMIN_USER / ADMIN_PASS from .env</div>
    </div>
    </body>
    </html>
    <?php
    exit;
}

// =====================
// Logged-in dashboard
// =====================
$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', '');

$dbh = null;
$dbError = null;
try {
    $dsn = "mysql:host={$DB_HOST};port={$DB_PORT};dbname={$DB_NAME};charset=utf8mb4";
    $dbh = new PDO($dsn, $DB_USER, $DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
} catch (Exception $e) {
    $dbError = $e->getMessage();
}

// Fetch last 100 leads
$rows = [];
if ($dbh) {
    $stmt = $dbh->query("SELECT * FROM sd_leads ORDER BY updated_at DESC LIMIT 100");
    $rows = $stmt->fetchAll();
}

function h($s) {
    return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ServiceDirect Leads Viewer</title>
<meta http-equiv="refresh" content="10">
<style>
body{font-family:system-ui,Segoe UI,Roboto,Arial;max-width:1150px;margin:18px auto;color:#111827;background:#f8fafc}
h1{font-size:22px;margin:0 0 4px}
.top{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px}
.bad{padding:10px;background:#fef2f2;border:1px solid #fecaca;color:#991b1b;border-radius:6px;margin-bottom:12px;font-size:13px}
.small{font-size:13px;color:#6b7280}
a.logout{font-size:13px;color:#2563eb;text-decoration:none}
a.logout:hover{text-decoration:underline}
.table-wrap{background:#fff;border-radius:10px;border:1px solid #e2e8f0;box-shadow:0 8px 18px rgba(15,23,42,0.08);padding:10px;overflow:auto}
table{width:100%;border-collapse:collapse;min-width:800px}
th,td{padding:8px;border-bottom:1px solid #e5e7eb;text-align:left;font-size:13px;vertical-align:top}
th{background:#f9fafb;font-weight:600;color:#374151}
tr:nth-child(even){background:#f9fafb}
pre{white-space:pre-wrap;font-size:12px;background:#f9fafb;padding:8px;border-radius:6px;border:1px solid #e5e7eb;max-height:220px;overflow:auto}
summary{cursor:pointer;color:#2563eb}
</style>
</head>
<body>
<div class="top">
  <div>
    <h1>ServiceDirect Leads Viewer</h1>
    <div class="small">
      Logged in as <strong><?php echo h($_SESSION['sd_user']); ?></strong> • 
      <a href="?logout=1" class="logout">Log out</a>
    </div>
  </div>
  <div class="small">
    DB: <?php echo h($DB_NAME); ?><br>
    Showing last <?php echo count($rows); ?> rows from <code>sd_leads</code>
  </div>
</div>

<?php if ($dbError): ?>
  <div class="bad">DB connection error: <?php echo h($dbError); ?></div>
<?php endif; ?>

<div class="table-wrap">
<?php if (!count($rows)): ?>
  <p class="small">No leads found yet. Once Service Direct delivers Direct Sync events successfully, new leads will appear here.</p>
<?php else: ?>
<table>
  <thead>
    <tr>
      <th>lead_id</th>
      <th>caller</th>
      <th>service_category</th>
      <th>payout</th>
      <th>outcome</th>
      <th>created_at</th>
      <th>raw_payload</th>
    </tr>
  </thead>
  <tbody>
  <?php foreach ($rows as $r): ?>
    <tr>
      <td><?php echo h($r['lead_id']); ?></td>
      <td><?php echo h($r['lead_caller_phone_number']); ?></td>
      <td><?php echo h($r['service_category']); ?></td>
      <td><?php echo h($r['payout']); ?></td>
      <td><?php echo h($r['affiliate_payout_outcome']); ?></td>
      <td><?php echo h($r['lead_creation_timestamp']); ?></td>
      <td>
        <details>
          <summary>view</summary>
          <pre><?php echo h($r['raw_payload']); ?></pre>
        </details>
      </td>
    </tr>
  <?php endforeach; ?>
  </tbody>
</table>
<?php endif; ?>
</div>
</body>
</html>
