<?php
namespace CAE\Lib;

/**
 * SEO API Helper - DataForSEO Integration
 * Ported for Savit Content Engine
 */
class SeoApiHelper
{
    public static function getSeoMetrics($keyword, $location = 'India')
    {
        if (!defined('DATAFORSEO_LOGIN') || !defined('DATAFORSEO_PASSWORD')) {
            return null;
        }

        $login = DATAFORSEO_LOGIN;
        $password = DATAFORSEO_PASSWORD;

        // Use DataForSEO Keyword Data API
        $post_data = array(
            "data" => array(
                array(
                    "keywords" => array($keyword),
                    "location_name" => $location,
                    "language_name" => "English"
                )
            )
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.dataforseo.com/v3/keywords_data/google/search_volume/live");
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $data = json_decode($response, true);
        
        if (isset($data['tasks'][0]['result'][0])) {
            $result = $data['tasks'][0]['result'][0];
            return [
                'volume' => $result['search_volume'] ?? 0,
                'intent' => $result['search_intent_info'] ?? null,
                'cpc' => $result['cpc'] ?? 0,
                'competition' => $result['competition'] ?? 0
            ];
        }

        return null;
    }

    public static function getKeywordSuggestions($keywords, $location = 'India', $language = 'English')
    {
        if (!defined('DATAFORSEO_LOGIN') || !defined('DATAFORSEO_PASSWORD')) {
            return null;
        }

        $login = DATAFORSEO_LOGIN;
        $password = DATAFORSEO_PASSWORD;

        $post_data = array(
            "data" => array(
                array(
                    "keywords" => $keywords,
                    "location_name" => $location,
                    "language_name" => $language,
                    "include_seed_keyword" => true,
                    "limit" => 20
                )
            )
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.dataforseo.com/v3/keywords_data/google/keyword_suggestions/live");
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);

        $response = curl_exec($ch);
        $data = json_decode($response, true);
        
        if (isset($data['tasks'][0]['result'])) {
            return $data['tasks'][0]['result'];
        }

        return null;
    }

    public static function getKeywordsForSite($url, $location = 'India', $language = 'English')
    {
        if (!defined('DATAFORSEO_LOGIN') || !defined('DATAFORSEO_PASSWORD')) {
            return null;
        }

        $login = DATAFORSEO_LOGIN;
        $password = DATAFORSEO_PASSWORD;

        $post_data = array(
            "data" => array(
                array(
                    "target" => $url,
                    "location_name" => $location,
                    "language_name" => $language,
                    "include_subdomains" => true,
                    "limit" => 20
                )
            )
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.dataforseo.com/v3/keywords_data/google/keywords_for_site/live");
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);

        $response = curl_exec($ch);
        $data = json_decode($response, true);
        
        if (isset($data['tasks'][0]['result'])) {
            return $data['tasks'][0]['result'];
        }

        return null;
    }

    public static function calculateAllIntentScores($prompt, $brands = [])
    {
        $text = strtolower($prompt);
        
        // 1. Informational Score
        $info_words = ['what', 'how', 'why', 'guide', 'tutorial', 'meaning', 'example', 'tips', 'learn', 'history', 'define', 'steps'];
        $educational_terms = ['tutorial', 'guide', 'learn', 'meaning', 'example', 'history'];
        $transactional_words = ['buy', 'price', 'cost', 'cheap', 'order', 'purchase', 'discount', 'coupon', 'sale', 'hire'];
        
        $info_count = 0;
        foreach ($info_words as $w) if (strpos($text, $w) !== false) $info_count++;
        $edu_count = 0;
        foreach ($educational_terms as $w) if (strpos($text, $w) !== false) $edu_count++;
        $tran_count = 0;
        foreach ($transactional_words as $w) if (strpos($text, $w) !== false) $tran_count++;
        
        $info_raw = ($info_count * 2) + ($edu_count * 1.5) - ($tran_count * 1);
        $info_score = max(1, min(10, round((float)$info_raw)));

        // 2. Commercial Score
        $comm_keywords = ['best', 'top', 'review', 'affordable', 'pricing', 'pro', 'premium', 'service', 'quality'];
        $comm_count = 0;
        foreach ($comm_keywords as $w) if (strpos($text, $w) !== false) $comm_count++;
        
        $product_presence = (preg_match('/(best|top|review|affordable|buy)\s+([a-z0-9\s]+)/i', $text)) ? 1 : 0;
        $comm_raw = ($comm_count * 2) + ($product_presence * 2);
        $comm_score = max(1, min(10, round((float)$comm_raw)));

        // 3. Navigational Score
        $nav_terms = ['login', 'website', 'official', 'homepage', 'portal', 'account', 'customer service', 'contact'];
        $nav_count = 0;
        foreach ($nav_terms as $w) if (strpos($text, $w) !== false) $nav_count++;
        
        $brand_mentions = 0;
        foreach ($brands as $brand) {
            if (!empty($brand) && strpos($text, strtolower((string)$brand)) !== false) $brand_mentions++;
        }
        
        $nav_raw = ($brand_mentions * 3) + ($nav_count * 2);
        $nav_score = max(1, min(10, round((float)$nav_raw)));

        // 4. Comparison Score
        $comp_keywords = ['vs', 'compare', 'difference', 'better than', 'alternatives', 'comparison', 'versus', 'or'];
        $comp_count = 0;
        foreach ($comp_keywords as $w) if (strpos($text, $w) !== false) $comp_count++;
        $comp_raw = ($comp_count * 3);
        $comp_score = max(1, min(10, round((float)$comp_raw)));

        // 5. Competition Score
        $high_val_keywords = ['insurance', 'loans', 'crypto', 'lawyer', 'software', 'hosting', 'credit', 'refinance', 'donate'];
        $high_val_count = 0;
        foreach ($high_val_keywords as $w) if (strpos($text, $w) !== false) $high_val_count++;
        
        $word_count = count(explode(' ', trim($text)));
        $short_penalty = ($word_count <= 2) ? 1 : 0;
        $brand_presence = ($brand_mentions > 0) ? 1 : 0;
        
        $diff_raw = ($high_val_count * 3) + ($short_penalty * 2) + ($brand_presence * 2);
        $diff_score = max(1, min(10, round((float)$diff_raw)));

        // 6. Branded Score
        $branded_raw = ($brand_mentions * 4);
        $branded_score = max(1, min(10, round((float)$branded_raw)));

        return [
            'informational' => (int)$info_score,
            'commercial'    => (int)$comm_score,
            'navigational'  => (int)$nav_score,
            'comparison'    => (int)$comp_score,
            'competition'   => (int)$diff_score,
            'branded'       => (int)$branded_score
        ];
    }
}
