<?php

/**
 * Class DatabaseController
 * 
 * Controller for managing databases and showing their structure
 */
class DatabaseController extends Controller
{
    /**
     * Construct this object by extending the basic Controller class
     */
    public function __construct()
    {
        parent::__construct();
        
        // Only admin users can access the database manager
        Auth::checkAuthentication();
        Auth::checkAdminAuthentication();
    }

    /**
     * Main database management interface
     */
    public function index()
    {
        $this->View->renderDbManager('database/index', array(
            'databases' => DatabaseModel::getAllDatabases(),
            'current_db' => Config::get('DB_NAME')
        ));
    }

    /**
     * Show details of a specific database
     * @param string $database_name
     */
    public function show($database_name = null)
    {
        if (!$database_name) {
            $database_name = Config::get('DB_NAME');
        }

        $this->View->renderDbManager('database/show', array(
            'tables' => DatabaseModel::getTablesInDatabase($database_name),
            'database_name' => $database_name,
            'table_info' => DatabaseModel::getTableDetails($database_name)
        ));
    }

    /**
     * Create a new database
     */
    public function create()
    {
        $database_name = Request::post('database_name');
        
        if ($this->isAjaxRequest()) {
            header('Content-Type: application/json');
            
            if (DatabaseModel::createDatabase($database_name)) {
                echo json_encode([
                    'success' => true, 
                    'message' => 'Database created successfully'
                ]);
            } else {
                echo json_encode([
                    'success' => false, 
                    'message' => 'Failed to create database'
                ]);
            }
            return;
        }
        
        Redirect::to('database');
    }

    /**
     * Delete a database
     * @param string $database_name
     */
    public function delete($database_name)
    {
        // Prevent deletion of the current database
        if ($database_name === Config::get('DB_NAME')) {
            if ($this->isAjaxRequest()) {
                header('Content-Type: application/json');
                echo json_encode([
                    'success' => false, 
                    'message' => 'Cannot delete the currently connected database'
                ]);
                return;
            }
            Redirect::to('database');
            return;
        }

        $success = DatabaseModel::deleteDatabase($database_name);
        
        if ($this->isAjaxRequest()) {
            header('Content-Type: application/json');
            if ($success) {
                echo json_encode([
                    'success' => true, 
                    'message' => 'Database deleted successfully'
                ]);
            } else {
                echo json_encode([
                    'success' => false, 
                    'message' => 'Failed to delete database'
                ]);
            }
            return;
        }
        
        Redirect::to('database');
    }

    /**
     * Get database structure as JSON (AJAX endpoint)
     * @param string $database_name
     */
    public function getStructure($database_name = null)
    {
        if (!$database_name) {
            $database_name = Config::get('DB_NAME');
        }

        $structure = DatabaseModel::getDatabaseStructure($database_name);

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

    /**
     * Get columns for a specific table (AJAX endpoint)
     * @param string $database_name
     * @param string $table_name
     */
    public function getColumns($database_name, $table_name)
    {
        $columns = TableModel::getTableColumns($database_name, $table_name);

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

    /**
     * Export database as raw SQL text
     * @param string $database_name
     */
    public function export($database_name)
    {
        header('Content-Type: text/plain; charset=utf-8');
        header('Content-Disposition: inline; filename="' . $database_name . '.sql"');

        echo DatabaseModel::exportDatabase($database_name);
    }

    /**
     * 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';
    }
}