<?php

namespace App\Controllers;

class Admin extends BaseController
{
    public function dashboard()
    {
        $db = \Config\Database::connect();
        
        $stats = [
            'total_users' => $db->table('users')->countAll(),
            'total_domains' => $db->table('domains')->countAll(),
            'active_domains' => $db->table('domains')->where('status', 'active')->countAllResults(),
            'total_records' => $db->table('dns_records')->countAll()
        ];
        
        return view('admin/dashboard', ['stats' => $stats]);
    }

    public function users()
    {
        $db = \Config\Database::connect();
        $users = $db->table('users')->orderBy('id', 'DESC')->get()->getResult();
        return view('admin/users', ['users' => $users]);
    }
    
    public function toggleUserStatus($id)
    {
        $db = \Config\Database::connect();
        $user = $db->table('users')->where('id', $id)->get()->getRow();
        if ($user) {
            $newStatus = $user->status === 'active' ? 'suspended' : 'active';
            $db->table('users')->where('id', $id)->update(['status' => $newStatus]);
            return redirect()->back()->with('success', "User status changed to $newStatus");
        }
        return redirect()->back();
    }

    public function domains()
    {
        $db = \Config\Database::connect();
        $domains = $db->table('domains')
                      ->select('domains.*, users.username, users.email')
                      ->join('users', 'users.id = domains.user_id')
                      ->orderBy('domains.id', 'DESC')
                      ->get()->getResult();
                      
        return view('admin/domains', ['domains' => $domains]);
    }

    public function deleteDomain($id)
    {
        $db = \Config\Database::connect();
        $db->table('domains')->where('id', $id)->delete();
        return redirect()->back()->with('success', 'Domain deleted successfully.');
    }

    public function settings()
    {
        $db = \Config\Database::connect();
        $settingsRaw = $db->table('settings')->get()->getResult();
        $settings = [];
        foreach ($settingsRaw as $s) {
            $settings[$s->setting_key] = $s->setting_value;
        }

        return view('admin/settings', ['settings' => $settings]);
    }

    public function saveSettings()
    {
        $db = \Config\Database::connect();
        $postData = $this->request->getPost();

        foreach ($postData as $key => $value) {
            $db->table('settings')->where('setting_key', $key)->update(['setting_value' => $value]);
        }

        return redirect()->back()->with('success', 'Settings updated automatically.');
    }

    public function suffixes()
    {
        $db = \Config\Database::connect();
        $suffixes = $db->table('suffixes')->orderBy('id', 'DESC')->get()->getResult();
        return view('admin/suffixes', ['suffixes' => $suffixes]);
    }

    public function addSuffix()
    {
        $db = \Config\Database::connect();
        $suffix = $this->request->getPost('suffix');
        
        // Ensure starting dot
        if (substr($suffix, 0, 1) !== '.') {
            $suffix = '.' . $suffix;
        }

        $db->table('suffixes')->insert([
            'suffix' => $suffix,
            'is_active' => 1
        ]);
        return redirect()->back()->with('success', 'New suffix activated.');
    }

    public function deleteSuffix($id)
    {
        $db = \Config\Database::connect();
        $db->table('suffixes')->where('id', $id)->delete();
        return redirect()->back()->with('success', 'Suffix deleted.');
    }
}
