<?php
/**
 * BossMail v2.1 - Professional Email Command Center
 * Author: Enhanced for canadianhealthplans.ca
 * Features: Porkbun support, Aliases, SMTP Send, Real Email Reading, IMAP Folders
 */

session_start();

// === CONFIGURATION ===
define('DB_FILE', __DIR__ . '/bossmail_data.db');
define('DEFAULT_PASS', 'bossmail2024');
define('ITEMS_PER_PAGE', 25);

// Provider presets
$PROVIDERS = [
    'gmail' => [
        'name' => 'Gmail',
        'imap_server' => 'imap.gmail.com',
        'imap_port' => 993,
        'smtp_server' => 'smtp.gmail.com',
        'smtp_port' => 587,
        'webmail_url' => 'https://mail.google.com',
        'compose_url' => 'https://mail.google.com/mail/?view=cm&fs=1&to={to}&su={subject}&body={body}',
    ],
    'mailcom' => [
        'name' => 'Mail.com',
        'imap_server' => 'imap.mail.com',
        'imap_port' => 993,
        'smtp_server' => 'smtp.mail.com',
        'smtp_port' => 587,
        'webmail_url' => 'https://www.mail.com',
        'compose_url' => '',
    ],
    'roundcube' => [
        'name' => 'Roundcube',
        'imap_server' => '',
        'imap_port' => 993,
        'smtp_server' => '',
        'smtp_port' => 587,
        'webmail_url' => '/rcube/',
        'compose_url' => '/rcube/?_task=mail&_action=compose&_to={to}&_subject={subject}&_body={body}',
    ],
    'porkbun' => [
        'name' => 'Porkbun Email',
        'imap_server' => 'mail.porkbun.com',
        'imap_port' => 993,
        'smtp_server' => 'mail.porkbun.com',
        'smtp_port' => 587,
        'webmail_url' => '',
        'compose_url' => '',
    ],
    'custom' => [
        'name' => 'Custom IMAP',
        'imap_server' => '',
        'imap_port' => 993,
        'smtp_server' => '',
        'smtp_port' => 587,
        'webmail_url' => '',
        'compose_url' => '',
    ],
];

// === DATABASE ===
function getDB(): PDO {
    static $db = null;
    if ($db) return $db;
    $isNew = !file_exists(DB_FILE);
    $db = new PDO('sqlite:' . DB_FILE);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    
    if ($isNew) {
        $db->exec("CREATE TABLE IF NOT EXISTS config (
            key TEXT PRIMARY KEY,
            value TEXT
        )");
        $db->exec("CREATE TABLE IF NOT EXISTS leads (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            email TEXT NOT NULL,
            name TEXT,
            phone TEXT,
            company TEXT,
            source TEXT DEFAULT 'manual',
            status TEXT DEFAULT 'new',
            notes TEXT,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )");
        $db->exec("CREATE TABLE IF NOT EXISTS email_accounts (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            provider TEXT DEFAULT 'custom',
            email TEXT NOT NULL,
            imap_server TEXT,
            imap_port INTEGER DEFAULT 993,
            smtp_server TEXT,
            smtp_port INTEGER DEFAULT 587,
            username TEXT,
            password TEXT,
            use_ssl INTEGER DEFAULT 1,
            active INTEGER DEFAULT 1,
            sort_order INTEGER DEFAULT 0,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )");
        $db->exec("INSERT INTO config (key, value) VALUES ('password_hash', '" . password_hash(DEFAULT_PASS, PASSWORD_DEFAULT) . "')");
        importLegacyLeads($db);
    }
    // Migration: add aliases column
    try {
        $db->query("SELECT aliases FROM email_accounts LIMIT 1");
    } catch (PDOException $e) {
        $db->exec("ALTER TABLE email_accounts ADD COLUMN aliases TEXT DEFAULT ''");
    }
    return $db;
}

// === AUTH ===
function checkAuth(): void {
    if (empty($_SESSION['bossmail_auth'])) {
        header('HTTP/1.1 403 Forbidden');
        exit('<h1>Access Denied</h1><p>Please <a href="?action=login">login</a>.</p>');
    }
}

function verifyPassword(string $pass): bool {
    $db = getDB();
    $hash = $db->query("SELECT value FROM config WHERE key = 'password_hash'")->fetchColumn();
    return password_verify($pass, $hash ?: '');
}

function changePassword(string $newPass): void {
    $db = getDB();
    $stmt = $db->prepare("INSERT OR REPLACE INTO config (key, value) VALUES ('password_hash', ?)");
    $stmt->execute([password_hash($newPass, PASSWORD_DEFAULT)]);
}

function importLegacyLeads($db) {
    // Stub: no legacy leads to import on fresh install
}

// === LEAD CRUD ===
function getLeads(array $filters = [], int $page = 1): array {
    $db = getDB();
    $where = ['1=1'];
    $params = [];
    if (!empty($filters['search'])) {
        $where[] = "(email LIKE ? OR name LIKE ? OR company LIKE ? OR phone LIKE ?)";
        $params[] = $params[] = $params[] = $params[] = '%' . $filters['search'] . '%';
    }
    if (!empty($filters['status']) && $filters['status'] !== 'all') {
        $where[] = "status = ?";
        $params[] = $filters['status'];
    }
    if (!empty($filters['source']) && $filters['source'] !== 'all') {
        $where[] = "source = ?";
        $params[] = $filters['source'];
    }
    $whereSql = implode(' AND ', $where);
    
    $countStmt = $db->prepare("SELECT COUNT(*) FROM leads WHERE $whereSql");
    $countStmt->execute($params);
    $total = (int)$countStmt->fetchColumn();
    
    $offset = ($page - 1) * ITEMS_PER_PAGE;
    $stmt = $db->prepare("SELECT * FROM leads WHERE $whereSql ORDER BY updated_at DESC LIMIT ? OFFSET ?");
    $stmt->execute(array_merge($params, [ITEMS_PER_PAGE, $offset]));
    
    return ['leads' => $stmt->fetchAll(), 'total' => $total, 'pages' => max(1, ceil($total / ITEMS_PER_PAGE))];
}

function getLead(int $id): ?array {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM leads WHERE id = ?");
    $stmt->execute([$id]);
    return $stmt->fetch() ?: null;
}

function saveLead(array $data): int {
    $db = getDB();
    if (!empty($data['id'])) {
        $stmt = $db->prepare("UPDATE leads SET email=?, name=?, phone=?, company=?, source=?, status=?, notes=?, updated_at=datetime('now') WHERE id=?");
        $stmt->execute([$data['email'], $data['name'], $data['phone'], $data['company'], $data['source'], $data['status'], $data['notes'], $data['id']]);
        return (int)$data['id'];
    } else {
        $stmt = $db->prepare("INSERT INTO leads (email, name, phone, company, source, status, notes) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$data['email'], $data['name'], $data['phone'], $data['company'], $data['source'], $data['status'], $data['notes']]);
        return (int)$db->lastInsertId();
    }
}

function deleteLead(int $id): void {
    $db = getDB();
    $stmt = $db->prepare("DELETE FROM leads WHERE id = ?");
    $stmt->execute([$id]);
}

function getLeadStats(): array {
    $db = getDB();
    return [
        'total' => (int)$db->query("SELECT COUNT(*) FROM leads")->fetchColumn(),
        'new' => (int)$db->query("SELECT COUNT(*) FROM leads WHERE status = 'new'")->fetchColumn(),
        'contacted' => (int)$db->query("SELECT COUNT(*) FROM leads WHERE status = 'contacted'")->fetchColumn(),
        'converted' => (int)$db->query("SELECT COUNT(*) FROM leads WHERE status = 'converted'")->fetchColumn(),
        'sources' => $db->query("SELECT source, COUNT(*) as count FROM leads GROUP BY source")->fetchAll(),
    ];
}

// === EMAIL ACCOUNTS ===
function getAccounts(): array {
    $db = getDB();
    return $db->query("SELECT * FROM email_accounts WHERE active = 1 ORDER BY sort_order, id")->fetchAll();
}

function getAccount(int $id): ?array {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM email_accounts WHERE id = ?");
    $stmt->execute([$id]);
    return $stmt->fetch() ?: null;
}

function saveAccount(array $data): int {
    $db = getDB();
    $password = !empty($data['password']) ? base64_encode($data['password']) : '';
    $aliases = $data['aliases'] ?? '';
    if (!empty($data['id'])) {
        $existing = getAccount((int)$data['id']);
        if (empty($password) && $existing) {
            $password = $existing['password'];
        }
        $stmt = $db->prepare("UPDATE email_accounts SET name=?, provider=?, email=?, imap_server=?, imap_port=?, smtp_server=?, smtp_port=?, username=?, password=?, use_ssl=?, sort_order=?, aliases=?, updated_at=datetime('now') WHERE id=?");
        $stmt->execute([$data['name'], $data['provider'], $data['email'], $data['imap_server'], $data['imap_port'], $data['smtp_server'], $data['smtp_port'], $data['username'], $password, $data['use_ssl'], $data['sort_order'], $aliases, $data['id']]);
        return (int)$data['id'];
    } else {
        $stmt = $db->prepare("INSERT INTO email_accounts (name, provider, email, imap_server, imap_port, smtp_server, smtp_port, username, password, use_ssl, sort_order, aliases) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$data['name'], $data['provider'], $data['email'], $data['imap_server'], $data['imap_port'], $data['smtp_server'], $data['smtp_port'], $data['username'], $password, $data['use_ssl'], $data['sort_order'], $aliases]);
        return (int)$db->lastInsertId();
    }
}

function deleteAccount(int $id): void {
    $db = getDB();
    $stmt = $db->prepare("DELETE FROM email_accounts WHERE id = ?");
    $stmt->execute([$id]);
}

// === IMAP FUNCTIONS ===
function imapCheck(): bool {
    return extension_loaded('imap');
}

function imapConnect(array $account) {
    if (!imapCheck()) return false;
    $server = $account['imap_server'];
    $port = (int)$account['imap_port'];
    $ssl = !empty($account['use_ssl']) ? '/ssl' : '';
    $mailbox = "{{$server}:{$port}/imap{$ssl}}INBOX";
    $password = base64_decode($account['password']);
    $conn = @imap_open($mailbox, $account['username'] ?: $account['email'], $password, OP_READONLY, 1);
    return $conn;
}

function imapGetFolders($conn, array $account): array {
    if (!is_resource($conn) && !($conn instanceof IMAP\Connection)) return [];
    $server = $account['imap_server'];
    $port = (int)$account['imap_port'];
    $ssl = !empty($account['use_ssl']) ? '/ssl' : '';
    $prefix = '{' . $server . ':' . $port . '/imap' . $ssl . '}';
    $folders = imap_list($conn, $prefix, '*');
    if (!$folders) return [];
    return array_map(function($f) use ($prefix) { return str_replace($prefix, '', $f); }, $folders);
}

function imapGetEmails($conn, array $account, string $folder = 'INBOX', int $page = 1, int $perPage = 20): array {
    if (!is_resource($conn) && !($conn instanceof IMAP\Connection)) return ['emails' => [], 'total' => 0];
    
    $total = imap_num_msg($conn);
    $start = max(1, $total - ($page * $perPage) + 1);
    $end = max(1, $total - (($page - 1) * $perPage));
    if ($start > $end) { $temp = $start; $start = $end; $end = $temp; }
    
    $emails = [];
    for ($i = $end; $i >= $start; $i--) {
        $header = imap_headerinfo($conn, $i);
        $structure = imap_fetchstructure($conn, $i);
        $preview = '';
        if ($structure && !empty($structure->parts)) {
            $preview = imap_fetchbody($conn, $i, 1);
            if ($structure->parts[0]->encoding == 3) $preview = base64_decode($preview);
            elseif ($structure->parts[0]->encoding == 4) $preview = quoted_printable_decode($preview);
        } else {
            $preview = imap_fetchbody($conn, $i, 1);
            if ($structure && $structure->encoding == 3) $preview = base64_decode($preview);
            elseif ($structure && $structure->encoding == 4) $preview = quoted_printable_decode($preview);
        }
        $preview = strip_tags($preview);
        $preview = substr($preview, 0, 200);
        
        $emails[] = [
            'uid' => imap_uid($conn, $i),
            'msgno' => $i,
            'subject' => imap_utf8($header->subject ?? 'No Subject'),
            'from' => imap_utf8($header->fromaddress ?? 'Unknown'),
            'date' => $header->date ?? '',
            'preview' => $preview,
            'seen' => !empty($header->Unseen) ? false : true,
        ];
    }
    return ['emails' => $emails, 'total' => $total];
}

function imapGetEmailBody($conn, int $uid): array {
    if (!is_resource($conn) && !($conn instanceof IMAP\Connection)) return ['html' => '', 'text' => ''];
    $msgno = imap_msgno($conn, $uid);
    if (!$msgno) return ['html' => '', 'text' => ''];
    $structure = imap_fetchstructure($conn, $msgno);
    $html = '';
    $text = '';
    
    if (!empty($structure->parts)) {
        foreach ($structure->parts as $partno => $part) {
            $body = imap_fetchbody($conn, $msgno, $partno + 1);
            if ($part->encoding == 3) $body = base64_decode($body);
            elseif ($part->encoding == 4) $body = quoted_printable_decode($body);
            if ($part->subtype == 'HTML') $html = $body;
            elseif ($part->subtype == 'PLAIN') $text = $body;
        }
    } else {
        $body = imap_fetchbody($conn, $msgno, 1);
        if ($structure->encoding == 3) $body = base64_decode($body);
        elseif ($structure->encoding == 4) $body = quoted_printable_decode($body);
        $text = $body;
    }
    return ['html' => $html, 'text' => nl2br(htmlspecialchars($text))];
}

// === SMTP SEND FUNCTION ===
function sendSmtpEmail(array $account, string $to, string $subject, string $body, string $fromEmail = '', string $fromName = ''): string {
    $smtpServer = $account['smtp_server'] ?: $account['imap_server'];
    $smtpPort = (int)($account['smtp_port'] ?: 587);
    $username = $account['username'] ?: $account['email'];
    $password = base64_decode($account['password']);
    $fromEmail = $fromEmail ?: $account['email'];
    $fromName = $fromName ?: $account['name'];

    $timeout = 30;
    $errno = 0;
    $errstr = '';

    $socket = @fsockopen($smtpServer, $smtpPort, $errno, $errstr, $timeout);
    if (!$socket) return "Connection failed: $errstr ($errno)";

    $response = fgets($socket, 515);
    if (substr($response, 0, 3) != '220') { fclose($socket); return "Server error: $response"; }

    fputs($socket, "EHLO bossmail\r\n");
    $response = '';
    while ($line = fgets($socket, 515)) {
        $response .= $line;
        if (substr($line, 3, 1) == ' ') break;
    }

    if ($smtpPort == 587) {
        fputs($socket, "STARTTLS\r\n");
        $response = fgets($socket, 515);
        if (substr($response, 0, 3) != '220') { fclose($socket); return "STARTTLS failed: $response"; }
        stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
        fputs($socket, "EHLO bossmail\r\n");
        $response = '';
        while ($line = fgets($socket, 515)) {
            $response .= $line;
            if (substr($line, 3, 1) == ' ') break;
        }
    }

    fputs($socket, "AUTH LOGIN\r\n");
    $response = fgets($socket, 515);
    if (substr($response, 0, 3) != '334') { fclose($socket); return "Auth failed: $response"; }

    fputs($socket, base64_encode($username) . "\r\n");
    $response = fgets($socket, 515);
    if (substr($response, 0, 3) != '334') { fclose($socket); return "Auth failed: $response"; }

    fputs($socket, base64_encode($password) . "\r\n");
    $response = fgets($socket, 515);
    if (substr($response, 0, 3) != '235') { fclose($socket); return "Auth failed: Check your password. For Gmail use an App Password."; }

    fputs($socket, "MAIL FROM:<$fromEmail>\r\n");
    $response = fgets($socket, 515);
    if (substr($response, 0, 3) != '250') { fclose($socket); return "MAIL FROM failed: $response"; }

    foreach (explode(',', $to) as $recipient) {
        $recipient = trim($recipient);
        if ($recipient) {
            fputs($socket, "RCPT TO:<$recipient>\r\n");
            fgets($socket, 515);
        }
    }

    fputs($socket, "DATA\r\n");
    $response = fgets($socket, 515);
    if (substr($response, 0, 3) != '354') { fclose($socket); return "DATA failed: $response"; }

    $headers = "From: =?UTF-8?B?" . base64_encode($fromName) . "?= <$fromEmail>\r\n";
    $headers .= "To: $to\r\n";
    $headers .= "Subject: =?UTF-8?B?" . base64_encode($subject) . "?=\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Date: " . date('r') . "\r\n";

    $message = $headers . "\r\n" . $body . "\r\n.\r\n";
    fputs($socket, $message);
    $response = fgets($socket, 515);
    if (substr($response, 0, 3) != '250') { fclose($socket); return "Send failed: $response"; }

    fputs($socket, "QUIT\r\n");
    fclose($socket);
    return 'OK';
}

// === EXPORT ===
function exportLeadsToCSV(): void {
    $db = getDB();
    $leads = $db->query("SELECT * FROM leads ORDER BY created_at DESC")->fetchAll();
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="bossmail_leads_' . date('Y-m-d') . '.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['ID', 'Email', 'Name', 'Phone', 'Company', 'Source', 'Status', 'Notes', 'Created', 'Updated']);
    foreach ($leads as $lead) {
        fputcsv($out, [$lead['id'], $lead['email'], $lead['name'], $lead['phone'], $lead['company'], $lead['source'], $lead['status'], $lead['notes'], $lead['created_at'], $lead['updated_at']]);
    }
    fclose($out);
    exit;
}

// === REQUEST HANDLER ===
$action = $_GET['action'] ?? 'dashboard';
$page = max(1, (int)($_GET['page'] ?? 1));
$msg = $_SESSION['msg'] ?? '';
$error = $_SESSION['error'] ?? '';
unset($_SESSION['msg'], $_SESSION['error']);

// Handle exports before any output
if ($action === 'export' && !empty($_SESSION['bossmail_auth'])) {
    exportLeadsToCSV();
}

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postAction = $_POST['post_action'] ?? '';
    
    if ($postAction === 'login') {
        if (verifyPassword($_POST['password'] ?? '')) {
            $_SESSION['bossmail_auth'] = true;
            header('Location: ?action=dashboard');
            exit;
        } else {
            $error = 'Invalid password.';
        }
    }
    
    if (!empty($_SESSION['bossmail_auth'])) {
        if ($postAction === 'logout') {
            unset($_SESSION['bossmail_auth']);
            header('Location: ?action=login');
            exit;
        }
        if ($postAction === 'change_password') {
            if (!empty($_POST['new_password']) && $_POST['new_password'] === ($_POST['confirm_password'] ?? '')) {
                changePassword($_POST['new_password']);
                $_SESSION['msg'] = 'Password changed successfully.';
            } else {
                $_SESSION['error'] = 'Passwords do not match or are empty.';
            }
            header('Location: ?action=settings');
            exit;
        }
        if ($postAction === 'save_lead') {
            saveLead($_POST);
            $_SESSION['msg'] = 'Lead saved successfully.';
            header('Location: ?action=leads');
            exit;
        }
        if ($postAction === 'delete_lead') {
            deleteLead((int)($_POST['id'] ?? 0));
            $_SESSION['msg'] = 'Lead deleted.';
            header('Location: ?action=leads');
            exit;
        }
        if ($postAction === 'save_account') {
            saveAccount($_POST);
            $_SESSION['msg'] = 'Email account saved.';
            header('Location: ?action=emails');
            exit;
        }
        if ($postAction === 'delete_account') {
            deleteAccount((int)($_POST['id'] ?? 0));
            $_SESSION['msg'] = 'Account deleted.';
            header('Location: ?action=emails');
            exit;
        }
        if ($postAction === 'send_email') {
            $account = getAccount((int)($_POST['account_id'] ?? 0));
            if ($account) {
                $fromEmail = $_POST['from_email'] ?: $account['email'];
                $result = sendSmtpEmail($account, $_POST['to'] ?? '', $_POST['subject'] ?? '', $_POST['body'] ?? '', $fromEmail, $_POST['from_name'] ?? $account['name']);
                if ($result === 'OK') {
                    $_SESSION['msg'] = 'Email sent successfully.';
                } else {
                    $_SESSION['error'] = $result;
                }
            } else {
                $_SESSION['error'] = 'Account not found.';
            }
            header('Location: ?action=emails&account_id=' . ($_POST['account_id'] ?? ''));
            exit;
        }
        if ($postAction === 'import_csv' && !empty($_FILES['csv_file']['tmp_name'])) {
            $handle = fopen($_FILES['csv_file']['tmp_name'], 'r');
            $header = fgetcsv($handle);
            $count = 0;
            while (($row = fgetcsv($handle)) !== false) {
                $data = array_combine($header, $row);
                if (!empty($data['email']) && filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
                    saveLead([
                        'email' => $data['email'],
                        'name' => $data['name'] ?? '',
                        'phone' => $data['phone'] ?? '',
                        'company' => $data['company'] ?? '',
                        'source' => $data['source'] ?? 'csv',
                        'status' => $data['status'] ?? 'new',
                        'notes' => $data['notes'] ?? '',
                    ]);
                    $count++;
                }
            }
            fclose($handle);
            $_SESSION['msg'] = "Imported $count leads from CSV.";
            header('Location: ?action=leads');
            exit;
        }
    }
}

// Auth check for protected pages
$publicPages = ['login'];
if (!in_array($action, $publicPages) && empty($_SESSION['bossmail_auth'])) {
    header('Location: ?action=login');
    exit;
}

// Load data
$accounts = [];
$currentAccount = null;
$imapConn = null;
$emailsData = ['emails' => [], 'total' => 0];
$leadData = ['leads' => [], 'total' => 0, 'pages' => 1];
$stats = [];
$leadEdit = null;
$accountEdit = null;

if (!empty($_SESSION['bossmail_auth'])) {
    $accounts = getAccounts();
    $stats = getLeadStats();
    
    if ($action === 'leads') {
        $leadData = getLeads($_GET, $page);
        if (!empty($_GET['edit'])) {
            $leadEdit = getLead((int)$_GET['edit']);
        }
    }
    if ($action === 'emails') {
        if (!empty($_GET['edit_account'])) {
            $accountEdit = getAccount((int)$_GET['edit_account']);
        }
        if (!empty($_GET['account_id'])) {
            $currentAccount = getAccount((int)$_GET['account_id']);
            if ($currentAccount && imapCheck()) {
                $imapConn = imapConnect($currentAccount);
                if ($imapConn) {
                    $folder = $_GET['folder'] ?? 'INBOX';
                    $emailsData = imapGetEmails($imapConn, $currentAccount, $folder, $page);
                }
            }
        }
    }
    // Load email body for viewing
    $viewEmail = null;
    if ($action === 'emails' && !empty($_GET['account_id']) && !empty($_GET['view_uid'])) {
        $currentAccount = getAccount((int)$_GET['account_id']);
        if ($currentAccount && imapCheck()) {
            $imapConn = imapConnect($currentAccount);
            if ($imapConn) {
                $viewEmail = imapGetEmailBody($imapConn, (int)$_GET['view_uid']);
                $viewEmail['uid'] = (int)$_GET['view_uid'];
                // Get header info for subject/from
                $msgno = imap_msgno($imapConn, (int)$_GET['view_uid']);
                if ($msgno) {
                    $header = imap_headerinfo($imapConn, $msgno);
                    $viewEmail['subject'] = imap_utf8($header->subject ?? 'No Subject');
                    $viewEmail['from'] = imap_utf8($header->fromaddress ?? 'Unknown');
                    $viewEmail['date'] = $header->date ?? '';
                    $viewEmail['to'] = imap_utf8($header->toaddress ?? '');
                }
            }
        }
    }
}

$statuses = ['new' => 'New', 'contacted' => 'Contacted', 'qualified' => 'Qualified', 'converted' => 'Converted', 'lost' => 'Lost'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BossMail 2.0 | Email Command Center</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-primary: #0a0e17;
            --bg-secondary: #111827;
            --bg-card: #1a2236;
            --bg-hover: #232d42;
            --border: #2d3748;
            --text-primary: #f1f5f9;
            --text-secondary: #94a3b8;
            --accent: #0ea5e9;
            --accent-hover: #0284c7;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
            --info: #6366f1;
        }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: var(--bg-primary);
            color: var(--text-primary);
            min-height: 100vh;
            line-height: 1.5;
        }
        
        /* Login */
        .login-page {
            display: flex; align-items: center; justify-content: center;
            min-height: 100vh; background: linear-gradient(135deg, #0a0e17 0%, #1a2236 100%);
        }
        .login-box {
            background: var(--bg-card); border: 1px solid var(--border);
            border-radius: 16px; padding: 48px; width: 100%; max-width: 420px;
            box-shadow: 0 25px 50px -12px rgba(0,0,0,0.5);
        }
        .login-box h1 { font-size: 28px; margin-bottom: 8px; }
        .login-box p { color: var(--text-secondary); margin-bottom: 32px; }
        .login-box input {
            width: 100%; padding: 14px 16px; background: var(--bg-secondary);
            border: 1px solid var(--border); border-radius: 8px; color: var(--text-primary);
            font-size: 15px; margin-bottom: 16px; outline: none;
        }
        .login-box input:focus { border-color: var(--accent); }
        .login-box button {
            width: 100%; padding: 14px; background: var(--accent); color: white;
            border: none; border-radius: 8px; font-size: 15px; font-weight: 600;
            cursor: pointer; transition: background 0.2s;
        }
        .login-box button:hover { background: var(--accent-hover); }
        .alert {
            padding: 12px 16px; border-radius: 8px; margin-bottom: 16px;
            font-size: 14px;
        }
        .alert-error { background: rgba(239,68,68,0.1); border: 1px solid rgba(239,68,68,0.3); color: #fca5a5; }
        .alert-success { background: rgba(16,185,129,0.1); border: 1px solid rgba(16,185,129,0.3); color: #6ee7b7; }
        
        /* Layout */
        .app-layout { display: flex; min-height: 100vh; }
        .sidebar {
            width: 260px; background: var(--bg-secondary); border-right: 1px solid var(--border);
            display: flex; flex-direction: column; position: fixed; height: 100vh; z-index: 100;
        }
        .sidebar-header {
            padding: 24px; border-bottom: 1px solid var(--border);
        }
        .sidebar-header h1 { font-size: 20px; font-weight: 700; letter-spacing: -0.5px; }
        .sidebar-header span { color: var(--accent); }
        .sidebar-header p { font-size: 12px; color: var(--text-secondary); margin-top: 4px; }
        .nav-menu { flex: 1; padding: 16px 12px; overflow-y: auto; }
        .nav-item {
            display: flex; align-items: center; gap: 12px;
            padding: 12px 16px; border-radius: 8px; color: var(--text-secondary);
            text-decoration: none; font-size: 14px; font-weight: 500;
            transition: all 0.2s; margin-bottom: 4px;
        }
        .nav-item:hover, .nav-item.active {
            background: var(--bg-hover); color: var(--text-primary);
        }
        .nav-item svg { width: 20px; height: 20px; flex-shrink: 0; }
        .sidebar-footer {
            padding: 16px; border-top: 1px solid var(--border);
        }
        .sidebar-footer form { margin: 0; }
        .sidebar-footer button {
            width: 100%; padding: 10px; background: transparent;
            border: 1px solid var(--border); border-radius: 8px;
            color: var(--text-secondary); font-size: 13px; cursor: pointer;
        }
        .sidebar-footer button:hover { border-color: var(--danger); color: var(--danger); }
        .main-content {
            flex: 1; margin-left: 260px; padding: 32px;
            max-width: calc(100vw - 260px);
        }
        
        /* Header */
        .page-header {
            display: flex; justify-content: space-between; align-items: center;
            margin-bottom: 32px;
        }
        .page-header h2 { font-size: 24px; font-weight: 700; }
        .page-header p { color: var(--text-secondary); font-size: 14px; margin-top: 4px; }
        
        /* Account Dropdown */
        .account-selector {
            position: relative;
        }
        .account-selector select {
            appearance: none; background: var(--bg-card); border: 1px solid var(--border);
            color: var(--text-primary); padding: 10px 40px 10px 16px; border-radius: 8px;
            font-size: 14px; cursor: pointer; min-width: 240px;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='%2394a3b8' viewBox='0 0 16 16'%3E%3Cpath d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/%3E%3C/svg%3E");
            background-repeat: no-repeat; background-position: right 12px center;
        }
        
        /* Stats Grid */
        .stats-grid {
            display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 20px; margin-bottom: 32px;
        }
        .stat-card {
            background: var(--bg-card); border: 1px solid var(--border);
            border-radius: 12px; padding: 24px;
        }
        .stat-card .label { font-size: 13px; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.5px; }
        .stat-card .value { font-size: 32px; font-weight: 700; margin-top: 8px; }
        .stat-card .change { font-size: 13px; margin-top: 8px; }
        .stat-card.total .value { color: var(--accent); }
        .stat-card.new .value { color: var(--info); }
        .stat-card.contacted .value { color: var(--warning); }
        .stat-card.converted .value { color: var(--success); }
        
        /* Cards */
        .card {
            background: var(--bg-card); border: 1px solid var(--border);
            border-radius: 12px; overflow: hidden;
        }
        .card-header {
            padding: 20px 24px; border-bottom: 1px solid var(--border);
            display: flex; justify-content: space-between; align-items: center;
        }
        .card-header h3 { font-size: 16px; font-weight: 600; }
        .card-body { padding: 24px; }
        
        /* Buttons */
        .btn {
            display: inline-flex; align-items: center; gap: 8px;
            padding: 10px 18px; border-radius: 8px; font-size: 14px;
            font-weight: 500; text-decoration: none; border: none;
            cursor: pointer; transition: all 0.2s;
        }
        .btn-primary { background: var(--accent); color: white; }
        .btn-primary:hover { background: var(--accent-hover); }
        .btn-secondary { background: var(--bg-hover); color: var(--text-primary); border: 1px solid var(--border); }
        .btn-secondary:hover { background: var(--border); }
        .btn-danger { background: rgba(239,68,68,0.1); color: var(--danger); border: 1px solid rgba(239,68,68,0.3); }
        .btn-danger:hover { background: rgba(239,68,68,0.2); }
        .btn-sm { padding: 6px 12px; font-size: 13px; }
        
        /* Tables */
        .data-table { width: 100%; border-collapse: collapse; }
        .data-table th {
            text-align: left; padding: 12px 16px; font-size: 12px;
            text-transform: uppercase; letter-spacing: 0.5px;
            color: var(--text-secondary); font-weight: 600;
            border-bottom: 1px solid var(--border);
        }
        .data-table td {
            padding: 14px 16px; border-bottom: 1px solid var(--border);
            font-size: 14px;
        }
        .data-table tr:hover td { background: var(--bg-hover); }
        .data-table tr:last-child td { border-bottom: none; }
        .badge {
            display: inline-block; padding: 4px 10px; border-radius: 20px;
            font-size: 12px; font-weight: 500;
        }
        .badge-new { background: rgba(99,102,241,0.15); color: #818cf8; }
        .badge-contacted { background: rgba(245,158,11,0.15); color: #fbbf24; }
        .badge-qualified { background: rgba(14,165,233,0.15); color: #7dd3fc; }
        .badge-converted { background: rgba(16,185,129,0.15); color: #34d399; }
        .badge-lost { background: rgba(239,68,68,0.15); color: #f87171; }
        .badge-warm { background: rgba(16,185,129,0.15); color: #34d399; }
        .badge-scraped { background: rgba(148,163,184,0.15); color: #94a3b8; }
        
        /* Forms */
        .form-grid {
            display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;
        }
        .form-group { display: flex; flex-direction: column; gap: 6px; }
        .form-group.full { grid-column: 1 / -1; }
        .form-group label { font-size: 13px; font-weight: 500; color: var(--text-secondary); }
        .form-group input, .form-group select, .form-group textarea {
            padding: 10px 14px; background: var(--bg-secondary);
            border: 1px solid var(--border); border-radius: 8px;
            color: var(--text-primary); font-size: 14px; outline: none;
        }
        .form-group input:focus, .form-group select:focus, .form-group textarea:focus {
            border-color: var(--accent);
        }
        .form-group textarea { min-height: 100px; resize: vertical; font-family: inherit; }
        
        /* Search & Filters */
        .toolbar {
            display: flex; gap: 12px; margin-bottom: 20px; flex-wrap: wrap;
        }
        .toolbar input, .toolbar select {
            padding: 10px 14px; background: var(--bg-secondary);
            border: 1px solid var(--border); border-radius: 8px;
            color: var(--text-primary); font-size: 14px; outline: none;
        }
        .toolbar input { min-width: 240px; }
        
        /* Pagination */
        .pagination {
            display: flex; gap: 8px; justify-content: center; margin-top: 24px;
        }
        .pagination a, .pagination span {
            padding: 8px 14px; border-radius: 6px; font-size: 14px;
            text-decoration: none; color: var(--text-secondary);
            border: 1px solid var(--border);
        }
        .pagination a:hover { background: var(--bg-hover); color: var(--text-primary); }
        .pagination .current { background: var(--accent); color: white; border-color: var(--accent); }
        
        /* Modal */
        .modal-overlay {
            display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.7);
            z-index: 1000; align-items: center; justify-content: center;
        }
        .modal-overlay.active { display: flex; }
        .modal {
            background: var(--bg-card); border: 1px solid var(--border);
            border-radius: 16px; width: 90%; max-width: 600px;
            max-height: 90vh; overflow-y: auto;
        }
        .modal-header {
            padding: 24px; border-bottom: 1px solid var(--border);
            display: flex; justify-content: space-between; align-items: center;
        }
        .modal-header h3 { font-size: 18px; }
        .modal-body { padding: 24px; }
        .modal-footer {
            padding: 20px 24px; border-top: 1px solid var(--border);
            display: flex; justify-content: flex-end; gap: 12px;
        }
        .modal-close {
            background: none; border: none; color: var(--text-secondary);
            font-size: 24px; cursor: pointer;
        }
        
        /* Email Viewer */
        .email-layout { display: grid; grid-template-columns: 280px 1fr; gap: 20px; }
        .folder-list {
            background: var(--bg-card); border: 1px solid var(--border);
            border-radius: 12px; padding: 16px;
        }
        .folder-item {
            padding: 10px 12px; border-radius: 6px; cursor: pointer;
            font-size: 14px; color: var(--text-secondary);
            display: flex; justify-content: space-between; align-items: center;
        }
        .folder-item:hover, .folder-item.active {
            background: var(--bg-hover); color: var(--text-primary);
        }
        .email-list {
            background: var(--bg-card); border: 1px solid var(--border);
            border-radius: 12px; overflow: hidden;
        }
        .email-item {
            padding: 16px 20px; border-bottom: 1px solid var(--border);
            cursor: pointer; transition: background 0.2s;
        }
        .email-item:hover { background: var(--bg-hover); }
        .email-item.unseen { border-left: 3px solid var(--accent); }
        .email-item .subject { font-weight: 600; font-size: 14px; margin-bottom: 4px; }
        .email-item .meta { font-size: 12px; color: var(--text-secondary); }
        .email-item .preview { font-size: 13px; color: var(--text-secondary); margin-top: 6px; }
        .email-reading {
            background: var(--bg-card); border: 1px solid var(--border);
            border-radius: 12px; padding: 24px; margin-top: 20px;
        }
        .email-reading h3 { margin-bottom: 12px; }
        .email-reading .meta { color: var(--text-secondary); font-size: 14px; margin-bottom: 16px; }
        .email-reading .body { line-height: 1.7; }
        
        /* Compose */
        .compose-bar {
            display: flex; gap: 12px; margin-bottom: 20px;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .sidebar { width: 100%; transform: translateX(-100%); transition: transform 0.3s; }
            .sidebar.open { transform: translateX(0); }
            .main-content { margin-left: 0; max-width: 100%; padding: 20px; }
            .stats-grid { grid-template-columns: 1fr; }
            .form-grid { grid-template-columns: 1fr; }
            .email-layout { grid-template-columns: 1fr; }
            .toolbar { flex-direction: column; }
            .toolbar input { min-width: 100%; }
        }
        
        /* Utilities */
        .text-muted { color: var(--text-secondary); }
        .mb-4 { margin-bottom: 16px; }
        .mt-4 { margin-top: 16px; }
        .flex { display: flex; }
        .items-center { align-items: center; }
        .gap-2 { gap: 8px; }
        .gap-4 { gap: 16px; }
        .justify-between { justify-content: space-between; }
    </style>
</head>
<body>

<?php if ($action === 'login'): ?>
<div class="login-page">
    <div class="login-box">
        <h1>Boss<span>Mail</span> 2.0</h1>
        <p>Email Command Center for Canadian Health Plans</p>
        <?php if ($error): ?>
            <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        <form method="POST">
            <input type="hidden" name="post_action" value="login">
            <input type="password" name="password" placeholder="Enter password" required autofocus>
            <button type="submit">Sign In</button>
        </form>
        <p style="margin-top: 20px; font-size: 12px; color: var(--text-secondary);">
            Default: <code>bossmail2024</code> — Change this in Settings after login.
        </p>
    </div>
</div>

<?php else: ?>
<div class="app-layout">
    <aside class="sidebar">
        <div class="sidebar-header">
            <h1>Boss<span>Mail</span></h1>
            <p>canadianhealthplans.ca</p>
        </div>
        <nav class="nav-menu">
            <a href="?action=dashboard" class="nav-item <?php echo $action === 'dashboard' ? 'active' : ''; ?>">
                <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 13h8V3H3v10zm0 8h8v-6H3v6zm10 0h8V11h-8v10zm0-18v6h8V3h-8z"/></svg>
                Dashboard
            </a>
            <a href="?action=leads" class="nav-item <?php echo $action === 'leads' ? 'active' : ''; ?>">
                <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
                Leads
                <?php if (!empty($stats['total'])): ?>
                    <span style="margin-left: auto; background: var(--accent); color: white; padding: 2px 8px; border-radius: 10px; font-size: 11px;"><?php echo $stats['total']; ?></span>
                <?php endif; ?>
            </a>
            <a href="?action=emails" class="nav-item <?php echo $action === 'emails' ? 'active' : ''; ?>">
                <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
                Email Center
            </a>
            <a href="?action=settings" class="nav-item <?php echo $action === 'settings' ? 'active' : ''; ?>">
                <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                Settings
            </a>
        </nav>
        <div class="sidebar-footer">
            <form method="POST" onsubmit="return confirm('Logout?');">
                <input type="hidden" name="post_action" value="logout">
                <button type="submit">Logout</button>
            </form>
        </div>
    </aside>
    
    <main class="main-content">
        <?php if ($msg): ?>
            <div class="alert alert-success" style="margin-bottom: 20px;"><?php echo htmlspecialchars($msg); ?></div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="alert alert-error" style="margin-bottom: 20px;"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        
        <?php if ($action === 'dashboard'): ?>
            <div class="page-header">
                <div>
                    <h2>Dashboard</h2>
                    <p>Overview of your leads and email activity</p>
                </div>
                <div class="account-selector">
                    <select onchange="if(this.value) window.open(this.value, '_blank')">
                        <option value="">Quick Open Email &rarr;</option>
                        <?php foreach ($accounts as $acc): 
                            global $PROVIDERS;
                            $preset = $PROVIDERS[$acc['provider']] ?? [];
                            $url = $preset['webmail_url'] ?? '';
                        ?>
                            <option value="<?php echo htmlspecialchars($url); ?>">
                                <?php echo htmlspecialchars($acc['name'] . ' (' . $acc['email'] . ')'); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            
            <div class="stats-grid">
                <div class="stat-card total">
                    <div class="label">Total Leads</div>
                    <div class="value"><?php echo number_format($stats['total'] ?? 0); ?></div>
                </div>
                <div class="stat-card new">
                    <div class="label">New Leads</div>
                    <div class="value"><?php echo number_format($stats['new'] ?? 0); ?></div>
                </div>
                <div class="stat-card contacted">
                    <div class="label">Contacted</div>
                    <div class="value"><?php echo number_format($stats['contacted'] ?? 0); ?></div>
                </div>
                <div class="stat-card converted">
                    <div class="label">Converted</div>
                    <div class="value"><?php echo number_format($stats['converted'] ?? 0); ?></div>
                </div>
            </div>
            
            <div class="card">
                <div class="card-header">
                    <h3>Lead Sources</h3>
                    <a href="?action=leads" class="btn btn-sm btn-secondary">View All</a>
                </div>
                <div class="card-body">
                    <?php if (!empty($stats['sources'])): ?>
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px;">
                            <?php foreach ($stats['sources'] as $src): ?>
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 12px 16px; background: var(--bg-secondary); border-radius: 8px;">
                                    <span style="text-transform: capitalize;"><?php echo htmlspecialchars($src['source']); ?></span>
                                    <span style="font-weight: 600; color: var(--accent);"><?php echo $src['count']; ?></span>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <p class="text-muted">No leads yet. Import from the Leads page.</p>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="card" style="margin-top: 20px;">
                <div class="card-header">
                    <h3>Connected Email Accounts</h3>
                    <a href="?action=emails" class="btn btn-sm btn-secondary">Manage</a>
                </div>
                <div class="card-body">
                    <?php if ($accounts): ?>
                        <div class="data-table-wrapper">
                            <table class="data-table">
                                <thead>
                                    <tr><th>Account</th><th>Provider</th><th>Email</th><th>Status</th></tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($accounts as $acc): ?>
                                        <tr>
                                            <td><strong><?php echo htmlspecialchars($acc['name']); ?></strong></td>
                                            <td style="text-transform: capitalize;"><?php echo htmlspecialchars($acc['provider']); ?></td>
                                            <td><?php echo htmlspecialchars($acc['email']); ?></td>
                                            <td><?php echo $acc['active'] ? '<span class="badge badge-converted">Active</span>' : '<span class="badge badge-lost">Inactive</span>'; ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <p class="text-muted">No email accounts connected. <a href="?action=emails" style="color: var(--accent);">Add your first account</a>.</p>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
        
        <?php if ($action === 'leads'): ?>
            <div class="page-header">
                <div>
                    <h2>Lead Management</h2>
                    <p>Manage and track all your leads</p>
                </div>
                <div style="display: flex; gap: 12px;">
                    <a href="?action=export" class="btn btn-secondary">Export CSV</a>
                    <button class="btn btn-primary" onclick="document.getElementById('leadModal').classList.add('active')">+ Add Lead</button>
                </div>
            </div>
            
            <form method="GET" class="toolbar">
                <input type="hidden" name="action" value="leads">
                <input type="text" name="search" placeholder="Search leads..." value="<?php echo htmlspecialchars($_GET['search'] ?? ''); ?>">
                <select name="status">
                    <option value="all">All Statuses</option>
                    <?php foreach ($statuses as $key => $label): ?>
                        <option value="<?php echo $key; ?>" <?php echo ($_GET['status'] ?? '') === $key ? 'selected' : ''; ?>><?php echo $label; ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="source">
                    <option value="all">All Sources</option>
                    <option value="warm" <?php echo ($_GET['source'] ?? '') === 'warm' ? 'selected' : ''; ?>>Warm</option>
                    <option value="scraped" <?php echo ($_GET['source'] ?? '') === 'scraped' ? 'selected' : ''; ?>>Scraped</option>
                    <option value="manual" <?php echo ($_GET['source'] ?? '') === 'manual' ? 'selected' : ''; ?>>Manual</option>
                    <option value="csv" <?php echo ($_GET['source'] ?? '') === 'csv' ? 'selected' : ''; ?>>CSV Import</option>
                </select>
                <button type="submit" class="btn btn-secondary">Filter</button>
                <a href="?action=leads" class="btn btn-secondary">Reset</a>
            </form>
            
            <form method="POST" enctype="multipart/form-data" style="margin-bottom: 20px;">
                <input type="hidden" name="post_action" value="import_csv">
                <div style="display: flex; gap: 12px; align-items: center;">
                    <input type="file" name="csv_file" accept=".csv" required style="color: var(--text-secondary);">
                    <button type="submit" class="btn btn-sm btn-secondary">Import CSV</button>
                    <span class="text-muted" style="font-size: 12px;">CSV columns: email, name, phone, company, source, status, notes</span>
                </div>
            </form>
            
            <div class="card">
                <div class="card-body" style="padding: 0;">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Email</th>
                                <th>Name</th>
                                <th>Company</th>
                                <th>Source</th>
                                <th>Status</th>
                                <th>Updated</th>
                                <th style="text-align: right;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($leadData['leads'] as $lead): ?>
                                <tr>
                                    <td><a href="mailto:<?php echo htmlspecialchars($lead['email']); ?>" style="color: var(--accent);"><?php echo htmlspecialchars($lead['email']); ?></a></td>
                                    <td><?php echo htmlspecialchars($lead['name'] ?: '-'); ?></td>
                                    <td><?php echo htmlspecialchars($lead['company'] ?: '-'); ?></td>
                                    <td><span class="badge badge-<?php echo $lead['source']; ?>"><?php echo ucfirst($lead['source']); ?></span></td>
                                    <td><span class="badge badge-<?php echo $lead['status']; ?>"><?php echo $statuses[$lead['status']] ?? ucfirst($lead['status']); ?></span></td>
                                    <td class="text-muted"><?php echo date('M j, Y', strtotime($lead['updated_at'])); ?></td>
                                    <td style="text-align: right;">
                                        <a href="?action=leads&edit=<?php echo $lead['id']; ?>" class="btn btn-sm btn-secondary">Edit</a>
                                        <form method="POST" style="display: inline;" onsubmit="return confirm('Delete this lead?');">
                                            <input type="hidden" name="post_action" value="delete_lead">
                                            <input type="hidden" name="id" value="<?php echo $lead['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-danger">Delete</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (empty($leadData['leads'])): ?>
                                <tr><td colspan="7" style="text-align: center; padding: 40px;" class="text-muted">No leads found. Add one or import from CSV.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <?php if ($leadData['pages'] > 1): ?>
                <div class="pagination">
                    <?php for ($i = 1; $i <= $leadData['pages']; $i++): ?>
                        <?php if ($i == $page): ?>
                            <span class="current"><?php echo $i; ?></span>
                        <?php else: ?>
                            <a href="?action=leads&page=<?php echo $i; ?>&search=<?php echo urlencode($_GET['search'] ?? ''); ?>&status=<?php echo urlencode($_GET['status'] ?? 'all'); ?>&source=<?php echo urlencode($_GET['source'] ?? 'all'); ?>"><?php echo $i; ?></a>
                        <?php endif; ?>
                    <?php endfor; ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>
        
        <?php if ($action === 'emails'): ?>
            <div class="page-header">
                <div>
                    <h2>Email Center</h2>
                    <p>Read and manage emails from all your accounts</p>
                </div>
                <div style="display: flex; gap: 12px;">
                    <button class="btn btn-primary" onclick="document.getElementById('accountModal').classList.add('active')">+ Add Account</button>
                </div>
            </div>

            <?php if (!imapCheck()): ?>
                <div class="alert alert-error" style="margin-bottom: 20px;">
                    <strong>PHP IMAP extension not installed.</strong> Email reading is disabled. Install it with: <code>apt-get install php-imap</code> (Ubuntu/Debian) or enable it in php.ini.
                </div>
            <?php endif; ?>

            <div class="card" style="margin-bottom: 20px;">
                <div class="card-body">
                    <form method="GET" class="toolbar" style="margin-bottom: 0;">
                        <input type="hidden" name="action" value="emails">
                        <select name="account_id" onchange="this.form.submit()">
                            <option value="">Select an email account...</option>
                            <?php foreach ($accounts as $acc): ?>
                                <option value="<?php echo $acc['id']; ?>" <?php echo ($currentAccount['id'] ?? '') == $acc['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($acc['name'] . ' <' . $acc['email'] . '>'); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if ($currentAccount): ?>
                            <select name="folder" onchange="this.form.submit()">
                                <?php
                                $folders = [];
                                if ($imapConn) {
                                    $folders = imapGetFolders($imapConn, $currentAccount);
                                }
                                $currentFolder = $_GET['folder'] ?? 'INBOX';
                                if (empty($folders)) $folders = ['INBOX'];
                                foreach ($folders as $f):
                                ?>
                                    <option value="<?php echo htmlspecialchars($f); ?>" <?php echo $currentFolder === $f ? 'selected' : ''; ?>><?php echo htmlspecialchars($f); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <a href="?action=emails&edit_account=<?php echo $currentAccount['id']; ?>" class="btn btn-sm btn-secondary">Edit Account</a>
                        <?php endif; ?>
                    </form>
                </div>
            </div>

            <?php if ($currentAccount): ?>
                <?php
                $preset = $PROVIDERS[$currentAccount['provider']] ?? [];
                $webmailUrl = $preset['webmail_url'] ?? '';
                $isRoundcube = $currentAccount['provider'] === 'roundcube';
                $isGmail = $currentAccount['provider'] === 'gmail';
                $isMailcom = $currentAccount['provider'] === 'mailcom';
                $isPorkbun = $currentAccount['provider'] === 'porkbun';
                ?>

                <div class="card" style="margin-bottom: 20px;">
                    <div class="card-body">
                        <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
                            <div>
                                <h3 style="margin-bottom: 4px;"><?php echo htmlspecialchars($currentAccount['name']); ?></h3>
                                <p class="text-muted"><?php echo htmlspecialchars($currentAccount['email']); ?></p>
                                <?php if (!empty($currentAccount['aliases'])): ?>
                                    <p class="text-muted" style="font-size: 12px;">Aliases: <?php echo htmlspecialchars($currentAccount['aliases']); ?></p>
                                <?php endif; ?>
                            </div>
                            <div style="display: flex; gap: 12px;">
                                <?php if ($webmailUrl): ?>
                                    <a href="<?php echo htmlspecialchars($webmailUrl); ?>" target="_blank" class="btn btn-secondary">Open Webmail</a>
                                <?php endif; ?>
                                <button class="btn btn-primary" onclick="openCompose('<?php echo htmlspecialchars($currentAccount['email']); ?>', '<?php echo htmlspecialchars($currentAccount['name']); ?>')">Compose</button>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if ($isRoundcube || ($currentAccount['provider'] === 'custom' && !empty($webmailUrl))): ?>
                    <div class="card" style="overflow: hidden;">
                        <div style="padding: 12px 20px; border-bottom: 1px solid var(--border); background: var(--bg-secondary); display: flex; justify-content: space-between; align-items: center;">
                            <span style="font-size: 13px; font-weight: 500;">Roundcube Webmail</span>
                            <span class="text-muted" style="font-size: 12px;">Full email client — send, receive, manage folders</span>
                        </div>
                        <iframe src="/rcube/" style="width: 100%; height: 700px; border: none;"></iframe>
                    </div>
                <?php elseif ($isGmail): ?>
                    <div class="card" style="text-align: center; padding: 60px 20px;">
                        <svg width="64" height="64" fill="none" stroke="var(--text-secondary)" stroke-width="1.5" viewBox="0 0 24 24" style="margin-bottom: 16px;"><path stroke-linecap="round" stroke-linejoin="round" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9"/></svg>
                        <h3 style="margin-bottom: 8px;">Gmail Blocks Iframes</h3>
                        <p class="text-muted" style="margin-bottom: 24px;">For security, Gmail cannot be embedded. Click below to open Gmail in a new tab.</p>
                        <a href="https://mail.google.com" target="_blank" class="btn btn-primary">Open Gmail</a>
                    </div>
                <?php elseif ($isMailcom): ?>
                    <div class="card" style="text-align: center; padding: 60px 20px;">
                        <svg width="64" height="64" fill="none" stroke="var(--text-secondary)" stroke-width="1.5" viewBox="0 0 24 24" style="margin-bottom: 16px;"><path stroke-linecap="round" stroke-linejoin="round" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9"/></svg>
                        <h3 style="margin-bottom: 8px;">Mail.com Blocks Iframes</h3>
                        <p class="text-muted" style="margin-bottom: 24px;">For security, Mail.com cannot be embedded. Click below to open Mail.com in a new tab.</p>
                        <a href="https://www.mail.com/int/mail/" target="_blank" class="btn btn-primary">Open Mail.com</a>
                    </div>
                <?php else: ?>
                    <?php if (!$imapConn): ?>
                        <div class="alert alert-error">Could not connect to <?php echo htmlspecialchars($currentAccount['imap_server']); ?>. Check your credentials and make sure IMAP is enabled.</div>
                        <p class="text-muted">
                            <strong>Gmail users:</strong> You must use an <a href="https://myaccount.google.com/apppasswords" target="_blank" style="color: var(--accent);">App Password</a>, not your regular password.
                        </p>
                    <?php else: ?>
                        <?php if ($viewEmail): ?>
                            <div class="email-reading" style="margin-bottom: 20px;">
                                <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 16px; flex-wrap: wrap; gap: 12px;">
                                    <div>
                                        <h3><?php echo htmlspecialchars($viewEmail['subject']); ?></h3>
                                        <div class="meta" style="margin-top: 4px;">
                                            <strong>From:</strong> <?php echo htmlspecialchars($viewEmail['from']); ?><br>
                                            <strong>To:</strong> <?php echo htmlspecialchars($viewEmail['to']); ?><br>
                                            <strong>Date:</strong> <?php echo date('M j, Y g:i A', strtotime($viewEmail['date'])); ?>
                                        </div>
                                    </div>
                                    <div style="display: flex; gap: 8px;">
                                        <a href="?action=emails&account_id=<?php echo $currentAccount['id']; ?>&folder=<?php echo urlencode($currentFolder); ?>" class="btn btn-sm btn-secondary">&larr; Back</a>
                                        <button class="btn btn-sm btn-primary" onclick="openCompose('<?php echo htmlspecialchars($currentAccount['email']); ?>', '<?php echo htmlspecialchars($currentAccount['name']); ?>', '<?php echo htmlspecialchars($viewEmail['from']); ?>', 'Re: <?php echo htmlspecialchars(addslashes($viewEmail['subject'])); ?>', '')">Reply</button>
                                    </div>
                                </div>
                                <div class="body" style="border-top: 1px solid var(--border); padding-top: 16px;">
                                    <?php if ($viewEmail['html']): ?>
                                        <div style="max-width: 100%; overflow-x: auto;"><?php echo $viewEmail['html']; ?></div>
                                    <?php else: ?>
                                        <?php echo $viewEmail['text']; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="email-layout">
                                <div class="folder-list">
                                    <div style="font-weight: 600; margin-bottom: 12px; font-size: 14px;">Folders</div>
                                    <?php foreach ($folders as $f): ?>
                                        <a href="?action=emails&account_id=<?php echo $currentAccount['id']; ?>&folder=<?php echo urlencode($f); ?>" class="folder-item <?php echo $currentFolder === $f ? 'active' : ''; ?>" style="text-decoration: none; color: inherit;">
                                            <?php echo htmlspecialchars($f); ?>
                                        </a>
                                    <?php endforeach; ?>
                                </div>
                                <div>
                                    <div class="email-list">
                                        <?php if (empty($emailsData['emails'])): ?>
                                            <div style="padding: 40px; text-align: center;" class="text-muted">No emails in this folder.</div>
                                        <?php endif; ?>
                                        <?php foreach ($emailsData['emails'] as $email): ?>
                                            <a href="?action=emails&account_id=<?php echo $currentAccount['id']; ?>&folder=<?php echo urlencode($currentFolder); ?>&view_uid=<?php echo $email['uid']; ?>" class="email-item <?php echo $email['seen'] ? '' : 'unseen'; ?>" style="text-decoration: none; color: inherit; display: block;">
                                                <div class="subject"><?php echo htmlspecialchars($email['subject']); ?> <?php echo $email['seen'] ? '' : '<span style="color: var(--accent); font-size: 11px;">NEW</span>'; ?></div>
                                                <div class="meta">From: <?php echo htmlspecialchars($email['from']); ?> &bull; <?php echo date('M j, g:i A', strtotime($email['date'])); ?></div>
                                                <div class="preview"><?php echo htmlspecialchars($email['preview']); ?>...</div>
                                            </a>
                                        <?php endforeach; ?>
                                    </div>
                                    <?php if ($emailsData['total'] > ITEMS_PER_PAGE): ?>
                                        <div class="pagination">
                                            <?php for ($i = 1; $i <= ceil($emailsData['total'] / ITEMS_PER_PAGE); $i++): ?>
                                                <?php if ($i == $page): ?>
                                                    <span class="current"><?php echo $i; ?></span>
                                                <?php else: ?>
                                                    <a href="?action=emails&account_id=<?php echo $currentAccount['id']; ?>&folder=<?php echo urlencode($currentFolder); ?>&page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                                <?php endif; ?>
                                            <?php endfor; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                <?php endif; ?>
            <?php else: ?>
                <div class="card" style="margin-bottom: 20px; overflow: hidden;">
                    <div style="padding: 16px 20px; border-bottom: 1px solid var(--border); background: var(--bg-secondary); display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <span style="font-size: 16px; font-weight: 600;">Roundcube Webmail</span>
                            <span class="text-muted" style="font-size: 13px; margin-left: 12px;">Your primary email client — all sending & receiving happens here</span>
                        </div>
                        <a href="/rcube/" target="_blank" class="btn btn-sm btn-secondary">Open in New Tab</a>
                    </div>
                    <iframe src="/rcube/" style="width: 100%; height: 700px; border: none;"></iframe>
                </div>

                <div class="card">
                    <div class="card-header"><h3>Configured Accounts</h3></div>
                    <div class="card-body" style="padding: 0;">
                        <table class="data-table">
                            <thead>
                                <tr><th>Name</th><th>Email</th><th>Provider</th><th>Aliases</th><th style="text-align: right;">Actions</th></tr>
                            </thead>
                            <tbody>
                                <?php foreach ($accounts as $acc):
                                    $accPreset = $PROVIDERS[$acc['provider']] ?? [];
                                    $accUrl = $accPreset['webmail_url'] ?? '';
                                ?>
                                    <tr>
                                        <td><strong><?php echo htmlspecialchars($acc['name']); ?></strong></td>
                                        <td><?php echo htmlspecialchars($acc['email']); ?></td>
                                        <td style="text-transform: capitalize;"><?php echo htmlspecialchars($acc['provider']); ?></td>
                                        <td class="text-muted"><?php echo htmlspecialchars($acc['aliases'] ?: '—'); ?></td>
                                        <td style="text-align: right;">
                                            <a href="?action=emails&edit_account=<?php echo $acc['id']; ?>" class="btn btn-sm btn-secondary">Edit</a>
                                            <form method="POST" style="display: inline;" onsubmit="return confirm('Delete this account?');">
                                                <input type="hidden" name="post_action" value="delete_account">
                                                <input type="hidden" name="id" value="<?php echo $acc['id']; ?>">
                                                <button type="submit" class="btn btn-sm btn-danger">Delete</button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                <?php if (empty($accounts)): ?>
                                    <tr><td colspan="5" style="text-align: center; padding: 40px;" class="text-muted">No accounts configured. <a href="#" onclick="document.getElementById('accountModal').classList.add('active'); return false;" style="color: var(--accent);">Add one now</a>.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php endif; ?>
        <?php endif; ?>
        
        <?php if ($action === 'settings'): ?>
            <div class="page-header">
                <div>
                    <h2>Settings</h2>
                    <p>Manage your account and application preferences</p>
                </div>
            </div>
            
            <div class="card" style="max-width: 600px;">
                <div class="card-header"><h3>Change Password</h3></div>
                <div class="card-body">
                    <form method="POST">
                        <input type="hidden" name="post_action" value="change_password">
                        <div class="form-group" style="margin-bottom: 16px;">
                            <label>New Password</label>
                            <input type="password" name="new_password" required>
                        </div>
                        <div class="form-group" style="margin-bottom: 16px;">
                            <label>Confirm Password</label>
                            <input type="password" name="confirm_password" required>
                        </div>
                        <button type="submit" class="btn btn-primary">Update Password</button>
                    </form>
                </div>
            </div>
            
            <div class="card" style="max-width: 600px; margin-top: 20px;">
                <div class="card-header"><h3>Database Info</h3></div>
                <div class="card-body">
                    <p class="text-muted">Database file: <code><?php echo DB_FILE; ?></code></p>
                    <p class="text-muted">Leads: <?php echo $stats['total'] ?? 0; ?></p>
                    <p class="text-muted">Email Accounts: <?php echo count($accounts); ?></p>
                    <p style="margin-top: 12px; font-size: 13px; color: var(--text-secondary);">
                        To backup: download <code>bossmail_data.db</code> from your server.
                    </p>
                </div>
            </div>

            <div class="card" style="max-width: 800px; margin-top: 20px;">
                <div class="card-header"><h3>💰 Stop Wasting Money on Porkbun Email Hosting</h3></div>
                <div class="card-body">
                    <p class="text-muted" style="margin-bottom: 16px;">
                        You are currently paying Porkbun for individual email mailboxes for every website. 
                        Use this <strong>free method</strong> to get <code>info@yoursite.com</code> for every domain without paying for multiple mailboxes.
                    </p>

                    <h4 style="margin-bottom: 8px; color: var(--accent);">Step 1: Keep ONE Mailbox</h4>
                    <p class="text-muted" style="margin-bottom: 16px;">
                        Keep only <strong>one</strong> Porkbun email hosting subscription (e.g., <code>boss@canadianhealthplans.ca</code>). 
                        Cancel all the others. You only need one real mailbox.
                    </p>

                    <h4 style="margin-bottom: 8px; color: var(--accent);">Step 2: Free Email Forwarding (All Other Domains)</h4>
                    <p class="text-muted" style="margin-bottom: 16px;">
                        In your Porkbun dashboard, go to each domain and set up <strong>Email Forwarding</strong> (it's free).<br>
                        Forward <code>info@site1.com</code> → <code>boss@canadianhealthplans.ca</code><br>
                        Forward <code>info@site2.com</code> → <code>boss@canadianhealthplans.ca</code><br>
                        Do this for <strong>every domain</strong>. Porkbun forwarding is free and instant.
                    </p>

                    <h4 style="margin-bottom: 8px; color: var(--accent);">Step 3: Add Your One Mailbox to BossMail</h4>
                    <p class="text-muted" style="margin-bottom: 16px;">
                        Add your one remaining mailbox here in BossMail using the <strong>Porkbun</strong> provider preset.<br>
                        In the account form, add all your <code>info@</code> addresses in the <strong>Aliases</strong> field (comma-separated).<br>
                        Example: <code>info@site1.com, info@site2.com, info@site3.com</code>
                    </p>

                    <h4 style="margin-bottom: 8px; color: var(--accent);">Step 4: Send From Any Address</h4>
                    <p class="text-muted" style="margin-bottom: 16px;">
                        When you compose an email in BossMail, the <strong>From</strong> dropdown will show all your aliases.<br>
                        Select <code>info@site1.com</code> and send. Replies will come back to your one inbox because of the forwarding.
                    </p>

                    <h4 style="margin-bottom: 8px; color: var(--accent);">Step 5: Optional — Set Up Reply-To</h4>
                    <p class="text-muted" style="margin-bottom: 16px;">
                        If Porkbun blocks sending from aliases, you can use a service like <strong>Amazon SES</strong> or <strong>SendGrid</strong> for SMTP sending. 
                        Their free tiers handle thousands of emails per month.
                    </p>

                    <div class="alert alert-success" style="margin-top: 20px;">
                        <strong>Result:</strong> You pay for <strong>ONE</strong> Porkbun mailbox instead of one per website. 
                        All emails arrive in one place. You can send from any alias. BossMail handles the rest.
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </main>
</div>

<!-- Lead Modal -->
<div class="modal-overlay" id="leadModal">
    <div class="modal">
        <div class="modal-header">
            <h3><?php echo $leadEdit ? 'Edit Lead' : 'Add New Lead'; ?></h3>
            <button class="modal-close" onclick="document.getElementById('leadModal').classList.remove('active')">&times;</button>
        </div>
        <form method="POST">
            <div class="modal-body">
                <input type="hidden" name="post_action" value="save_lead">
                <?php if ($leadEdit): ?><input type="hidden" name="id" value="<?php echo $leadEdit['id']; ?>"><?php endif; ?>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Email *</label>
                        <input type="email" name="email" value="<?php echo htmlspecialchars($leadEdit['email'] ?? ''); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Name</label>
                        <input type="text" name="name" value="<?php echo htmlspecialchars($leadEdit['name'] ?? ''); ?>">
                    </div>
                    <div class="form-group">
                        <label>Phone</label>
                        <input type="text" name="phone" value="<?php echo htmlspecialchars($leadEdit['phone'] ?? ''); ?>">
                    </div>
                    <div class="form-group">
                        <label>Company</label>
                        <input type="text" name="company" value="<?php echo htmlspecialchars($leadEdit['company'] ?? ''); ?>">
                    </div>
                    <div class="form-group">
                        <label>Source</label>
                        <select name="source">
                            <option value="manual" <?php echo ($leadEdit['source'] ?? '') === 'manual' ? 'selected' : ''; ?>>Manual</option>
                            <option value="warm" <?php echo ($leadEdit['source'] ?? '') === 'warm' ? 'selected' : ''; ?>>Warm Lead</option>
                            <option value="scraped" <?php echo ($leadEdit['source'] ?? '') === 'scraped' ? 'selected' : ''; ?>>Scraped</option>
                            <option value="csv" <?php echo ($leadEdit['source'] ?? '') === 'csv' ? 'selected' : ''; ?>>CSV Import</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Status</label>
                        <select name="status">
                            <?php foreach ($statuses as $key => $label): ?>
                                <option value="<?php echo $key; ?>" <?php echo ($leadEdit['status'] ?? 'new') === $key ? 'selected' : ''; ?>><?php echo $label; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group full">
                        <label>Notes</label>
                        <textarea name="notes"><?php echo htmlspecialchars($leadEdit['notes'] ?? ''); ?></textarea>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="document.getElementById('leadModal').classList.remove('active')">Cancel</button>
                <button type="submit" class="btn btn-primary">Save Lead</button>
            </div>
        </form>
    </div>
</div>

<!-- Account Modal -->
<div class="modal-overlay" id="accountModal">
    <div class="modal">
        <div class="modal-header">
            <h3><?php echo $accountEdit ? 'Edit Email Account' : 'Add Email Account'; ?></h3>
            <button class="modal-close" onclick="document.getElementById('accountModal').classList.remove('active')">&times;</button>
        </div>
        <form method="POST">
            <div class="modal-body">
                <input type="hidden" name="post_action" value="save_account">
                <?php if ($accountEdit): ?><input type="hidden" name="id" value="<?php echo $accountEdit['id']; ?>"><?php endif; ?>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Account Name *</label>
                        <input type="text" name="name" placeholder="Work Gmail" value="<?php echo htmlspecialchars($accountEdit['name'] ?? ''); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Provider *</label>
                        <select name="provider" id="providerSelect" onchange="applyPreset(this.value)">
                            <option value="gmail" <?php echo ($accountEdit['provider'] ?? '') === 'gmail' ? 'selected' : ''; ?>>Gmail</option>
                            <option value="mailcom" <?php echo ($accountEdit['provider'] ?? '') === 'mailcom' ? 'selected' : ''; ?>>Mail.com</option>
                            <option value="porkbun" <?php echo ($accountEdit['provider'] ?? '') === 'porkbun' ? 'selected' : ''; ?>>Porkbun Email</option>
                            <option value="roundcube" <?php echo ($accountEdit['provider'] ?? '') === 'roundcube' ? 'selected' : ''; ?>>Roundcube</option>
                            <option value="custom" <?php echo ($accountEdit['provider'] ?? '') === 'custom' ? 'selected' : ''; ?>>Custom IMAP</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Email Address *</label>
                        <input type="email" name="email" value="<?php echo htmlspecialchars($accountEdit['email'] ?? ''); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Username (if different)</label>
                        <input type="text" name="username" value="<?php echo htmlspecialchars($accountEdit['username'] ?? ''); ?>" placeholder="Usually same as email">
                    </div>
                    <div class="form-group">
                        <label>Password / App Password *</label>
                        <input type="password" name="password" placeholder="<?php echo $accountEdit ? 'Leave blank to keep current' : ''; ?>">
                        <span class="text-muted" style="font-size: 12px;">Gmail users: use an <a href="https://myaccount.google.com/apppasswords" target="_blank" style="color: var(--accent);">App Password</a></span>
                    </div>
                    <div class="form-group">
                        <label>IMAP Server</label>
                        <input type="text" name="imap_server" id="imapServer" value="<?php echo htmlspecialchars($accountEdit['imap_server'] ?? 'imap.gmail.com'); ?>">
                    </div>
                    <div class="form-group">
                        <label>IMAP Port</label>
                        <input type="number" name="imap_port" id="imapPort" value="<?php echo htmlspecialchars($accountEdit['imap_port'] ?? '993'); ?>">
                    </div>
                    <div class="form-group">
                        <label>SMTP Server</label>
                        <input type="text" name="smtp_server" id="smtpServer" value="<?php echo htmlspecialchars($accountEdit['smtp_server'] ?? 'smtp.gmail.com'); ?>">
                    </div>
                    <div class="form-group">
                        <label>SMTP Port</label>
                        <input type="number" name="smtp_port" id="smtpPort" value="<?php echo htmlspecialchars($accountEdit['smtp_port'] ?? '587'); ?>">
                    </div>
                    <div class="form-group">
                        <label>Use SSL</label>
                        <select name="use_ssl">
                            <option value="1" <?php echo ($accountEdit['use_ssl'] ?? 1) == 1 ? 'selected' : ''; ?>>Yes</option>
                            <option value="0" <?php echo ($accountEdit['use_ssl'] ?? 1) == 0 ? 'selected' : ''; ?>>No</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Sort Order</label>
                        <input type="number" name="sort_order" value="<?php echo htmlspecialchars($accountEdit['sort_order'] ?? '0'); ?>">
                    </div>
                    <div class="form-group full">
                        <label>Email Aliases (comma-separated)</label>
                        <input type="text" name="aliases" value="<?php echo htmlspecialchars($accountEdit['aliases'] ?? ''); ?>" placeholder="info@site1.com, info@site2.com">
                        <span class="text-muted" style="font-size: 12px;">Additional addresses you can send from using this account's SMTP server</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="document.getElementById('accountModal').classList.remove('active')">Cancel</button>
                <button type="submit" class="btn btn-primary">Save Account</button>
            </div>
        </form>
    </div>
</div>

<!-- Compose Modal -->
<div class="modal-overlay" id="composeModal">
    <div class="modal" style="max-width: 700px;">
        <div class="modal-header">
            <h3>Compose Email</h3>
            <button class="modal-close" onclick="document.getElementById('composeModal').classList.remove('active')">&times;</button>
        </div>
        <form method="POST">
            <div class="modal-body">
                <input type="hidden" name="post_action" value="send_email">
                <input type="hidden" name="account_id" id="composeAccountId" value="<?php echo $currentAccount['id'] ?? ''; ?>">
                <div class="form-grid">
                    <div class="form-group full">
                        <label>From</label>
                        <select name="from_email" id="composeFrom" style="width: 100%;">
                            <?php if ($currentAccount): ?>
                                <option value="<?php echo htmlspecialchars($currentAccount['email']); ?>"><?php echo htmlspecialchars($currentAccount['name'] . ' <' . $currentAccount['email'] . '>'); ?></option>
                                <?php foreach (array_filter(array_map('trim', explode(',', $currentAccount['aliases'] ?? ''))) as $alias): ?>
                                    <option value="<?php echo htmlspecialchars($alias); ?>"><?php echo htmlspecialchars($alias); ?></option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    </div>
                    <div class="form-group full">
                        <label>To *</label>
                        <input type="text" name="to" id="composeTo" placeholder="recipient@example.com" required>
                    </div>
                    <div class="form-group full">
                        <label>Subject *</label>
                        <input type="text" name="subject" id="composeSubject" placeholder="Email subject" required>
                    </div>
                    <div class="form-group full">
                        <label>Message *</label>
                        <textarea name="body" id="composeBody" rows="10" placeholder="Type your message here... HTML is supported." required></textarea>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="document.getElementById('composeModal').classList.remove('active')">Cancel</button>
                <button type="submit" class="btn btn-primary">Send Email</button>
            </div>
        </form>
    </div>
</div>

<script>
const presets = {
    gmail: { imap: 'imap.gmail.com', imapPort: 993, smtp: 'smtp.gmail.com', smtpPort: 587 },
    mailcom: { imap: 'imap.mail.com', imapPort: 993, smtp: 'smtp.mail.com', smtpPort: 587 },
    porkbun: { imap: 'mail.porkbun.com', imapPort: 993, smtp: 'mail.porkbun.com', smtpPort: 587 },
    roundcube: { imap: '', imapPort: 993, smtp: '', smtpPort: 587 },
    custom: { imap: '', imapPort: 993, smtp: '', smtpPort: 587 }
};
function applyPreset(provider) {
    const p = presets[provider];
    if (p) {
        document.getElementById('imapServer').value = p.imap;
        document.getElementById('imapPort').value = p.imapPort;
        document.getElementById('smtpServer').value = p.smtp;
        document.getElementById('smtpPort').value = p.smtpPort;
    }
}
function openCompose(email, name, to, subject, body) {
    document.getElementById('composeModal').classList.add('active');
    if (to) document.getElementById('composeTo').value = to;
    if (subject) document.getElementById('composeSubject').value = subject;
    if (body) document.getElementById('composeBody').value = body;
}
<?php if ($leadEdit): ?>document.getElementById('leadModal').classList.add('active');<?php endif; ?>
<?php if ($accountEdit): ?>document.getElementById('accountModal').classList.add('active');<?php endif; ?>
</script>

<?php endif; ?>
</body>
</html>
