<?php
require_once __DIR__ . '/../global.php';

$fb = new FacebookIntegration();

// --- simple logger
$logDir = dirname(__DIR__) . '/logs';
if (!is_dir($logDir)) mkdir($logDir, 0777, true);
$log = function($line) use ($logDir){ @file_put_contents($logDir.'/cron_fb_pull.log', date('c').' '.$line."\n", FILE_APPEND); };

$pageId    = $fb->getSetting('fb_page_id','');
$pageToken = $fb->getSetting('fb_page_access_token','');
if (!$pageId || !$pageToken) { echo "Missing pageId/token\n"; $log('ERR missing pageId/token'); exit(1); }

// normalise token a bit (same as webhook)
$pageToken = html_entity_decode($pageToken, ENT_QUOTES | ENT_HTML5, 'UTF-8');
$pageToken = preg_replace("/\s+/", "", $pageToken);
$pageToken = preg_replace('/[^\x20-\x7E]/', '', $pageToken);
$pageToken = trim($pageToken);

// appsecret_proof (recommended)
$appSecret = $fb->getSetting('fb_app_secret', '');
$proof     = !empty($appSecret) ? hash_hmac('sha256', $pageToken, $appSecret) : '';

// 1) List leadgen forms on the page
$formsResp = $fb->fbGet($pageId . "/leadgen_forms?limit=50" . ($proof ? "&appsecret_proof=".$proof : ""), $pageToken);
$forms = $formsResp['data'] ?? [];
$log('Found forms: '.count($forms));

foreach ($forms as $form) {
    $formId = $form['id'] ?? null;
    if (!$formId) continue;

    $log("Form $formId: pulling leads");
    // 2) Paginate leads for each form
    $after = null;
    do {
        $endpoint = $formId . "/leads?limit=100";
        if ($after) $endpoint .= "&after=" . urlencode($after);
        if ($proof) $endpoint .= "&appsecret_proof=".$proof;

        $leadsResp = $fb->fbGet($endpoint, $pageToken);

        foreach (($leadsResp['data'] ?? []) as $lead) {
            // $lead already contains field_data + created_time on this edge
            $fieldData = $lead['field_data'] ?? [];
            $meta = [
                'fb_page_id'    => $pageId,
                'fb_form_id'    => $formId,
                'fb_lead_id'    => $lead['id'] ?? '',
                'created_time'  => !empty($lead['created_time']) ? strtotime($lead['created_time']) : null,
                'ad_id'         => $lead['ad_id']        ?? null,
                'adgroup_id'    => $lead['adgroup_id']   ?? null,
                'campaign_id'   => $lead['campaign_id']  ?? null,
                '_raw'          => $lead,
            ];
            try {
                $res = $fb->insertLeadFromFacebookFields($fieldData, $meta);
                if (($res['status'] ?? '') === 'inserted') {
                    $log("Inserted lead_id=".$meta['fb_lead_id']);
                } else {
                    $log("Skipped lead_id=".$meta['fb_lead_id']." reason=".($res['reason'] ?? 'n/a'));
                }
            } catch (Throwable $e) {
                $log("ERR insert lead_id=".$meta['fb_lead_id']." msg=".$e->getMessage());
            }
        }

        $after = $leadsResp['paging']['cursors']['after'] ?? null;
    } while ($after);
}

echo "Done";
$log('Done run');
