<?php

/**
 * Class UserController for Database Manager
 * 
 * Controller for managing MySQL users and privileges
 */
class DbUserController extends Controller
{
    /**
     * Construct this object by extending the basic Controller class
     */
    public function __construct()
    {
        parent::__construct();
        
        // Only admin users can access database user management
        Auth::checkAuthentication();
        Auth::checkAdminAuthentication();
    }

    /**
     * List all database users
     */
    public function index()
    {
        $this->View->renderDbManager('dbuser/index', array(
            'users' => DbUserModel::getAllUsers(),
            'current_user' => Config::get('DB_USER')
        ));
    }

    /**
     * Create a new database user
     */
    public function create()
    {
        if (Request::post('submit_create_user')) {
            $username = Request::post('username');
            $password = Request::post('password');
            $host = Request::post('host');
            $privileges = Request::post('privileges');

            if ($this->isAjaxRequest()) {
                header('Content-Type: application/json');

                if (DbUserModel::createUser($username, $password, $host)) {
                    if (!empty($privileges)) {
                        DbUserModel::updateUserPrivileges($username, $host, $privileges);
                    }
                    echo json_encode([
                        'success' => true,
                        'message' => 'User created successfully',
                        'reload' => true
                    ]);
                } else {
                    echo json_encode([
                        'success' => false,
                        'message' => 'Failed to create user'
                    ]);
                }
                return;
            }

            if (DbUserModel::createUser($username, $password, $host)) {
                if (!empty($privileges)) {
                    DbUserModel::updateUserPrivileges($username, $host, $privileges);
                }
                Redirect::to('dbuser');
            } else {
                Redirect::to('dbuser');
            }
            return;
        }

        $this->View->renderDbManager('dbuser/create');
    }

    /**
     * Edit user details and privileges
     * @param string $username
     * @param string $host
     */
    public function edit($username, $host)
    {
        if (Request::post('submit_edit_user')) {
            $new_password = Request::post('password');
            $privileges = Request::post('privileges');
            
            if ($this->isAjaxRequest()) {
                header('Content-Type: application/json');
                
                $success = true;
                $message = 'User updated successfully';
                
                if (!empty($new_password)) {
                    if (!DbUserModel::updateUserPassword($username, $host, $new_password)) {
                        $success = false;
                        $message = 'Failed to update user password';
                    }
                }
                
                if ($success && !DbUserModel::updateUserPrivileges($username, $host, $privileges)) {
                    $success = false;
                    $message = 'Failed to update user privileges';
                }
                
                if ($success) {
                    echo json_encode([
                        'success' => true,
                        'message' => $message
                    ]);
                } else {
                    echo json_encode([
                        'success' => false,
                        'message' => $message
                    ]);
                }
                return;
            }
            
            $success = true;
            if (!empty($new_password)) {
                $success = DbUserModel::updateUserPassword($username, $host, $new_password);
            }
            
            if ($success && !DbUserModel::updateUserPrivileges($username, $host, $privileges)) {
                $success = false;
            }
            
            Redirect::to('dbuser');
            return;
        }

        // Show edit user form
        $this->View->renderDbManager('dbuser/edit', array(
            'user' => DbUserModel::getUserDetails($username, $host),
            'privileges' => DbUserModel::getUserPrivileges($username, $host),
            'databases' => DatabaseModel::getAllDatabases()
        ));
    }

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

        $success = DbUserModel::deleteUser($username, $host);
        
        if ($this->isAjaxRequest()) {
            header('Content-Type: application/json');
            
            if ($success) {
                echo json_encode([
                    'success' => true,
                    'message' => 'User deleted successfully'
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Failed to delete user'
                ]);
            }
            return;
        }
        
        Redirect::to('dbuser');
    }

    /**
     * Show user privileges
     * @param string $username
     * @param string $host
     */
    public function privileges($username, $host)
    {
        $this->View->renderDbManager('dbuser/privileges', array(
            'user' => DbUserModel::getUserDetails($username, $host),
            'privileges' => DbUserModel::getUserPrivileges($username, $host)
        ));
    }

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