<?php

namespace App\Core\Database\Controllers;

use App\Controllers\BaseController;
use App\Core\Audit\Services\AuditService;
use App\Core\Database\Models\DatabaseConnectionModel;
use App\Core\Database\Services\DatabaseConnectionService;
use Throwable;

class DatabaseConnectionController extends BaseController
{
    public function index()
    {
        return view('core/database/index', [
            'title' => 'Connexions SQL',
            'connections' => (new DatabaseConnectionModel())->orderBy('name')->findAll(),
        ]);
    }

    public function store()
    {
        $rules = [
            'name' => 'required|max_length[120]',
            'host' => 'required|max_length[190]',
            'database_name' => 'required|max_length[190]',
            'username' => 'required|max_length[190]',
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('error', 'Connexion invalide.');
        }

        $service = new DatabaseConnectionService();
        $id = (new DatabaseConnectionModel())->insert([
            'name' => (string) $this->request->getPost('name'),
            'driver' => 'MySQLi',
            'host' => (string) $this->request->getPost('host'),
            'port' => (int) ($this->request->getPost('port') ?: 3306),
            'database_name' => (string) $this->request->getPost('database_name'),
            'username' => (string) $this->request->getPost('username'),
            'encrypted_password' => $service->encryptPassword((string) $this->request->getPost('password')),
            'charset' => 'utf8mb4',
            'status' => 'active',
        ], true);

        (new AuditService())->log('db_connection.create', 'database_connection', (string) $id, 'Création connexion SQL');

        return redirect()->back()->with('success', 'Connexion enregistrée.');
    }

    public function show(int $id)
    {
        $model = new DatabaseConnectionModel();
        $connection = $model->find($id);
        $tables = [];
        $error = null;

        try {
            $tables = (new DatabaseConnectionService())->getTables($id);
        } catch (Throwable $e) {
            $error = $e->getMessage();
        }

        return view('core/database/show', [
            'title' => 'Tables SQL',
            'connection' => $connection,
            'tables' => $tables,
            'error' => $error,
        ]);
    }
}
