<?php

namespace App\Controllers;

use App\Models\UserModel;
use App\Models\ProductModel;
use App\Models\OrderModel;
use App\Models\OfferModel;
use App\Models\NotificationModel;

class SuperAdmin extends BaseController
{
    protected $userModel;
    protected $productModel;
    protected $orderModel;
    protected $offerModel;
    protected $notificationModel;

    public function __construct()
    {
        $this->userModel = new UserModel();
        $this->productModel = new ProductModel();
        $this->orderModel = new OrderModel();
        $this->offerModel = new OfferModel();
        $this->notificationModel = new NotificationModel();
    }

    private function checkSuperAdminAccess()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }

        $role = session()->get('role') ?: session()->get('user_type');
        if ($role !== 'super_admin') {
            return redirect()->to('/dashboard')->with('error', 'Access denied - Super Admin only');
        }

        return null;
    }

    // SA1 - Dashboard with system overview
    public function dashboard()
    {
        $check = $this->checkSuperAdminAccess();
        if ($check) return $check;

        $userId = session()->get('user_id');
        $user = $this->userModel->find($userId);

        // Get system statistics
        $stats = [
            'total_users' => $this->userModel->countAllResults(),
            'total_buyers' => $this->userModel->where('user_type', 'buyer')->countAllResults(),
            'total_sellers' => $this->userModel->where('user_type', 'seller')->countAllResults(),
            'total_delivery' => $this->userModel->where('user_type', 'delivery')->countAllResults(),
            'total_admins' => $this->userModel->where('user_type', 'admin')->countAllResults(),
            'total_products' => $this->productModel->countAllResults(),
            'pending_products' => $this->productModel->where('status', 'pending')->countAllResults(),
            'approved_products' => $this->productModel->where('status', 'approved')->countAllResults(),
            'total_orders' => $this->orderModel->countAllResults(),
            'active_orders' => $this->orderModel->whereIn('status', ['pending', 'dispatched', 'in_transit'])->countAllResults(),
        ];

        // Get recent activities
        $recentUsers = $this->userModel->orderBy('created_at', 'DESC')->limit(10)->findAll();
        $recentOrders = $this->orderModel->orderBy('created_at', 'DESC')->limit(10)->findAll();

        $data = [
            'user' => $user,
            'stats' => $stats,
            'recentUsers' => $recentUsers,
            'recentOrders' => $recentOrders,
        ];

        return view('superadmin/dashboard', $data);
    }

    // SA2 - Manage Admins
    public function admins()
    {
        if ($check = $this->checkSuperAdminAccess()) return('/login');
        }

        $userId = session()->get('user_id');
        $user = $this->userModel->find($userId);

        $admins = $this->userModel
            ->where('user_type', 'admin')
            ->orderBy('created_at', 'DESC')
            ->findAll();

        $data = [
            'user' => $user,
            'admins' => $admins,
        ];

        return view('superadmin/admins', $data);
    }

    // SA3 - Create Admin
    public function createAdmin()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $validation = \Config\Services::validation();
        
        $rules = [
            'name' => 'required|min_length[3]',
            'email' => 'required|valid_email|is_unique[users.email]',
            'mobile' => 'required|min_length[10]|max_length[15]',
            'password' => 'required|min_length[6]',
        ];

        if (!$this->validate($rules)) {
            return $this->response->setJSON([
                'success' => false,
                'errors' => $validation->getErrors()
            ]);
        }

        $adminData = [
            'name' => $this->request->getPost('name'),
            'email' => $this->request->getPost('email'),
            'mobile' => $this->request->getPost('mobile'),
            'password' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
            'user_type' => 'admin',
            'is_verified' => 1,
        ];

        $adminId = $this->userModel->insert($adminData);

        if ($adminId) {
            return $this->response->setJSON([
                'success' => true,
                'message' => 'Admin created successfully'
            ]);
        }

        return $this->response->setJSON([
            'success' => false,
            'message' => 'Failed to create admin'
        ]);
    }

    // SA4 - Delete/Deactivate Admin
    public function deleteAdmin($adminId)
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $admin = $this->userModel->find($adminId);

        if (!$admin || $admin['user_type'] !== 'admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Admin not found']);
        }

        // Soft delete or deactivate
        $this->userModel->update($adminId, ['is_verified' => 0]);

        return $this->response->setJSON(['success' => true, 'message' => 'Admin deactivated successfully']);
    }

    // SA5 - System Settings
    public function settings()
    {
        if ($check = $this->checkSuperAdminAccess()) return('/login');
        }

        $userId = session()->get('user_id');
        $user = $this->userModel->find($userId);

        // Get system settings from database or config
        $settings = [
            'site_name' => 'Flex Market',
            'commission_rate' => 5, // %
            'delivery_charge' => 50,
            'min_order_value' => 100,
        ];

        $data = [
            'user' => $user,
            'settings' => $settings,
        ];

        return view('superadmin/settings', $data);
    }

    // SA6 - Update System Settings
    public function updateSettings()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        // Update settings in database or config
        // For now, just return success
        
        return $this->response->setJSON(['success' => true, 'message' => 'Settings updated successfully']);
    }

    // SA7 - View All Users
    public function users()
    {
        if ($check = $this->checkSuperAdminAccess()) return('/login');
        }

        $userId = session()->get('user_id');
        $user = $this->userModel->find($userId);

        $userType = $this->request->getGet('type');
        
        $builder = $this->userModel;
        if ($userType) {
            $builder->where('user_type', $userType);
        }

        $users = $builder->orderBy('created_at', 'DESC')->findAll();

        $data = [
            'user' => $user,
            'users' => $users,
            'filterType' => $userType,
        ];

        return view('superadmin/users', $data);
    }

    // SA8 - Suspend/Activate User
    public function toggleUserStatus($targetUserId)
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $targetUser = $this->userModel->find($targetUserId);

        if (!$targetUser) {
            return $this->response->setJSON(['success' => false, 'message' => 'User not found']);
        }

        // Toggle verified status (1 = active, 0 = suspended)
        $newStatus = $targetUser['is_verified'] ? 0 : 1;
        $this->userModel->update($targetUserId, ['is_verified' => $newStatus]);

        $message = $newStatus ? 'User activated successfully' : 'User suspended successfully';
        
        return $this->response->setJSON(['success' => true, 'message' => $message]);
    }

    // SA9 - System Reports
    public function reports()
    {
        if ($check = $this->checkSuperAdminAccess()) return('/login');
        }

        $userId = session()->get('user_id');
        $user = $this->userModel->find($userId);

        // Generate various reports
        $reports = [
            'daily_orders' => $this->orderModel->where('DATE(created_at)', date('Y-m-d'))->countAllResults(),
            'weekly_orders' => $this->orderModel->where('created_at >=', date('Y-m-d', strtotime('-7 days')))->countAllResults(),
            'monthly_orders' => $this->orderModel->where('created_at >=', date('Y-m-d', strtotime('-30 days')))->countAllResults(),
            'total_revenue' => 0, // Calculate from orders
        ];

        $data = [
            'user' => $user,
            'reports' => $reports,
        ];

        return view('superadmin/reports', $data);
    }

    // SA1, SA2 - Mark BGV Cleared for Delivery Person(s)
    public function markBGVCleared($userId)
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $user = $this->userModel->find($userId);
        if (!$user || $user['user_type'] !== 'delivery') {
            return $this->response->setJSON(['success' => false, 'message' => 'Invalid delivery person']);
        }

        $this->userModel->update($userId, ['bgv_cleared' => 1]);

        return $this->response->setJSON(['success' => true, 'message' => 'BGV cleared successfully']);
    }

    public function markBGVClearedBulk()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $userIds = $this->request->getPost('user_ids');
        if (empty($userIds)) {
            return $this->response->setJSON(['success' => false, 'message' => 'No users selected']);
        }

        $this->userModel->whereIn('id', $userIds)
                        ->where('user_type', 'delivery')
                        ->set(['bgv_cleared' => 1])
                        ->update();

        return $this->response->setJSON(['success' => true, 'message' => 'BGV cleared for selected delivery persons']);
    }

    // SA3 - Manage Pin Codes/Cities/States
    public function managePinCodes()
    {
        if ($check = $this->checkSuperAdminAccess()) return('/login');
        }

        $db = \Config\Database::connect();
        $allowedPinCodes = $db->table('allowed_pin_codes')->get()->getResultArray();

        $data = [
            'user' => $this->userModel->find(session()->get('user_id')),
            'pin_codes' => $allowedPinCodes,
        ];

        return view('superadmin/pin_codes', $data);
    }

    public function addPinCode()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $data = [
            'pin_code' => $this->request->getPost('pin_code'),
            'city' => $this->request->getPost('city'),
            'state' => $this->request->getPost('state'),
        ];

        $db->table('allowed_pin_codes')->insert($data);

        return $this->response->setJSON(['success' => true, 'message' => 'Pin code added successfully']);
    }

    public function removePinCode($id)
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $db->table('allowed_pin_codes')->where('id', $id)->delete();

        return $this->response->setJSON(['success' => true, 'message' => 'Pin code removed successfully']);
    }

    // SA4 - Manage Listing Types (Clothes, Accessories, Furniture, Electronics)
    public function manageListingTypes()
    {
        if ($check = $this->checkSuperAdminAccess()) return('/login');
        }

        $db = \Config\Database::connect();
        $listingTypes = $db->table('listing_types')->get()->getResultArray();

        $data = [
            'user' => $this->userModel->find(session()->get('user_id')),
            'listing_types' => $listingTypes,
        ];

        return view('superadmin/listing_types', $data);
    }

    public function addListingType()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $data = [
            'type_name' => $this->request->getPost('type_name'),
            'category' => $this->request->getPost('category'),
        ];

        $db->table('listing_types')->insert($data);

        return $this->response->setJSON(['success' => true, 'message' => 'Listing type added successfully']);
    }

    public function removeListingType($id)
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $db->table('listing_types')->where('id', $id)->delete();

        return $this->response->setJSON(['success' => true, 'message' => 'Listing type removed successfully']);
    }

    // SA5 - Toggle Admin Approval Requirement
    public function toggleApprovalRequired()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $currentSetting = $db->table('system_settings')
                             ->where('setting_key', 'product_approval_required')
                             ->get()
                             ->getRowArray();

        $newValue = $currentSetting ? !$currentSetting['setting_value'] : 1;

        if ($currentSetting) {
            $db->table('system_settings')
               ->where('setting_key', 'product_approval_required')
               ->update(['setting_value' => $newValue]);
        } else {
            $db->table('system_settings')->insert([
                'setting_key' => 'product_approval_required',
                'setting_value' => $newValue,
            ]);
        }

        return $this->response->setJSON([
            'success' => true,
            'message' => 'Approval setting updated',
            'approval_required' => $newValue,
        ]);
    }

    // SA13 - Modify Delivery Formula
    public function updateDeliveryFormula()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $formula = [
            'base_charge' => $this->request->getPost('base_charge'),
            'per_km_charge' => $this->request->getPost('per_km_charge'),
            'weight_multiplier' => $this->request->getPost('weight_multiplier'),
        ];

        $db->table('system_settings')
           ->where('setting_key', 'delivery_formula')
           ->set(['setting_value' => json_encode($formula)])
           ->update();

        return $this->response->setJSON(['success' => true, 'message' => 'Delivery formula updated']);
    }

    // SA14 - Toggle Maintenance Mode
    public function toggleMaintenanceMode()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $currentSetting = $db->table('system_settings')
                             ->where('setting_key', 'maintenance_mode')
                             ->get()
                             ->getRowArray();

        $newValue = $currentSetting ? !$currentSetting['setting_value'] : 1;

        if ($currentSetting) {
            $db->table('system_settings')
               ->where('setting_key', 'maintenance_mode')
               ->update(['setting_value' => $newValue]);
        } else {
            $db->table('system_settings')->insert([
                'setting_key' => 'maintenance_mode',
                'setting_value' => $newValue,
            ]);
        }

        return $this->response->setJSON([
            'success' => true,
            'message' => 'Maintenance mode ' . ($newValue ? 'enabled' : 'disabled'),
            'maintenance_mode' => $newValue,
        ]);
    }

    // SA16 - Extend Rental Date
    public function extendRentalDate($orderId)
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $order = $this->orderModel->find($orderId);
        if (!$order || $order['order_type'] !== 'rent') {
            return $this->response->setJSON(['success' => false, 'message' => 'Invalid rental order']);
        }

        $newEndDate = $this->request->getPost('new_end_date');
        $proof = $this->request->getPost('proof_of_confirmation');

        $this->orderModel->update($orderId, [
            'rental_end_date' => $newEndDate,
            'rental_extension_proof' => $proof,
        ]);

        return $this->response->setJSON(['success' => true, 'message' => 'Rental date extended successfully']);
    }

    // SA17 - Bank Account Security Control (placeholder)
    public function manageBankSecurity()
    {
        if ($check = $this->checkSuperAdminAccess()) return('/login');
        }

        $data = [
            'user' => $this->userModel->find(session()->get('user_id')),
        ];

        return view('superadmin/bank_security', $data);
    }

    // SA18 - Modify Badge Requirements for Brand Creation
    public function updateBrandBadgeRequirement()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $badgeCount = $this->request->getPost('badge_count');

        $db->table('system_settings')
           ->where('setting_key', 'brand_badge_requirement')
           ->set(['setting_value' => $badgeCount])
           ->update();

        return $this->response->setJSON(['success' => true, 'message' => 'Badge requirement updated']);
    }

    // SA19 - Set Minimum Transaction Amount for Seller
    public function updateMinTransactionAmount()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $minAmount = $this->request->getPost('min_amount');

        $db->table('system_settings')
           ->where('setting_key', 'seller_min_transaction_amount')
           ->set(['setting_value' => $minAmount])
           ->update();

        return $this->response->setJSON(['success' => true, 'message' => 'Minimum transaction amount updated']);
    }

    // SA20 - Configure Commission Percentages
    public function updateCommissionRates()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $rates = [
            'platform_commission' => $this->request->getPost('platform_commission'),
            'delivery_commission' => $this->request->getPost('delivery_commission'),
            'payment_gateway_commission' => $this->request->getPost('payment_gateway_commission'),
        ];

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

        return $this->response->setJSON(['success' => true, 'message' => 'Commission rates updated']);
    }

    // SA21 - Set GST Percentage
    public function updateGSTRate()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $gstRate = $this->request->getPost('gst_rate');

        $db->table('system_settings')
           ->where('setting_key', 'gst_rate')
           ->set(['setting_value' => $gstRate])
           ->update();

        return $this->response->setJSON(['success' => true, 'message' => 'GST rate updated']);
    }

    // SA22 - Manage Contact Viewing Range
    public function updateContactViewingRange()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $ranges = [
            'daily_range' => $this->request->getPost('daily_range'),
            'weekly_range' => $this->request->getPost('weekly_range'),
            'monthly_range' => $this->request->getPost('monthly_range'),
        ];

        $db->table('system_settings')
           ->where('setting_key', 'contact_viewing_ranges')
           ->set(['setting_value' => json_encode($ranges)])
           ->update();

        return $this->response->setJSON(['success' => true, 'message' => 'Contact viewing ranges updated']);
    }

    // SA23 - Manage Subscription Models
    public function manageSubscriptionModels()
    {
        if ($check = $this->checkSuperAdminAccess()) return('/login');
        }

        $db = \Config\Database::connect();
        $subscriptions = $db->table('subscription_plans')->get()->getResultArray();

        $data = [
            'user' => $this->userModel->find(session()->get('user_id')),
            'subscriptions' => $subscriptions,
        ];

        return view('superadmin/subscription_models', $data);
    }

    public function addSubscriptionModel()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $data = [
            'plan_name' => $this->request->getPost('plan_name'),
            'duration' => $this->request->getPost('duration'), // monthly, quarterly, yearly
            'price' => $this->request->getPost('price'),
            'features' => $this->request->getPost('features'),
        ];

        $db->table('subscription_plans')->insert($data);

        return $this->response->setJSON(['success' => true, 'message' => 'Subscription model added']);
    }

    public function updateSubscriptionModel($planId)
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $data = [
            'plan_name' => $this->request->getPost('plan_name'),
            'price' => $this->request->getPost('price'),
            'features' => $this->request->getPost('features'),
        ];

        $db->table('subscription_plans')->where('id', $planId)->update($data);

        return $this->response->setJSON(['success' => true, 'message' => 'Subscription model updated']);
    }

    // SA24 - Manage Price Range for Subscriptions
    public function updateSubscriptionPriceRange()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $priceRange = [
            'min_price' => $this->request->getPost('min_price'),
            'max_price' => $this->request->getPost('max_price'),
        ];

        $db->table('system_settings')
           ->where('setting_key', 'subscription_price_range')
           ->set(['setting_value' => json_encode($priceRange)])
           ->update();

        return $this->response->setJSON(['success' => true, 'message' => 'Subscription price range updated']);
    }

    // SA25 - Create User/Product Categories
    public function manageCategories()
    {
        if ($check = $this->checkSuperAdminAccess()) return('/login');
        }

        $db = \Config\Database::connect();
        $categories = $db->table('categories')->get()->getResultArray();

        $data = [
            'user' => $this->userModel->find(session()->get('user_id')),
            'categories' => $categories,
        ];

        return view('superadmin/categories', $data);
    }

    public function addCategory()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $data = [
            'category_name' => $this->request->getPost('category_name'),
            'category_type' => $this->request->getPost('category_type'), // user or product
            'applies_to' => $this->request->getPost('applies_to'), // new_users, all_users, etc.
        ];

        $db->table('categories')->insert($data);

        return $this->response->setJSON(['success' => true, 'message' => 'Category created']);
    }

    // SA26-SA28 - Brand Management
    public function manageBrands()
    {
        if ($check = $this->checkSuperAdminAccess()) return('/login');
        }

        $brandModel = new \App\Models\BrandModel();
        $brands = $brandModel->findAll();

        $data = [
            'user' => $this->userModel->find(session()->get('user_id')),
            'brands' => $brands,
        ];

        return view('superadmin/brands', $data);
    }

    public function createBrand()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $brandModel = new \App\Models\BrandModel();
        
        $data = [
            'seller_id' => $this->request->getPost('seller_id'),
            'brand_name' => $this->request->getPost('brand_name'),
            'description' => $this->request->getPost('description'),
            'created_by_admin' => 1,
        ];

        $brandModel->insert($data);

        return $this->response->setJSON(['success' => true, 'message' => 'Brand created successfully']);
    }

    public function tagProductToBrand()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $productId = $this->request->getPost('product_id');
        $brandId = $this->request->getPost('brand_id');

        $this->productModel->update($productId, ['brand_id' => $brandId]);

        return $this->response->setJSON(['success' => true, 'message' => 'Product tagged to brand']);
    }

    public function blockBrand($brandId)
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $brandModel = new \App\Models\BrandModel();
        $brandModel->update($brandId, ['is_blocked' => 1]);

        return $this->response->setJSON(['success' => true, 'message' => 'Brand blocked']);
    }

    public function unblockBrand($brandId)
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $brandModel = new \App\Models\BrandModel();
        $brandModel->update($brandId, ['is_blocked' => 0]);

        return $this->response->setJSON(['success' => true, 'message' => 'Brand unblocked']);
    }

    // SA29 - Advertisement Management
    public function manageAdvertisements()
    {
        if ($check = $this->checkSuperAdminAccess()) return('/login');
        }

        $db = \Config\Database::connect();
        $advertisements = $db->table('advertisements')->get()->getResultArray();

        $data = [
            'user' => $this->userModel->find(session()->get('user_id')),
            'advertisements' => $advertisements,
        ];

        return view('superadmin/advertisements', $data);
    }

    public function uploadAdvertisement()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $file = $this->request->getFile('ad_media');
        if ($file && $file->isValid()) {
            $newName = $file->getRandomName();
            $file->move(WRITEPATH . 'uploads/advertisements/', $newName);

            $db = \Config\Database::connect();
            $data = [
                'title' => $this->request->getPost('title'),
                'media_path' => $newName,
                'media_type' => $file->getMimeType(),
                'position' => $this->request->getPost('position'),
                'is_active' => 1,
            ];

            $db->table('advertisements')->insert($data);

            return $this->response->setJSON(['success' => true, 'message' => 'Advertisement uploaded']);
        }

        return $this->response->setJSON(['success' => false, 'message' => 'File upload failed']);
    }

    public function toggleAdvertisement($adId)
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $ad = $db->table('advertisements')->where('id', $adId)->get()->getRowArray();

        if ($ad) {
            $newStatus = $ad['is_active'] ? 0 : 1;
            $db->table('advertisements')->where('id', $adId)->update(['is_active' => $newStatus]);

            return $this->response->setJSON(['success' => true, 'message' => 'Advertisement status updated']);
        }

        return $this->response->setJSON(['success' => false, 'message' => 'Advertisement not found']);
    }

    // SA30 - Toggle Brand Creation Feature
    public function toggleBrandCreation()
    {
        if (!session()->get('logged_in') || session()->get('user_type') !== 'super_admin') {
            return $this->response->setJSON(['success' => false, 'message' => 'Unauthorized']);
        }

        $db = \Config\Database::connect();
        $currentSetting = $db->table('system_settings')
                             ->where('setting_key', 'brand_creation_enabled')
                             ->get()
                             ->getRowArray();

        $newValue = $currentSetting ? !$currentSetting['setting_value'] : 0;

        if ($currentSetting) {
            $db->table('system_settings')
               ->where('setting_key', 'brand_creation_enabled')
               ->update(['setting_value' => $newValue]);
        } else {
            $db->table('system_settings')->insert([
                'setting_key' => 'brand_creation_enabled',
                'setting_value' => $newValue,
            ]);
        }

        return $this->response->setJSON([
            'success' => true,
            'message' => 'Brand creation ' . ($newValue ? 'enabled' : 'disabled'),
            'brand_creation_enabled' => $newValue,
        ]);
    }
}

