<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Controller extends CI_Controller {
    
    protected $response = [
        'status' => false,
        'message' => '',
        'data' => null
    ];

    public function __construct() {
        parent::__construct();
        
        // Start output buffering to prevent "headers already sent" errors
        if (!ob_get_level()) {
            ob_start();
        }
        
        // Enable CORS - check if headers haven't been sent already
        if (!headers_sent()) {
            // Get the origin of the request
            $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
            
            // List of allowed origins
            $allowed_origins = [
                'https://www.channamix.org',
                'https://channamix.org',
                'https://api.channamix.org',
                'https://hallobundapedia.id',
                'https://www.hallobundapedia.id',
                'http://localhost:3000',
                'http://localhost:3001',
                'http://127.0.0.1:3000'
            ];
            
            // Check if the origin is in the allowed list
            if (in_array($origin, $allowed_origins)) {
                header('Access-Control-Allow-Origin: ' . $origin);
            } else {
                // For production, you might want to be more restrictive
                // For now, we'll allow the specific domain
                if (strpos($origin, 'channamix.org') !== false || 
                    strpos($origin, 'hallobundapedia.id') !== false || 
                    strpos($origin, 'localhost') !== false) {
                    header('Access-Control-Allow-Origin: ' . $origin);
                }
            }
            
            header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
            header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400'); // Cache preflight for 24 hours
        }
        
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit(0);
        }
    }

    protected function json_response($data = null, $status = true, $message = '') {
        $this->response['status'] = $status;
        $this->response['message'] = $message;
        $this->response['data'] = $data;
        
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($this->response));
    }
} 