<?php

namespace App\Libraries;

class Cloudflare
{
    private $email;
    private $apiKey;
    private $zoneId;
    private $apiUrl = 'https://api.cloudflare.com/client/v4/';

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

        $this->email = $settings['cf_email'] ?? '';
        $this->apiKey = $settings['cf_api_key'] ?? '';
        $this->zoneId = $settings['cf_zone_id'] ?? '';
    }

    public function isConfigured()
    {
        return !empty($this->apiKey) && !empty($this->zoneId);
    }

    private function request($method, $endpoint, $data = null)
    {
        if (!$this->isConfigured()) return ['success' => false, 'errors' => ['Cloudflare API not configured in settings.']];

        $url = $this->apiUrl . ltrim($endpoint, '/');
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $headers = [
            'X-Auth-Email: ' . $this->email,
            'X-Auth-Key: ' . $this->apiKey,
            'Content-Type: application/json'
        ];
        
        // If ApiKey is actually an API Token (Bearer), adjust headers gracefully fallback
        if (empty($this->email) && !empty($this->apiKey)) {
            $headers = [
                'Authorization: Bearer ' . $this->apiKey,
                'Content-Type: application/json'
            ];
        }

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);

        if ($data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }

        $response = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);

        if ($err) {
            return ['success' => false, 'errors' => [$err]];
        }

        return json_decode($response, true);
    }

    public function createRecord($type, $name, $content, $ttl = 1)
    {
        $endpoint = "zones/{$this->zoneId}/dns_records";
        $data = [
            'type' => strtoupper($type),
            'name' => $name,
            'content' => $content,
            'ttl' => (int)$ttl,
            'proxied' => false
        ];

        return $this->request('POST', $endpoint, $data);
    }

    public function deleteRecordsByName($name, $type = null, $content = null)
    {
        $endpoint = "zones/{$this->zoneId}/dns_records?name=" . urlencode($name);
        if ($type) $endpoint .= "&type=" . strtoupper($type);
        if ($content) $endpoint .= "&content=" . urlencode($content);

        $res = $this->request('GET', $endpoint);
        
        if (isset($res['success']) && $res['success'] && !empty($res['result'])) {
            $deletedCount = 0;
            foreach ($res['result'] as $record) {
                $delEndpoint = "zones/{$this->zoneId}/dns_records/{$record['id']}";
                $delRes = $this->request('DELETE', $delEndpoint);
                if (isset($delRes['success']) && $delRes['success']) {
                    $deletedCount++;
                }
            }
            return ['success' => true, 'deleted' => $deletedCount];
        }
        
        return ['success' => false, 'msg' => 'No matching records found to delete.'];
    }
}
