<?php

namespace App\Controllers;

class Dashboard extends BaseController
{
    public function index()
    {
        $db = \Config\Database::connect();
        $userId = session()->get('id');
        $domains = $db->table('domains')->where('user_id', $userId)->get()->getResult();

        return view('dashboard/index', ['domains' => $domains]);
    }

    public function manage($domainId)
    {
        $db = \Config\Database::connect();
        $userId = session()->get('id');
        
        $domain = $db->table('domains')->where('id', $domainId)->where('user_id', $userId)->get()->getRow();
        if (!$domain) {
            return redirect()->to('dashboard')->with('error', 'Domain not found.');
        }

        $records = $db->table('dns_records')->where('domain_id', $domainId)->get()->getResult();

        return view('dashboard/manage', ['domain' => $domain, 'records' => $records]);
    }

    public function saveNs()
    {
        $db = \Config\Database::connect();
        $userId = session()->get('id');
        $domainId = $this->request->getPost('domain_id');
        $ns1 = $this->request->getPost('custom_ns1');
        $ns2 = $this->request->getPost('custom_ns2');

        $domain = $db->table('domains')->where('id', $domainId)->where('user_id', $userId)->get()->getRow();
        if (!$domain) {
            return redirect()->back()->with('error', 'Domain not found.');
        }

        $db->table('domains')->where('id', $domainId)->update([
            'custom_ns1' => $ns1,
            'custom_ns2' => $ns2,
            'updated_at' => date('Y-m-d H:i:s')
        ]);

        // Cloudflare Sync
        $cf = new \App\Libraries\Cloudflare();
        if ($cf->isConfigured()) {
            $cf->deleteRecordsByName($domain->full_domain, 'NS');
            if (!empty($ns1)) $cf->createRecord('NS', $domain->full_domain, $ns1);
            if (!empty($ns2)) $cf->createRecord('NS', $domain->full_domain, $ns2);
        }

        return redirect()->back()->with('success', 'Custom nameservers updated. They will be applied shortly.');
    }

    public function addDnsRecord()
    {
        $db = \Config\Database::connect();
        $userId = session()->get('id');
        $domainId = $this->request->getPost('domain_id');

        $domain = $db->table('domains')->where('id', $domainId)->where('user_id', $userId)->get()->getRow();
        if (!$domain) {
            return redirect()->back()->with('error', 'Domain not found.');
        }

        $type = $this->request->getPost('type');
        $name = $this->request->getPost('name');
        $content = $this->request->getPost('content');

        $db->table('dns_records')->insert([
            'domain_id' => $domainId,
            'type' => $type,
            'name' => $name,
            'content' => $content,
            'ttl' => 1,
            'created_at' => date('Y-m-d H:i:s')
        ]);

        // Cloudflare Sync
        $cf = new \App\Libraries\Cloudflare();
        if ($cf->isConfigured()) {
            $fqdn = ($name === '@') ? $domain->full_domain : $name . '.' . $domain->full_domain;
            $cfReq = $cf->createRecord($type, $fqdn, $content);
            if(isset($cfReq['success']) && !$cfReq['success']) {
                $errs = implode(", ", $cfReq['errors'] ?? ['Unknown CF Error']);
                return redirect()->back()->with('error', 'Saved locally but Cloudflare sync failed: ' . $errs);
            }
        }

        return redirect()->back()->with('success', 'DNS Record added successfully.');
    }

    public function deleteDnsRecord($recordId)
    {
        $db = \Config\Database::connect();
        $userId = session()->get('id');
        
        $record = $db->table('dns_records')->where('id', $recordId)->get()->getRow();
        if (!$record) return redirect()->back();

        $domain = $db->table('domains')->where('id', $record->domain_id)->where('user_id', $userId)->get()->getRow();
        if (!$domain) return redirect()->back()->with('error', 'Denied.');

        $db->table('dns_records')->where('id', $recordId)->delete();
        
        // Cloudflare Sync
        $cf = new \App\Libraries\Cloudflare();
        if ($cf->isConfigured()) {
            $fqdn = ($record->name === '@') ? $domain->full_domain : $record->name . '.' . $domain->full_domain;
            $cf->deleteRecordsByName($fqdn, $record->type, $record->content);
        }

        return redirect()->back()->with('success', 'DNS Record deleted.');
    }
}
