<?php
class ApiController {
    private $baseUrl = 'https://flickrite.com/rest_api/classes/userMaster.php?';
    
    public function handleRequest() {
        // Set CORS headers
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization');
        
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            http_response_code(200);
            exit();
        }
        
        // Get the function parameter from the request
        $function = $_GET['f'] ?? '';
        
        // Route to the appropriate method
        switch ($function) {
            case 'get_top_stories':
                $this->getTopStories();
                break;
            case 'get_category_posts':
                $this->getCategoryPosts();
                break;
            case 'get_post_details':
                $this->getPostDetails();
                break;
            case 'search_posts':
                $this->searchPosts();
                break;
            default:
                $this->sendError('Invalid function parameter');
        }
    }
    
    private function getTopStories() {
        try {
            // Fetch news from external API
            $response = $this->makeApiCall('get_top_stories');
            
            if ($response) {
                $this->sendJson(['success' => true, 'data' => $response]);
            } else {
                $this->sendError('Failed to fetch top stories');
            }
        } catch (Exception $e) {
            $this->sendError('Error: ' . $e->getMessage());
        }
    }
    
    private function getCategoryPosts() {
        $category = $_GET['category'] ?? 'general';
        $page = $_GET['page'] ?? 1;
        $limit = $_GET['limit'] ?? 10;
        
        try {
            // Fetch category posts from external API
            $response = $this->makeApiCall('get_category_posts', [
                'category' => $category,
                'page' => $page,
                'limit' => $limit
            ]);
            
            if ($response) {
                $this->sendJson(['success' => true, 'data' => $response]);
            } else {
                $this->sendError('Failed to fetch category posts');
            }
        } catch (Exception $e) {
            $this->sendError('Error: ' . $e->getMessage());
        }
    }
    
    private function getPostDetails() {
        $postId = $_GET['id'] ?? '';
        
        if (empty($postId)) {
            $this->sendError('Post ID is required');
            return;
        }
        
        try {
            // Fetch post details from external API
            $response = $this->makeApiCall('get_post_details', ['id' => $postId]);
            
            if ($response) {
                $this->sendJson(['success' => true, 'data' => $response]);
            } else {
                $this->sendError('Post not found');
            }
        } catch (Exception $e) {
            $this->sendError('Error: ' . $e->getMessage());
        }
    }
    
    private function searchPosts() {
        $query = $_GET['q'] ?? '';
        
        if (empty($query)) {
            $this->sendError('Search query is required');
            return;
        }
        
        try {
            // Search posts from external API
            $response = $this->makeApiCall('search_posts', ['q' => $query]);
            
            if ($response) {
                $this->sendJson(['success' => true, 'data' => $response]);
            } else {
                $this->sendError('No search results found');
            }
        } catch (Exception $e) {
            $this->sendError('Error: ' . $e->getMessage());
        }
    }
    
    private function makeApiCall($function, $params = []) {
        // Build URL with function parameter
        $url = $this->baseUrl . 'f=' . $function;
        
        // Add additional parameters
        foreach ($params as $key => $value) {
            $url .= '&' . $key . '=' . urlencode($value);
        }
        
        // Make the API call using cURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            throw new Exception('API request failed: ' . $error);
        }
        
        if ($httpCode !== 200) {
            throw new Exception('API returned error code: ' . $httpCode);
        }
        
        $data = json_decode($response, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('Invalid JSON response from API');
        }
        
        return $data;
    }
    
    private function sendJson($data) {
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }
    
    private function sendError($message, $code = 400) {
        http_response_code($code);
        $this->sendJson(['success' => false, 'error' => $message]);
    }
}
?>