<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AppModel;
use App\Enums\AppStatus;
use App\Services\DatabaseService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ViewController extends Controller
{
    public function login()
    {
        if (Auth::guard('admin')->check()) {
            return redirect('/admin');
        }

        return view('auth.login');
    }

    public function loginSubmit(Request $request)
    {
        $credentials = $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        if (Auth::guard('admin')->attempt($credentials)) {
            $request->session()->regenerate();

            $redirect = $request->input('redirect');
            if ($redirect && str_starts_with($redirect, '/')) {
                return redirect($redirect);
            }

            return redirect()->intended('/admin');
        }

        return back()->withErrors([
            'username' => '用户名或密码错误',
        ])->onlyInput('username');
    }

    public function logout(Request $request)
    {
        Auth::guard('admin')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/admin/login');
    }

    public function index()
    {
        return view('layouts.admin');
    }

    public function dashboard()
    {
        return view('admin.dashboard');
    }

    public function userIndex()
    {
        return view('admin.user.index');
    }

    public function userForm()
    {
        return view('admin.user.form');
    }

    public function roleIndex()
    {
        return view('admin.role.index');
    }

    public function roleForm()
    {
        return view('admin.role.form');
    }

    public function rolePermissions()
    {
        return view('admin.role.permissions');
    }

    public function roleMenus()
    {
        return view('admin.role.menus');
    }

    public function menuIndex()
    {
        return view('admin.menu.index');
    }

    public function menuForm()
    {
        return view('admin.menu.form');
    }

    public function menuTerminal()
    {
        return view('admin.menu.terminal');
    }

    public function menuTerminalForm()
    {
        return view('admin.menu.terminal-form');
    }

    public function accountIndex()
    {
        return view('admin.account.index');
    }

    public function accountPassword()
    {
        return view('admin.account.password');
    }

    public function configIndex()
    {
        return view('admin.config.index');
    }

    public function settingIndex()
    {
        return view('admin.setting.index');
    }

    public function attachmentIndex()
    {
        return view('admin.attachment.index');
    }

    public function logIndex()
    {
        return view('admin.log.index');
    }

    public function environmentIndex()
    {
        return view('admin.environment.index');
    }

    public function environmentPhpinfo()
    {
        ob_start();
        phpinfo();
        $phpinfo = ob_get_clean();

        $phpinfo = preg_replace(
            '#(<body.*?>)(.*?)(</body>)#is',
            '$2',
            $phpinfo
        );

        return response('<!DOCTYPE html><html><head><meta charset="utf-8"><style>body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;font-size:14px;padding:20px;background:#fff;} table{border-collapse:collapse;width:100%;margin-bottom:16px;} td,th{border:1px solid #ddd;padding:8px 12px;text-align:left;} th{background:#f5f5f5;font-weight:600;} h1{font-size:20px;border-bottom:2px solid #5FB878;padding-bottom:8px;} h2{font-size:16px;margin-top:24px;border-bottom:1px solid #eee;padding-bottom:6px;}</style></head><body>' . $phpinfo . '</body></html>');
    }

    public function operationLogIndex()
    {
        return view('admin.operation-log.index');
    }

    public function databaseWelcome()
    {
        return view('admin.database.welcome');
    }

    public function databaseAdvanced()
    {
        return view('admin.database.index');
    }

    public function databaseCheck(string $table)
    {
        $dbService = new DatabaseService;
        $columns = $dbService->getTableColumns($table);

        return view('admin.database.check', compact('table', 'columns'));
    }

    public function databaseRecover(string $table)
    {
        return view('admin.database.recover', compact('table'));
    }

    public function databaseAddFields(string $table)
    {
        $dbService = new DatabaseService;
        $columns = $dbService->getTableColumns($table);

        return view('admin.database.add-fields', compact('table', 'columns'));
    }

    public function databaseEditField(string $table)
    {
        $dbService = new DatabaseService;
        $columns = $dbService->getTableColumns($table);

        return view('admin.database.edit-field', compact('table', 'columns'));
    }

    public function databaseTableAdd(string $table)
    {
        $dbService = new DatabaseService;
        $columns = $dbService->getTableColumns($table);

        return view('admin.database.table-add', compact('table', 'columns'));
    }

    public function databaseTableEdit(string $table)
    {
        $dbService = new DatabaseService;
        $columns = $dbService->getTableColumns($table);

        return view('admin.database.table-edit', compact('table', 'columns'));
    }

    public function databaseTableCopy(string $table)
    {
        $dbService = new DatabaseService;
        $columns = $dbService->getTableColumns($table);

        return view('admin.database.table-copy', compact('table', 'columns'));
    }

    public function categoryIndex()
    {
        return view('admin.content.category.index');
    }

    public function categoryForm()
    {
        return view('admin.content.category.form');
    }

    public function modelIndex()
    {
        return view('admin.content.model.index');
    }

    public function modelForm()
    {
        return view('admin.content.model.form');
    }

    public function modelDesign($id)
    {
        return view('admin.content.model.design', ['id' => $id]);
    }

    public function contentIndex()
    {
        return view('admin.content.index');
    }

    public function contentForm()
    {
        return view('admin.content.form');
    }

    public function appIndex()
    {
        return view('admin.app.index');
    }

    public function appMarket()
    {
        return view('admin.app.market');
    }

    public function appLog()
    {
        return view('admin.app.log');
    }

    public function frontUserIndex()
    {
        return view('admin.front-user.index');
    }

    public function frontUserForm()
    {
        return view('admin.front-user.form');
    }

    public function userGroupIndex()
    {
        return view('admin.user-group.index');
    }

    public function disabledApp(string $appId)
    {
        $app = AppModel::where('app_id', $appId)->first();

        if (! $app) {
            abort(404);
        }

        if ($app->status === AppStatus::ENABLED) {
            abort(404);
        }

        return view('errors.app-disabled', ['appName' => $app->name]);
    }
}
