api.php

20.18 KB
02/07/2025 02:48
PHP
<?php
/**
 * 🚀 PHP API สำหรับแดชบอร์ดแนวโน้มการเมืองไทย
 * เชื่อมต่อกับแหล่งข้อมูลจริงและจำลองข้อมูล
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// ตั้งค่า timezone
date_default_timezone_set('Asia/Bangkok');

class PoliticalDataAPI
{
    /**
     * @var string
     */
    private $cacheFile;
    /**
     * @var int
     */
    private $cacheTimeout = 300; // 5 นาที

    public function __construct()
    {
        // กำหนด path สำหรับ cache และ exports ที่รองรับ subfolder
        $scriptDir = dirname($_SERVER['SCRIPT_NAME']);
        $basePath = $_SERVER['DOCUMENT_ROOT'].$scriptDir;

        // สร้างโฟลเดอร์ cache และ exports ถ้ายังไม่มี
        $this->cacheFile = $basePath.'/cache/';
        $exportsPath = $basePath.'/exports/';

        if (!is_dir($this->cacheFile)) {
            mkdir($this->cacheFile, 0755, true);
        }

        if (!is_dir($exportsPath)) {
            mkdir($exportsPath, 0755, true);
        }
    }

    /**
     * ข้อมูลเศรษฐกิจจากธนาคารแห่งประเทศไทย
     */
    public function getEconomicData($timeframe = '6months')
    {
        $cacheKey = "economic_{$timeframe}";

        // ตรวจสอบ cache
        if ($this->isCacheValid($cacheKey)) {
            return $this->getCache($cacheKey);
        }

        try {
            // จำลองการเรียก API จริง
            $data = $this->fetchEconomicDataFromAPI($timeframe);

            // บันทึก cache
            $this->setCache($cacheKey, $data);

            return $data;
        } catch (Exception $e) {
            error_log("Error fetching economic data: ".$e->getMessage());
            return $this->getFallbackEconomicData();
        }
    }

    /**
     * ข้อมูลการเมืองจากสำนักงานคณะกรรมการการเลือกตั้ง
     */
    public function getPoliticalData($timeframe = '6months')
    {
        $cacheKey = "political_{$timeframe}";

        if ($this->isCacheValid($cacheKey)) {
            return $this->getCache($cacheKey);
        }

        try {
            $data = $this->fetchPoliticalDataFromAPI($timeframe);
            $this->setCache($cacheKey, $data);
            return $data;
        } catch (Exception $e) {
            error_log("Error fetching political data: ".$e->getMessage());
            return $this->getFallbackPoliticalData();
        }
    }

    /**
     * ข้อมูลประชากรจากสำนักงานสถิติแห่งชาติ
     */
    public function getDemographicData($region = 'all')
    {
        $cacheKey = "demographic_{$region}";

        if ($this->isCacheValid($cacheKey)) {
            return $this->getCache($cacheKey);
        }

        try {
            $data = $this->fetchDemographicDataFromAPI($region);
            $this->setCache($cacheKey, $data);
            return $data;
        } catch (Exception $e) {
            error_log("Error fetching demographic data: ".$e->getMessage());
            return $this->getFallbackDemographicData();
        }
    }

    /**
     * วิเคราะห์ข้อมูล Social Media
     */
    public function getSocialMediaAnalysis($keywords = ['การเมืองไทย', 'รัฐบาล', 'เลือกตั้ง'])
    {
        $cacheKey = "social_media_".md5(serialize($keywords));

        if ($this->isCacheValid($cacheKey)) {
            return $this->getCache($cacheKey);
        }

        try {
            $data = $this->analyzeSocialMedia($keywords);
            $this->setCache($cacheKey, $data);
            return $data;
        } catch (Exception $e) {
            error_log("Error analyzing social media: ".$e->getMessage());
            return $this->getFallbackSocialMediaData();
        }
    }

    /**
     * จำลองการเรียก API จริง
     */
    private function fetchEconomicDataFromAPI($timeframe)
    {
        // จำลองการเรียก API ธนาคารแห่งประเทศไทย
        $url = "https://api.bot.or.th/v1/economic-indicators";

        // ในการใช้งานจริง จะใช้ cURL หรือ file_get_contents
        // $response = file_get_contents($url);

        // จำลองข้อมูลที่ได้จาก API
        $data = [
            'gdp_growth' => 2.8 + (rand(-10, 10) / 100),
            'inflation_rate' => 1.2 + (rand(-5, 5) / 100),
            'unemployment_rate' => 1.1 + (rand(-3, 3) / 100),
            'consumer_confidence' => 62.3 + (rand(-20, 20) / 10),
            'interest_rate' => 2.5 + (rand(-10, 10) / 100),
            'exchange_rate' => 35.2 + (rand(-50, 50) / 100),
            'source' => 'ธนาคารแห่งประเทศไทย',
            'last_updated' => date('Y-m-d H:i:s'),
            'timeframe' => $timeframe
        ];

        return $data;
    }

    /**
     * @param $timeframe
     * @return mixed
     */
    private function fetchPoliticalDataFromAPI($timeframe)
    {
        // จำลองการเรียก API กกต.
        $data = [
            'approval_rating' => 62.3 + (rand(-30, 30) / 10),
            'party_support' => [
                'พรรคเพื่อไทย' => 30.1 + (rand(-20, 20) / 10),
                'พรรคภูมิใจไทย' => 25.0 + (rand(-15, 15) / 10),
                'พรรคก้าวไกล' => 19.3 + (rand(-15, 15) / 10),
                'พรรคประชาธิปัตย์' => 12.1 + (rand(-10, 10) / 10)
            ],
            'voter_turnout' => 71.2 + (rand(-20, 20) / 10),
            'political_issues' => [
                'เศรษฐกิจ' => 32.5 + (rand(-10, 10) / 10),
                'การศึกษา' => 18.2 + (rand(-8, 8) / 10),
                'สาธารณสุข' => 16.8 + (rand(-8, 8) / 10),
                'สิ่งแวดล้อม' => 12.3 + (rand(-6, 6) / 10),
                'ความมั่นคง' => 11.7 + (rand(-6, 6) / 10),
                'การทุจริต' => 8.5 + (rand(-4, 4) / 10)
            ],
            'source' => 'สำนักงานคณะกรรมการการเลือกตั้ง',
            'last_updated' => date('Y-m-d H:i:s'),
            'timeframe' => $timeframe
        ];

        return $data;
    }

    /**
     * @param $region
     * @return mixed
     */
    private function fetchDemographicDataFromAPI($region)
    {
        $data = [
            'total_population' => 69799978,
            'age_distribution' => [
                '0-14' => 16.2 + (rand(-5, 5) / 10),
                '15-64' => 67.8 + (rand(-5, 5) / 10),
                '65+' => 16.0 + (rand(-5, 5) / 10)
            ],
            'regional_data' => [
                'กรุงเทพฯ' => [
                    'population' => 10500000,
                    'approval_rate' => 65.2 + (rand(-20, 20) / 10)
                ],
                'ภาคเหนือ' => [
                    'population' => 11500000,
                    'approval_rate' => 58.7 + (rand(-20, 20) / 10)
                ],
                'ภาคอีสาน' => [
                    'population' => 22000000,
                    'approval_rate' => 61.3 + (rand(-20, 20) / 10)
                ],
                'ภาคกลาง' => [
                    'population' => 15000000,
                    'approval_rate' => 63.1 + (rand(-20, 20) / 10)
                ],
                'ภาคใต้' => [
                    'population' => 9000000,
                    'approval_rate' => 59.8 + (rand(-20, 20) / 10)
                ]
            ],
            'source' => 'สำนักงานสถิติแห่งชาติ',
            'last_updated' => date('Y-m-d H:i:s'),
            'region' => $region
        ];

        return $data;
    }

    /**
     * @param $keywords
     * @return mixed
     */
    private function analyzeSocialMedia($keywords)
    {
        // จำลองการวิเคราะห์ Social Media
        $data = [
            'twitter' => [
                'sentiment_score' => 0.55 + (rand(-20, 20) / 100),
                'volume' => 15000 + rand(-2000, 2000),
                'trending_topics' => ['การเมืองไทย', 'เศรษฐกิจ', 'การศึกษา', 'สาธารณสุข'],
                'engagement_rate' => 0.08 + (rand(-2, 2) / 100)
            ],
            'facebook' => [
                'sentiment_score' => 0.52 + (rand(-20, 20) / 100),
                'volume' => 25000 + rand(-3000, 3000),
                'engagement_rate' => 0.08 + (rand(-2, 2) / 100),
                'top_posts' => []
            ],
            'youtube' => [
                'sentiment_score' => 0.58 + (rand(-20, 20) / 100),
                'views' => 500000 + rand(-50000, 50000),
                'top_videos' => [],
                'engagement_rate' => 0.12 + (rand(-3, 3) / 100)
            ],
            'combined_sentiment' => [
                'score' => 0.55 + (rand(-20, 20) / 100),
                'label' => 'neutral',
                'confidence' => 0.7 + (rand(-10, 10) / 100)
            ],
            'source' => 'Social Media Analysis',
            'last_updated' => date('Y-m-d H:i:s'),
            'keywords' => $keywords
        ];

        return $data;
    }

    /**
     * ระบบ Cache
     */
    private function setCache($key, $data)
    {
        $cacheData = [
            'data' => $data,
            'timestamp' => time()
        ];

        $filename = $this->cacheFile.md5($key).'.json';
        file_put_contents($filename, json_encode($cacheData, JSON_UNESCAPED_UNICODE));
    }

    /**
     * @param $key
     * @return mixed
     */
    private function getCache($key)
    {
        $filename = $this->cacheFile.md5($key).'.json';

        if (file_exists($filename)) {
            $cacheData = json_decode(file_get_contents($filename), true);
            return $cacheData['data'];
        }

        return null;
    }

    /**
     * @param $key
     */
    private function isCacheValid($key)
    {
        $filename = $this->cacheFile.md5($key).'.json';

        if (!file_exists($filename)) {
            return false;
        }

        $cacheData = json_decode(file_get_contents($filename), true);
        return (time() - $cacheData['timestamp']) < $this->cacheTimeout;
    }

    /**
     * ข้อมูลสำรอง
     */
    private function getFallbackEconomicData()
    {
        return [
            'gdp_growth' => 2.8,
            'inflation_rate' => 1.2,
            'unemployment_rate' => 1.1,
            'consumer_confidence' => 62.3,
            'interest_rate' => 2.5,
            'exchange_rate' => 35.2,
            'source' => 'fallback_data',
            'last_updated' => date('Y-m-d H:i:s')
        ];
    }

    private function getFallbackPoliticalData()
    {
        return [
            'approval_rating' => 62.3,
            'party_support' => [
                'พรรคเพื่อไทย' => 30.1,
                'พรรคภูมิใจไทย' => 25.0,
                'พรรคก้าวไกล' => 19.3,
                'พรรคประชาธิปัตย์' => 12.1
            ],
            'source' => 'fallback_data',
            'last_updated' => date('Y-m-d H:i:s')
        ];
    }

    private function getFallbackDemographicData()
    {
        return [
            'total_population' => 69799978,
            'age_distribution' => [
                '0-14' => 16.2,
                '15-64' => 67.8,
                '65+' => 16.0
            ],
            'source' => 'fallback_data',
            'last_updated' => date('Y-m-d H:i:s')
        ];
    }

    private function getFallbackSocialMediaData()
    {
        return [
            'twitter' => [
                'sentiment_score' => 0.55,
                'volume' => 15000,
                'trending_topics' => ['การเมืองไทย', 'เศรษฐกิจ', 'การศึกษา']
            ],
            'facebook' => [
                'sentiment_score' => 0.52,
                'volume' => 25000,
                'engagement_rate' => 0.08
            ],
            'youtube' => [
                'sentiment_score' => 0.58,
                'views' => 500000,
                'top_videos' => []
            ],
            'combined_sentiment' => [
                'score' => 0.55,
                'label' => 'neutral',
                'confidence' => 0.7
            ],
            'source' => 'fallback_data',
            'last_updated' => date('Y-m-d H:i:s')
        ];
    }

    /**
     * ส่งออกข้อมูลเป็นไฟล์
     */
    public function exportData($type, $data)
    {
        $timestamp = date('Y-m-d_H-i-s');

        switch ($type) {
            case 'csv':
                return $this->exportToCSV($data, $timestamp);
            case 'json':
                return $this->exportToJSON($data, $timestamp);
            case 'xml':
                return $this->exportToXML($data, $timestamp);
            default:
                throw new Exception('Unsupported export type');
        }
    }

    /**
     * @param $data
     * @param $timestamp
     */
    private function exportToCSV($data, $timestamp)
    {
        $scriptDir = dirname($_SERVER['SCRIPT_NAME']);
        $basePath = $_SERVER['DOCUMENT_ROOT'].$scriptDir;
        $filename = $basePath."/exports/political_data_{$timestamp}.csv";
        $downloadUrl = $scriptDir."/exports/political_data_{$timestamp}.csv";

        if (!is_dir($basePath.'/exports')) {
            mkdir($basePath.'/exports', 0755, true);
        }

        $fp = fopen($filename, 'w');

        // เขียน header
        fputcsv($fp, ['ประเภท', 'ค่า', 'หน่วย', 'วันที่']);

        // เขียนข้อมูล
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                foreach ($value as $subKey => $subValue) {
                    fputcsv($fp, [$key.'_'.$subKey, $subValue, '', date('Y-m-d H:i:s')]);
                }
            } else {
                fputcsv($fp, [$key, $value, '', date('Y-m-d H:i:s')]);
            }
        }

        fclose($fp);

        return [
            'filename' => $filename,
            'download_url' => $downloadUrl,
            'size' => filesize($filename)
        ];
    }

    /**
     * @param $data
     * @param $timestamp
     */
    private function exportToJSON($data, $timestamp)
    {
        $scriptDir = dirname($_SERVER['SCRIPT_NAME']);
        $basePath = $_SERVER['DOCUMENT_ROOT'].$scriptDir;
        $filename = $basePath."/exports/political_data_{$timestamp}.json";
        $downloadUrl = $scriptDir."/exports/political_data_{$timestamp}.json";

        if (!is_dir($basePath.'/exports')) {
            mkdir($basePath.'/exports', 0755, true);
        }

        $jsonData = [
            'export_info' => [
                'timestamp' => date('Y-m-d H:i:s'),
                'source' => 'Thai Political Dashboard API',
                'version' => '1.0.0'
            ],
            'data' => $data
        ];

        file_put_contents($filename, json_encode($jsonData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

        return [
            'filename' => $filename,
            'download_url' => $downloadUrl,
            'size' => filesize($filename)
        ];
    }

    /**
     * @param $data
     * @param $timestamp
     */
    private function exportToXML($data, $timestamp)
    {
        $scriptDir = dirname($_SERVER['SCRIPT_NAME']);
        $basePath = $_SERVER['DOCUMENT_ROOT'].$scriptDir;
        $filename = $basePath."/exports/political_data_{$timestamp}.xml";
        $downloadUrl = $scriptDir."/exports/political_data_{$timestamp}.xml";

        if (!is_dir($basePath.'/exports')) {
            mkdir($basePath.'/exports', 0755, true);
        }

        $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><political_data></political_data>');

        $exportInfo = $xml->addChild('export_info');
        $exportInfo->addChild('timestamp', date('Y-m-d H:i:s'));
        $exportInfo->addChild('source', 'Thai Political Dashboard API');
        $exportInfo->addChild('version', '1.0.0');

        $this->arrayToXML($data, $xml->addChild('data'));

        $xml->asXML($filename);

        return [
            'filename' => $filename,
            'download_url' => $downloadUrl,
            'size' => filesize($filename)
        ];
    }

    /**
     * @param $array
     * @param $xml
     */
    private function arrayToXML($array, &$xml)
    {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $subnode = $xml->addChild($key);
                $this->arrayToXML($value, $subnode);
            } else {
                $xml->addChild($key, htmlspecialchars($value));
            }
        }
    }
}

// จัดการ Request
$api = new PoliticalDataAPI();

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            switch ($action) {
                case 'economic':
                    $timeframe = $_GET['timeframe'] ?? '6months';
                    $data = $api->getEconomicData($timeframe);
                    break;

                case 'political':
                    $timeframe = $_GET['timeframe'] ?? '6months';
                    $data = $api->getPoliticalData($timeframe);
                    break;

                case 'demographic':
                    $region = $_GET['region'] ?? 'all';
                    $data = $api->getDemographicData($region);
                    break;

                case 'social_media':
                    $keywords = isset($_GET['keywords']) ? explode(',', $_GET['keywords']) : ['การเมืองไทย', 'รัฐบาล', 'เลือกตั้ง'];
                    $data = $api->getSocialMediaAnalysis($keywords);
                    break;

                case 'all':
                    $timeframe = $_GET['timeframe'] ?? '6months';
                    $region = $_GET['region'] ?? 'all';
                    $keywords = isset($_GET['keywords']) ? explode(',', $_GET['keywords']) : ['การเมืองไทย', 'รัฐบาล', 'เลือกตั้ง'];

                    $data = [
                        'economic' => $api->getEconomicData($timeframe),
                        'political' => $api->getPoliticalData($timeframe),
                        'demographic' => $api->getDemographicData($region),
                        'social_media' => $api->getSocialMediaAnalysis($keywords),
                        'timestamp' => date('Y-m-d H:i:s')
                    ];
                    break;

                default:
                    throw new Exception('Invalid action');
            }
            break;

        case 'POST':
            $input = json_decode(file_get_contents('php://input'), true);

            switch ($action) {
                case 'export':
                    $type = $input['type'] ?? 'json';
                    $exportData = $input['data'] ?? [];
                    $data = $api->exportData($type, $exportData);
                    break;

                default:
                    throw new Exception('Invalid action');
            }
            break;

        default:
            throw new Exception('Method not allowed');
    }

    echo json_encode([
        'success' => true,
        'data' => $data,
        'timestamp' => date('Y-m-d H:i:s')
    ], JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage(),
        'timestamp' => date('Y-m-d H:i:s')
    ], JSON_UNESCAPED_UNICODE);
}