<?php
include __DIR__ . "/../../global.php";

class FacebookIntegration extends object_class {

    /* ---------------- Settings ---------------- */

    public function getSetting($key, $default='') {
        $row = $this->dbF->getRow("SELECT setting_value FROM integration_facebook_settings WHERE setting_key = ?", [$key]);
        if($this->dbF->rowCount>0){
            $val = $row['setting_value'];
            return $val;
        }
        return $default;
    }

    /* ---------------- Facebook API ---------------- */

    public function fbGet($endpoint, $accessToken){
        $url = "https://graph.facebook.com/v24.0/{$endpoint}" . (str_contains($endpoint,'?') ? "&" : "?") . "access_token=" . urlencode($accessToken);
        return $this->curlJson('GET', $url);
    }

    public function fbGetLead($leadId, $accessToken, $appSecretProof = '') {
        $url = "https://graph.facebook.com/v24.0/{$leadId}?fields=field_data,created_time,form_id,ad_id"
            . "&access_token=" . urlencode($accessToken);
        if (!empty($appSecretProof)) {
            $url .= "&appsecret_proof=" . $appSecretProof;
        }
        return $this->curlJson('GET', $url);
    }

    private function curlJson($method, $url, $body=null, $headers=[]){
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_TIMEOUT => 20,
            CURLOPT_HTTPHEADER => array_merge(['Accept: application/json'], $headers)
        ]);
        if($body){
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        }
        $out = curl_exec($ch);
        $err = curl_error($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if($err) return ['error'=>['message'=>$err,'code'=>$code]];
        $json = json_decode($out, true);
        if($code>=400) return ['error'=>['message'=>$json['error']['message'] ?? 'HTTP '.$code,'code'=>$code]];
        return $json;
    }

    /* ---------------- Lead ingestion ---------------- */

    public function insertLeadFromFacebookFields(array $fieldData, array $meta = []) {
        // Extract common fields
        $full=''; $first=''; $last=''; $email=''; $phone='';
        foreach ($fieldData as $f) {
            $name = strtolower($f['name'] ?? '');
            $val  = is_array($f['values'] ?? null) ? ($f['values'][0] ?? '') : '';
            if ($name === 'full_name' || $name === 'name') $full = $val;
            if ($name === 'first_name') $first = $val;
            if ($name === 'last_name')  $last  = $val;
            if ($name === 'email')      $email = $val;
            if ($name === 'phone_number' || $name === 'phone') $phone = $val;
        }

        if (!$full && ($first || $last)) $full = trim($first.' '.$last);

        // Build dedupe hash (email|phone combo)
        $dedupeKey = strtolower(trim($email)).'|'.preg_replace('/\D+/', '', $phone);
        $dedupeHash = $dedupeKey ? hash('sha256', $dedupeKey) : null;

        // Skip duplicates (by leadgen_id or dedupe_hash)
        $leadgenId = $meta['fb_lead_id'] ?? '';
        $this->dbF->getRow("SELECT id FROM meta_leads WHERE leadgen_id=? OR (dedupe_hash IS NOT NULL AND dedupe_hash=?) LIMIT 1", [$leadgenId, $dedupeHash]);
        if ($this->dbF->rowCount > 0) {
            return ['status'=>'skipped','reason'=>'duplicate'];
        }

        $now = date('Y-m-d H:i:s');
        $fbCreated = !empty($meta['created_time']) ? date('Y-m-d H:i:s', (int)$meta['created_time']) : null;
        $rawJson = isset($meta['_raw']) ? json_encode($meta['_raw']) : null;

        $this->dbF->setRow("INSERT INTO meta_leads (source, leadgen_id, page_id, form_id, ad_id, adgroup_id, 
        campaign_id, full_name, first_name, last_name, email, phone, status, fb_created_time, ingested_at, updated_at, raw_payload, dedupe_hash) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ['facebook', $leadgenId, $meta['fb_page_id'] ?? '', $meta['fb_form_id'] ?? '', $meta['ad_id'] ?? null, $meta['adgroup_id'] ?? null, $meta['campaign_id'] ?? null, $full, $first, $last, $email, $phone, 'new', $fbCreated, $now, $now, $rawJson, $dedupeHash]);
        $leadId = $this->dbF->rowLastId;

        if ($leadId && $fieldData) {
            $vals = []; $params = [];
            foreach ($fieldData as $f) {
                $name = (string)($f['name'] ?? '');
                $val  = is_array($f['values'] ?? null) ? implode(',', $f['values']) : '';
                $vals[] = "(?,?,?)";
                $params[] = $leadId; $params[] = $name; $params[] = $val;
            }
            $this->dbF->setRow("INSERT INTO meta_lead_answers (lead_id, name, value) VALUES ".implode(',', $vals), $params, false);
        }

        $this->dbF->setRow("INSERT INTO meta_lead_events (lead_id, event, detail, created_at) VALUES (?,?,?,?)", [$leadId, 'webhook', 'Lead inserted via webhook', $now]);

        return ['status'=>'inserted','lead_id'=>$leadId];
    }
}
