<?php

namespace App\Controllers;

class Auth extends BaseController
{
    public function login()
    {
        if (session()->get('isLoggedIn')) {
            return redirect()->to(session()->get('role') === 'admin' ? 'admin/dashboard' : 'dashboard');
        }
        return view('auth/login');
    }
    
    public function register()
    {
        if (session()->get('isLoggedIn')) {
            return redirect()->to('dashboard');
        }
        $domain = $this->request->getGet('domain');
        $suffix = $this->request->getGet('suffix');
        return view('auth/register', ['domain' => $domain, 'suffix_id' => $suffix]);
    }

    public function processLogin()
    {
        $db = \Config\Database::connect();
        $email = $this->request->getPost('email');
        $password = $this->request->getPost('password');

        $user = $db->table('users')->where('email', $email)->get()->getRowArray();

        if ($user && password_verify($password, $user['password'])) {
            if($user['status'] == 'suspended') {
                return redirect()->back()->with('error', 'Your account is suspended.');
            }
            session()->set([
                'id' => $user['id'],
                'username' => $user['username'],
                'email' => $user['email'],
                'role' => $user['role'],
                'isLoggedIn' => true
            ]);
            return redirect()->to($user['role'] === 'admin' ? 'admin/dashboard' : 'dashboard')->with('success', 'Logged in successfully!');
        }

        return redirect()->back()->with('error', 'Invalid email or password.');
    }

    public function processRegister()
    {
        $db = \Config\Database::connect();
        
        $username = $this->request->getPost('username');
        $email = $this->request->getPost('email');
        $password = $this->request->getPost('password');
        $passwordConfirm = $this->request->getPost('password_confirm');
        $domain = $this->request->getPost('domain');
        $suffixId = $this->request->getPost('suffix_id');

        if ($password !== $passwordConfirm) {
            return redirect()->back()->with('error', 'Passwords do not match.');
        }

        $existing = $db->table('users')->where('email', $email)->countAllResults();
        if ($existing > 0) {
            return redirect()->back()->with('error', 'Email already exists.');
        }

        $userData = [
            'username' => $username,
            'email' => $email,
            'password' => password_hash($password, PASSWORD_DEFAULT),
            'role' => 'user',
            'status' => 'active',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ];

        $db->table('users')->insert($userData);
        $userId = $db->insertID();

        if ($domain && $suffixId) {
            // Register their requested domain to them as well
            $subdomain = str_replace($db->table('suffixes')->where('id', $suffixId)->get()->getRow()->suffix, '', $domain);
            $db->table('domains')->insert([
                'user_id' => $userId,
                'suffix_id' => $suffixId,
                'subdomain' => $subdomain,
                'full_domain' => $domain,
                'status' => 'active',
                'created_at' => date('Y-m-d H:i:s')
            ]);
        }

        session()->set([
            'id' => $userId,
            'username' => $username,
            'email' => $email,
            'role' => 'user',
            'isLoggedIn' => true
        ]);

        return redirect()->to('dashboard')->with('success', 'Account created successfully!');
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to('/');
    }
}
