<?php
namespace App\Controllers;

use App\Models\Tenant;

class SuperAdminController extends Controller {

    public function __construct() {
        parent::__construct();
        
        $uri = $_SERVER['REQUEST_URI'];
        if (($pos = strpos($uri, '?')) !== false) {
            $uri = substr($uri, 0, $pos);
        }
        $uri = rtrim($uri, '/');
        
        $isLoginOrAuth = (str_ends_with($uri, '/superadmin/login') || str_ends_with($uri, '/superadmin/auth'));
        
        if (!$isLoginOrAuth) {
            $user = $this->session->get('superadmin_user');
            if (!$user || $user['role'] !== 'superadmin') {
                $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/superadmin/login');
            }
        }
    }

    public function login() {
        if ($this->session->get('superadmin_user')) {
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/superadmin/dashboard');
        }
        $this->response->render('superadmin/login', [
            'title' => 'Süper Yönetici Girişi - Multi Panel'
        ]);
    }

    public function auth() {
        $body = $this->request->getBody();
        $username = isset($body['username']) ? $body['username'] : '';
        $password = isset($body['password']) ? $body['password'] : '';

        // Simple hardcoded superadmin credentials for demonstration/first run
        if ($username === 'superadmin' && $password === 'super123') {
            $this->session->set('superadmin_user', [
                'username' => 'superadmin',
                'name' => 'Süper Yönetici',
                'role' => 'superadmin'
            ]);
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/superadmin/dashboard');
        }

        $this->response->render('superadmin/login', [
            'error' => 'Geçersiz kullanıcı adı veya şifre.',
            'title' => 'Süper Yönetici Girişi - Multi Panel'
        ]);
    }

    public function logout() {
        $this->session->remove('superadmin_user');
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/superadmin/login');
    }

    public function dashboard() {
        $tenants = Tenant::all();
        $this->response->render('superadmin/dashboard', [
            'tenants' => $tenants,
            'title' => 'Süper Yönetici Paneli - Mağaza Kontrolü'
        ]);
    }

    public function tenantCreate() {
        $this->response->render('superadmin/tenants/create', [
            'title' => 'Yeni Mağaza Oluştur - Süper Yönetici Paneli'
        ]);
    }

    public function tenantStore() {
        $body = $this->request->getBody();
        $id = strtolower(trim(isset($body['id']) ? $body['id'] : ''));
        $name = trim(isset($body['name']) ? $body['name'] : '');
        $domain = strtolower(trim(isset($body['domain']) ? $body['domain'] : ''));
        $subdomainsRaw = trim(isset($body['subdomains']) ? $body['subdomains'] : '');
        
        $subdomains = array_filter(array_map('trim', explode(',', $subdomainsRaw)));
        if (empty($subdomains)) {
            $subdomains = ['www'];
        }

        if (empty($id) || empty($name) || empty($domain)) {
            return $this->response->render('superadmin/tenants/create', [
                'error' => 'Lütfen tüm alanları doldurun.',
                'title' => 'Yeni Mağaza Oluştur - Süper Yönetici Paneli'
            ]);
        }

        // Validate unique tenant ID
        $tenants = Tenant::all();
        foreach ($tenants as $t) {
            if ($t['id'] === $id) {
                return $this->response->render('superadmin/tenants/create', [
                    'error' => 'Bu Mağaza ID\'si zaten kullanılıyor.',
                    'title' => 'Yeni Mağaza Oluştur - Süper Yönetici Paneli'
                ]);
            }
        }

        // Create tenant folder structure
        $tenantDir = __DIR__ . '/../../data/tenants/' . $id;
        if (!is_dir($tenantDir)) {
            mkdir($tenantDir, 0777, true);
        }

        // Copy template data files or create blank ones
        $products = [];
        $categories = [];
        $orders = [];
        
        $settings = [
            'store_name' => $name,
            'store_title' => $name . ' Mağazası',
            'store_description' => $name . ' e-ticaret sitesi.',
            'store_keywords' => 'eticaret, magaza',
            'email' => 'admin@' . $domain,
            'telephone' => '',
            'address' => '',
            'brands' => [],
            'base_currency' => 'TRY'
        ];
        
        $users = [
            [
                'id' => 'user_admin',
                'username' => 'admin',
                'password' => password_hash('admin123', PASSWORD_DEFAULT),
                'role' => 'admin',
                'name' => $name . ' Yönetici',
                'status' => 1
            ]
        ];

        file_put_contents("$tenantDir/products.json", json_encode($products, JSON_PRETTY_PRINT));
        file_put_contents("$tenantDir/categories.json", json_encode($categories, JSON_PRETTY_PRINT));
        file_put_contents("$tenantDir/orders.json", json_encode($orders, JSON_PRETTY_PRINT));
        file_put_contents("$tenantDir/settings.json", json_encode($settings, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        file_put_contents("$tenantDir/users.json", json_encode($users, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

        // Save new tenant globally
        $tenants[] = [
            'id' => $id,
            'name' => $name,
            'domain' => $domain,
            'subdomains' => array_values($subdomains),
            'status' => 1
        ];

        Tenant::save($tenants);
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/superadmin/dashboard');
    }

    public function tenantDelete($id) {
        // Main tenant cannot be deleted
        if ($id === 'everestburo') {
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/superadmin/dashboard');
        }

        $tenants = Tenant::all();
        $updatedTenants = [];
        foreach ($tenants as $t) {
            if ($t['id'] !== $id) {
                $updatedTenants[] = $t;
            }
        }

        Tenant::save($updatedTenants);
        
        // Note: For safety, we do not recursively delete the data/tenants/{id} folder automatically in this script.
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/superadmin/dashboard');
    }
}
