<?php

/**
 * Class SqlController
 * 
 * Controller for executing raw SQL queries
 */
class SqlController extends Controller
{
    /**
     * Construct this object by extending the basic Controller class
     */
    public function __construct()
    {
        parent::__construct();
        
        // Only admin users can access the SQL console
        Auth::checkAuthentication();
        Auth::checkAdminAuthentication();
    }

    /**
     * Show SQL console interface
     * @param string $database_name
     */
    public function index($database_name = null)
    {
        if (!$database_name) {
            $database_name = Config::get('DB_NAME');
        }

        $this->View->renderDbManager('sql/index', array(
            'database_name' => $database_name,
            'databases' => DatabaseModel::getAllDatabases(),
            'history' => SqlModel::getQueryHistory(Session::get('user_id'))
        ));
    }

    /**
     * Execute SQL query
     */
    public function execute()
    {
        $database_name = Request::post('database_name') ?: Config::get('DB_NAME');
        $sql_query = Request::post('sql_query');
        
        if (empty($sql_query)) {
            if ($this->isAjaxRequest()) {
                header('Content-Type: application/json');
                echo json_encode([
                    'success' => false,
                    'message' => 'SQL query cannot be empty'
                ]);
                return;
            }
            Redirect::to('sql');
            return;
        }

        $result = SqlModel::executeQuery($database_name, $sql_query, Session::get('user_id'));
        
        if ($this->isAjaxRequest()) {
            header('Content-Type: application/json');
            
            if ($result['success']) {
                echo json_encode([
                    'success' => true,
                    'message' => $result['message'],
                    'result' => $result['result'],
                    'affected_rows' => $result['affected_rows'],
                    'execution_time' => $result['execution_time'],
                    'query_type' => $result['query_type']
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => $result['message'],
                    'error' => $result['error']
                ]);
            }
            return;
        }
        
        // Non-AJAX: redirect with results in session
        Session::set('sql_result', $result);
        Redirect::to('sql/index/' . urlencode($database_name));
    }

    /**
     * Get query history as JSON (AJAX endpoint)
     */
    public function getHistory()
    {
        $history = SqlModel::getQueryHistory(Session::get('user_id'));
        
        header('Content-Type: application/json');
        echo json_encode([
            'success' => true,
            'history' => $history
        ]);
    }

    /**
     * Clear query history
     */
    public function clearHistory()
    {
        $success = SqlModel::clearQueryHistory(Session::get('user_id'));
        
        if ($this->isAjaxRequest()) {
            header('Content-Type: application/json');
            
            if ($success) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Query history cleared successfully'
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Failed to clear query history'
                ]);
            }
            return;
        }
        
        Redirect::to('sql');
    }

    /**
     * Get database schema for autocomplete
     * @param string $database_name
     */
    public function getSchema($database_name = null)
    {
        if (!$database_name) {
            $database_name = Config::get('DB_NAME');
        }

        $schema = SqlModel::getDatabaseSchema($database_name);
        
        header('Content-Type: application/json');
        echo json_encode([
            'success' => true,
            'schema' => $schema
        ]);
    }

    /**
     * Format SQL query (AJAX endpoint)
     */
    public function formatQuery()
    {
        $query = Request::post('query');
        
        if (empty($query)) {
            header('Content-Type: application/json');
            echo json_encode([
                'success' => false,
                'message' => 'Query cannot be empty'
            ]);
            return;
        }

        $formatted = SqlModel::formatQuery($query);
        
        header('Content-Type: application/json');
        echo json_encode([
            'success' => true,
            'formatted' => $formatted
        ]);
    }

    /**
     * Check if the request is an AJAX request
     */
    private function isAjaxRequest()
    {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 
               strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
    }
}