<?php
// controllers/BaseController.php
// Base controller class

require_once 'config/config.php';
require_once 'includes/functions.php';

class BaseController {
    protected $data = [];

    public function __construct() {
        // Load site settings
        $this->loadSiteSettings();
    }

    // Load site settings
    protected function loadSiteSettings() {
        require_once 'models/SiteSetting.php';
        $siteSetting = new SiteSetting();
        $this->data['settings'] = $siteSetting->getAllAsArray();
    }

    // Render view
    protected function render($view, $data = []) {
        $this->data = array_merge($this->data, $data);
        extract($this->data);
        
        $viewFile = "views/{$view}.php";
        if (file_exists($viewFile)) {
            include $viewFile;
        } else {
            throw new Exception("View file not found: {$viewFile}");
        }
    }

    // Render JSON response
    protected function renderJson($data, $statusCode = 200) {
        http_response_code($statusCode);
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }

    // Redirect
    protected function redirect($url) {
        // Eğer URL mutlak değilse SITE_URL ile birleştir
        if (strpos($url, 'http') !== 0) {
            $url = SITE_URL . $url;
        }
        header("Location: {$url}");
        exit;
    }

    // Check if request is AJAX
    protected function isAjax() {
        return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
               strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
    }

    // Get POST data
    protected function getPostData() {
        return $_POST;
    }

    // Get GET data
    protected function getGetData() {
        return $_GET;
    }

    // Validate required fields
    protected function validateRequired($data, $requiredFields) {
        $errors = [];
        foreach ($requiredFields as $field) {
            if (empty($data[$field])) {
                $errors[] = ucfirst($field) . ' is required';
            }
        }
        return $errors;
    }

    // Sanitize input data
    protected function sanitizeInput($data) {
        $sanitized = [];
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $sanitized[$key] = $this->sanitizeInput($value);
            } else {
                $sanitized[$key] = sanitize($value);
            }
        }
        return $sanitized;
    }
}
?>
