<?php
/**
 * FB Lead Receiver — Admin UI
 * -----------------------------------------------------------------
 * Lets you add/edit page tokens, form->project mappings, and the
 * shared settings (verify token, master token, XD CRM url/secret)
 * WITHOUT touching fb_receiver.php or the database directly.
 *
 * Deploy this file next to fb_receiver.php, then:
 *   1) Change ADMIN_PASSWORD_HASH below (see the comment there).
 *   2) Visit this file in your browser and log in.
 * -----------------------------------------------------------------
 */

session_start();

// =========================================================
// 0) CONFIG — same DB the receiver uses
// =========================================================
$db_host = "localhost";
$db_user = "theniralatrio_root";
$db_pass = 'Kamal@321';
$db_name = "theniralatrio_lead";

// Default password is "changeme123" — CHANGE THIS before putting the file
// online. Generate a new hash with:  php -r "echo password_hash('yourpass', PASSWORD_DEFAULT);"
define('ADMIN_PASSWORD_HASH', '$2b$10$WXwroUbmdZcfz462ISp0zejLT6uMjIefjBLLdLGPPbw7U29JrPV46');

$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) {
    die('DB connection failed: ' . htmlspecialchars($conn->connect_error));
}

// =========================================================
// 1) LOGIN / LOGOUT
// =========================================================
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ' . basename(__FILE__));
    exit;
}

if (!isset($_SESSION['is_admin'])) {
    $login_error = '';

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password'])) {
        if (password_verify($_POST['password'], ADMIN_PASSWORD_HASH)) {
            session_regenerate_id(true);
            $_SESSION['is_admin'] = true;
        } else {
            $login_error = 'Wrong password.';
        }
    }

    if (!isset($_SESSION['is_admin'])) {
        renderLoginPage($login_error);
        exit;
    }
}

// CSRF token for all forms on this page
if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf'];

function checkCsrf(): void
{
    if (!isset($_POST['csrf']) || !hash_equals($_SESSION['csrf'], $_POST['csrf'])) {
        die('Invalid or expired form submission. Please go back and try again.');
    }
}

// =========================================================
// 2) HANDLE POST ACTIONS
// =========================================================
$flash = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    checkCsrf();
    $action = $_POST['form_action'] ?? '';

    // ---- Pages: add or update ----
    if ($action === 'save_page') {
        $id             = (int) ($_POST['id'] ?? 0);
        $page_id        = trim($_POST['page_id']);
        $access_token   = trim($_POST['access_token']);
        $default_source = trim($_POST['default_source']);
        $is_active      = isset($_POST['is_active']) ? 1 : 0;

        if ($page_id === '' || $access_token === '') {
            $flash = 'Page ID and Access Token are required.';
        } elseif ($id > 0) {
            $stmt = $conn->prepare("UPDATE fb_pages SET page_id=?, access_token=?, default_source=?, is_active=? WHERE id=?");
            $stmt->bind_param('sssii', $page_id, $access_token, $default_source, $is_active, $id);
            $stmt->execute();
            $stmt->close();
            $flash = 'Page updated.';
        } else {
            $stmt = $conn->prepare("INSERT INTO fb_pages (page_id, access_token, default_source, is_active) VALUES (?,?,?,?)
                                     ON DUPLICATE KEY UPDATE access_token=VALUES(access_token), default_source=VALUES(default_source), is_active=VALUES(is_active)");
            $stmt->bind_param('sssi', $page_id, $access_token, $default_source, $is_active);
            $stmt->execute();
            $stmt->close();
            $flash = 'Page added.';
        }
    }

    if ($action === 'delete_page') {
        $id = (int) ($_POST['id'] ?? 0);
        $stmt = $conn->prepare("DELETE FROM fb_pages WHERE id = ?");
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $stmt->close();
        $flash = 'Page deleted.';
    }

    // ---- Form mappings: add or update ----
    if ($action === 'save_form') {
        $id              = (int) ($_POST['id'] ?? 0);
        $form_id         = trim($_POST['form_id']);
        $project_name    = trim($_POST['project_name']);
        $route_to_xd_crm = isset($_POST['route_to_xd_crm']) ? 1 : 0;

        if ($form_id === '' || $project_name === '') {
            $flash = 'Form ID and Project Name are required.';
        } elseif ($id > 0) {
            $stmt = $conn->prepare("UPDATE fb_form_mapping SET form_id=?, project_name=?, route_to_xd_crm=? WHERE id=?");
            $stmt->bind_param('ssii', $form_id, $project_name, $route_to_xd_crm, $id);
            $stmt->execute();
            $stmt->close();
            $flash = 'Form mapping updated.';
        } else {
            $stmt = $conn->prepare("INSERT INTO fb_form_mapping (form_id, project_name, route_to_xd_crm) VALUES (?,?,?)
                                     ON DUPLICATE KEY UPDATE project_name=VALUES(project_name), route_to_xd_crm=VALUES(route_to_xd_crm)");
            $stmt->bind_param('ssi', $form_id, $project_name, $route_to_xd_crm);
            $stmt->execute();
            $stmt->close();
            $flash = 'Form mapping added.';
        }
    }

    if ($action === 'delete_form') {
        $id = (int) ($_POST['id'] ?? 0);
        $stmt = $conn->prepare("DELETE FROM fb_form_mapping WHERE id = ?");
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $stmt->close();
        $flash = 'Form mapping deleted.';
    }

    // ---- Settings: always update the single row (id = 1) ----
    if ($action === 'save_settings') {
        $webhook_verify_token = trim($_POST['webhook_verify_token']);
        $master_token         = trim($_POST['master_token']);
        $xd_crm_url           = trim($_POST['xd_crm_url']);
        $xd_crm_secret        = trim($_POST['xd_crm_secret']);

        $stmt = $conn->prepare("UPDATE fb_settings SET webhook_verify_token=?, master_token=?, xd_crm_url=?, xd_crm_secret=? WHERE id = 1");
        $stmt->bind_param('ssss', $webhook_verify_token, $master_token, $xd_crm_url, $xd_crm_secret);
        $stmt->execute();
        $stmt->close();
        $flash = 'Settings saved.';
    }
}

// =========================================================
// 3) FETCH DATA FOR THE CURRENT TAB
// =========================================================
$tab = $_GET['tab'] ?? 'pages';

$pages = $conn->query("SELECT * FROM fb_pages ORDER BY page_id")->fetch_all(MYSQLI_ASSOC);
$forms = $conn->query("SELECT * FROM fb_form_mapping ORDER BY project_name")->fetch_all(MYSQLI_ASSOC);
$settings = $conn->query("SELECT * FROM fb_settings WHERE id = 1 LIMIT 1")->fetch_assoc() ?: [];

// Edit-mode: if ?edit_page=ID or ?edit_form=ID is present, pre-fill the add form with that row
$editing_page = null;
if (isset($_GET['edit_page'])) {
    foreach ($pages as $p) {
        if ($p['id'] == $_GET['edit_page']) { $editing_page = $p; break; }
    }
}
$editing_form = null;
if (isset($_GET['edit_form'])) {
    foreach ($forms as $f) {
        if ($f['id'] == $_GET['edit_form']) { $editing_form = $f; break; }
    }
}

function h($v) { return htmlspecialchars((string) $v, ENT_QUOTES); }
function maskToken($t) {
    $t = (string) $t;
    return strlen($t) > 18 ? substr($t, 0, 10) . '…' . substr($t, -6) : $t;
}

// =========================================================
// 4) RENDER
// =========================================================
function renderLoginPage($error) {
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>FB Receiver Admin — Login</title>
<style><?php echo baseCss(); ?></style>
</head>
<body>
<div class="login-box">
    <h2>🔐 FB Receiver Admin</h2>
    <?php if ($error): ?><div class="flash error"><?php echo h($error); ?></div><?php endif; ?>
    <form method="post">
        <input type="password" name="password" placeholder="Password" autofocus required>
        <button type="submit">Log in</button>
    </form>
</div>
</body>
</html>
<?php
}

function baseCss() {
    return <<<CSS
        * { box-sizing: border-box; }
        body { font-family: -apple-system, Segoe UI, Roboto, Arial, sans-serif; background:#f5f6fa; margin:0; color:#1f2430; }
        .login-box { max-width:340px; margin:120px auto; background:#fff; padding:32px; border-radius:12px; box-shadow:0 4px 20px rgba(0,0,0,.08); text-align:center; }
        .login-box h2 { margin-top:0; }
        .login-box input { width:100%; padding:10px; margin-bottom:12px; border:1px solid #ddd; border-radius:8px; font-size:14px; }
        .login-box button { width:100%; padding:10px; background:#4f46e5; color:#fff; border:none; border-radius:8px; font-size:14px; cursor:pointer; }
        .topbar { background:#fff; border-bottom:1px solid #eee; padding:14px 28px; display:flex; justify-content:space-between; align-items:center; }
        .topbar h1 { font-size:18px; margin:0; }
        .topbar a.logout { color:#888; font-size:13px; text-decoration:none; }
        .tabs { display:flex; gap:6px; padding:16px 28px 0; }
        .tabs a { padding:8px 16px; border-radius:8px 8px 0 0; text-decoration:none; color:#555; font-size:13px; font-weight:600; background:#eceef2; }
        .tabs a.active { background:#fff; color:#4f46e5; }
        .wrap { padding:20px 28px 60px; max-width:1100px; margin:0 auto; }
        .card { background:#fff; border-radius:12px; padding:20px; margin-bottom:20px; box-shadow:0 1px 4px rgba(0,0,0,.04); }
        .card h3 { margin-top:0; font-size:15px; }
        table { width:100%; border-collapse:collapse; font-size:13px; }
        th, td { text-align:left; padding:8px 10px; border-bottom:1px solid #f0f0f0; }
        th { color:#888; font-size:11px; text-transform:uppercase; letter-spacing:.04em; }
        .badge { display:inline-block; padding:2px 8px; border-radius:20px; font-size:11px; font-weight:700; }
        .badge.on { background:#dcfce7; color:#166534; }
        .badge.off { background:#fee2e2; color:#991b1b; }
        .row-actions a, .row-actions button { font-size:12px; color:#4f46e5; text-decoration:none; background:none; border:none; cursor:pointer; padding:0; margin-right:10px; }
        .row-actions button.danger { color:#dc2626; }
        form.inline { display:flex; gap:10px; flex-wrap:wrap; align-items:flex-end; }
        .fg { display:flex; flex-direction:column; gap:4px; }
        .fg label { font-size:11px; color:#888; text-transform:uppercase; letter-spacing:.03em; }
        .fg input[type=text], .fg input[type=url] { padding:8px 10px; border:1px solid #ddd; border-radius:8px; font-size:13px; min-width:180px; }
        .fg.wide input { min-width:340px; }
        .fg.checkbox { flex-direction:row; align-items:center; gap:6px; }
        .btn { padding:8px 16px; background:#4f46e5; color:#fff; border:none; border-radius:8px; font-size:13px; cursor:pointer; }
        .btn.cancel { background:#fff; color:#888; border:1px solid #ddd; text-decoration:none; display:inline-flex; align-items:center; }
        .flash { padding:10px 14px; border-radius:8px; margin-bottom:16px; font-size:13px; background:#dbeafe; color:#1e40af; }
        .flash.error { background:#fee2e2; color:#991b1b; }
CSS;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>FB Receiver Admin</title>
<style><?php echo baseCss(); ?></style>
</head>
<body>

<div class="topbar">
    <h1>📡 FB Receiver Admin</h1>
    <a class="logout" href="?logout=1">Log out</a>
</div>

<div class="tabs">
    <a href="?tab=pages" class="<?php echo $tab === 'pages' ? 'active' : ''; ?>">Pages &amp; Tokens</a>
    <a href="?tab=forms" class="<?php echo $tab === 'forms' ? 'active' : ''; ?>">Form Mapping</a>
    <a href="?tab=settings" class="<?php echo $tab === 'settings' ? 'active' : ''; ?>">Settings</a>
</div>

<div class="wrap">

<?php if ($flash): ?><div class="flash"><?php echo h($flash); ?></div><?php endif; ?>

<?php if ($tab === 'pages'): ?>

    <div class="card">
        <h3><?php echo $editing_page ? 'Edit Page' : 'Add New Page'; ?></h3>
        <form method="post" class="inline">
            <input type="hidden" name="csrf" value="<?php echo h($csrf); ?>">
            <input type="hidden" name="form_action" value="save_page">
            <input type="hidden" name="id" value="<?php echo h($editing_page['id'] ?? 0); ?>">

            <div class="fg">
                <label>Page ID</label>
                <input type="text" name="page_id" value="<?php echo h($editing_page['page_id'] ?? ''); ?>" required>
            </div>
            <div class="fg wide">
                <label>Access Token</label>
                <input type="text" name="access_token" value="<?php echo h($editing_page['access_token'] ?? ''); ?>" required>
            </div>
            <div class="fg">
                <label>Default Source (optional)</label>
                <input type="text" name="default_source" value="<?php echo h($editing_page['default_source'] ?? ''); ?>" placeholder="Digital Marketing XD">
            </div>
            <div class="fg checkbox">
                <input type="checkbox" name="is_active" id="is_active" <?php echo (!isset($editing_page) || $editing_page['is_active']) ? 'checked' : ''; ?>>
                <label for="is_active" style="text-transform:none;">Active</label>
            </div>
            <button type="submit" class="btn"><?php echo $editing_page ? 'Update' : 'Add Page'; ?></button>
            <?php if ($editing_page): ?><a href="?tab=pages" class="btn cancel">Cancel</a><?php endif; ?>
        </form>
    </div>

    <div class="card">
        <h3>All Pages (<?php echo count($pages); ?>)</h3>
        <table>
            <tr><th>Page ID</th><th>Token</th><th>Default Source</th><th>Status</th><th></th></tr>
            <?php foreach ($pages as $p): ?>
            <tr>
                <td><?php echo h($p['page_id']); ?></td>
                <td title="<?php echo h($p['access_token']); ?>"><?php echo h(maskToken($p['access_token'])); ?></td>
                <td><?php echo h($p['default_source'] ?: '—'); ?></td>
                <td><span class="badge <?php echo $p['is_active'] ? 'on' : 'off'; ?>"><?php echo $p['is_active'] ? 'Active' : 'Inactive'; ?></span></td>
                <td class="row-actions">
                    <a href="?tab=pages&edit_page=<?php echo (int) $p['id']; ?>">Edit</a>
                    <form method="post" style="display:inline" onsubmit="return confirm('Delete this page?');">
                        <input type="hidden" name="csrf" value="<?php echo h($csrf); ?>">
                        <input type="hidden" name="form_action" value="delete_page">
                        <input type="hidden" name="id" value="<?php echo (int) $p['id']; ?>">
                        <button type="submit" class="danger">Delete</button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
        </table>
    </div>

<?php elseif ($tab === 'forms'): ?>

    <div class="card">
        <h3><?php echo $editing_form ? 'Edit Form Mapping' : 'Add New Form Mapping'; ?></h3>
        <form method="post" class="inline">
            <input type="hidden" name="csrf" value="<?php echo h($csrf); ?>">
            <input type="hidden" name="form_action" value="save_form">
            <input type="hidden" name="id" value="<?php echo h($editing_form['id'] ?? 0); ?>">

            <div class="fg">
                <label>Form ID</label>
                <input type="text" name="form_id" value="<?php echo h($editing_form['form_id'] ?? ''); ?>" required>
            </div>
            <div class="fg wide">
                <label>Project Name</label>
                <input type="text" name="project_name" value="<?php echo h($editing_form['project_name'] ?? ''); ?>" required>
            </div>
            <div class="fg checkbox">
                <input type="checkbox" name="route_to_xd_crm" id="route_to_xd_crm" <?php echo !empty($editing_form['route_to_xd_crm']) ? 'checked' : ''; ?>>
                <label for="route_to_xd_crm" style="text-transform:none;">Send to X-Dimension CRM</label>
            </div>
            <button type="submit" class="btn"><?php echo $editing_form ? 'Update' : 'Add Mapping'; ?></button>
            <?php if ($editing_form): ?><a href="?tab=forms" class="btn cancel">Cancel</a><?php endif; ?>
        </form>
    </div>

    <div class="card">
        <h3>All Form Mappings (<?php echo count($forms); ?>)</h3>
        <table>
            <tr><th>Form ID</th><th>Project Name</th><th>XD CRM</th><th></th></tr>
            <?php foreach ($forms as $f): ?>
            <tr>
                <td><?php echo h($f['form_id']); ?></td>
                <td><?php echo h($f['project_name']); ?></td>
                <td><span class="badge <?php echo $f['route_to_xd_crm'] ? 'on' : 'off'; ?>"><?php echo $f['route_to_xd_crm'] ? 'Yes' : 'No'; ?></span></td>
                <td class="row-actions">
                    <a href="?tab=forms&edit_form=<?php echo (int) $f['id']; ?>">Edit</a>
                    <form method="post" style="display:inline" onsubmit="return confirm('Delete this mapping?');">
                        <input type="hidden" name="csrf" value="<?php echo h($csrf); ?>">
                        <input type="hidden" name="form_action" value="delete_form">
                        <input type="hidden" name="id" value="<?php echo (int) $f['id']; ?>">
                        <button type="submit" class="danger">Delete</button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
        </table>
    </div>

<?php elseif ($tab === 'settings'): ?>

    <div class="card">
        <h3>Shared Settings</h3>
        <form method="post" class="inline">
            <input type="hidden" name="csrf" value="<?php echo h($csrf); ?>">
            <input type="hidden" name="form_action" value="save_settings">

            <div class="fg wide">
                <label>Webhook Verify Token</label>
                <input type="text" name="webhook_verify_token" value="<?php echo h($settings['webhook_verify_token'] ?? ''); ?>">
            </div>
            <div class="fg wide">
                <label>Master Token (fallback)</label>
                <input type="text" name="master_token" value="<?php echo h($settings['master_token'] ?? ''); ?>">
            </div>
            <div class="fg wide">
                <label>XD CRM URL</label>
                <input type="text" name="xd_crm_url" value="<?php echo h($settings['xd_crm_url'] ?? ''); ?>">
            </div>
            <div class="fg wide">
                <label>XD CRM Secret</label>
                <input type="text" name="xd_crm_secret" value="<?php echo h($settings['xd_crm_secret'] ?? ''); ?>">
            </div>
            <button type="submit" class="btn">Save Settings</button>
        </form>
    </div>

<?php endif; ?>

</div>
</body>
</html>
