<?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 $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        // 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 $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $db = \Config\Database::connect();
        $name = $this->request->getPost('name') ?: $this->request->getPost('type_name');
        $data = [
            'type_name' => $name,
            'category' => $this->request->getPost('category') ?: '',
            'created_at' => date('Y-m-d H:i:s'),
        ];

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

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

    public function removeListingType($id)
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

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

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

    public function removeProductType($id)
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

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

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

    public function removeCategory($id)
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

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

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

    public function removeSubCategory($id)
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

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

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

    // Edit endpoints for taxonomy items
    public function updateListingType($id)
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

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

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

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

    public function updateProductType($id)
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

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

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

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

    public function updateCategory($id)
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

        $db = \Config\Database::connect();
        $fields = $db->getFieldNames('categories');

        $postName = $this->request->getPost('category_name');
        $productTypeId = $this->request->getPost('product_type_id') ?: null;

        $data = [];
        if (in_array('name', $fields)) {
            $data['name'] = $postName;
        } elseif (in_array('category_name', $fields)) {
            $data['category_name'] = $postName;
        }

        if (in_array('product_type_id', $fields)) {
            $data['product_type_id'] = $productTypeId ? (int)$productTypeId : null;
        } elseif (in_array('parent_id', $fields)) {
            $data['parent_id'] = $productTypeId ? (int)$productTypeId : null;
        }

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

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

    public function updateSubCategory($id)
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

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

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

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

    // SA5 - Toggle Admin Approval Requirement
    public function toggleApprovalRequired()
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $db = \Config\Database::connect();
        // Be tolerant to older/newer migrations: detect available columns and map accordingly.
        $fields = [];
        try {
            $fields = $db->getFieldNames('categories');
        } catch (\Exception $e) {
            // table may not exist or other DB error
        }

        $postName = $this->request->getPost('category_name');
        $productTypeId = $this->request->getPost('product_type_id') ?: null;

        $data = [];
        if (in_array('name', $fields)) {
            $data['name'] = $postName;
            if (in_array('parent_id', $fields) && $productTypeId) {
                $data['parent_id'] = (int)$productTypeId;
            }
            if (in_array('category_type', $fields)) {
                $data['category_type'] = $this->request->getPost('category_type') ?: 'category';
            }
            if (in_array('slug', $fields)) {
                $data['slug'] = '';
            }
        } elseif (in_array('category_name', $fields)) {
            // older schema
            $data['category_name'] = $postName;
            if (in_array('product_type_id', $fields) && $productTypeId) {
                $data['product_type_id'] = (int)$productTypeId;
            }
            if (in_array('category_type', $fields)) {
                $data['category_type'] = $this->request->getPost('category_type') ?: 'product';
            }
            if (in_array('applies_to', $fields)) {
                $data['applies_to'] = $this->request->getPost('applies_to') ?: 'all';
            }
        } else {
            // fallback: attempt to insert minimal set
            $data['category_name'] = $postName;
        }

        // add timestamp if column present
        if (in_array('created_at', $fields)) {
            $data['created_at'] = date('Y-m-d H:i:s');
        }

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

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

    // SA27 - Consolidated Taxonomy UI for Listing/Product/Category/Sub-category
    public function manageTaxonomy()
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

        $db = \Config\Database::connect();

        // Listing types (may already exist)
        $listingTypes = [];
        try {
            $listingTypes = $db->table('listing_types')->get()->getResultArray();
        } catch (\Exception $e) {
            // table may not exist yet
        }

        // Product types
        $productTypes = [];
        try {
            $productTypes = $db->table('product_types')->get()->getResultArray();
        } catch (\Exception $e) {
        }

        // Categories (existing table)
        $categories = [];
        try {
            $categories = $db->table('categories')->get()->getResultArray();
        } catch (\Exception $e) {
        }

        // Sub-categories
        $subCategories = [];
        try {
            $subCategories = $db->table('sub_categories')->get()->getResultArray();
        } catch (\Exception $e) {
        }

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

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

    // AJAX: Get product types by listing type
    public function getProductTypes($listingTypeId = 0)
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

        $db = \Config\Database::connect();
        try {
            $rows = $db->table('product_types')->where('listing_type_id', (int)$listingTypeId)->get()->getResultArray();
            return $this->response->setJSON(['success' => true, 'data' => $rows]);
        } catch (\Exception $e) {
            return $this->response->setJSON(['success' => false, 'data' => []]);
        }
    }

    // AJAX: Get categories by product type
    public function getCategoriesByProductType($productTypeId = 0)
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

        $db = \Config\Database::connect();
        try {
            $rows = [];
            $fields = $db->getFieldNames('categories');
            if ($productTypeId && in_array('parent_id', $fields)) {
                $rows = $db->table('categories')->where('parent_id', (int)$productTypeId)->get()->getResultArray();
            } elseif ($productTypeId && in_array('product_type_id', $fields)) {
                $rows = $db->table('categories')->where('product_type_id', (int)$productTypeId)->get()->getResultArray();
            } else {
                $rows = $db->table('categories')->get()->getResultArray();
            }
            return $this->response->setJSON(['success' => true, 'data' => $rows]);
        } catch (\Exception $e) {
            return $this->response->setJSON(['success' => false, 'data' => []]);
        }
    }

    // AJAX: Get sub-categories by category
    public function getSubCategories($categoryId = 0)
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

        $db = \Config\Database::connect();
        try {
            $rows = $db->table('sub_categories')->where('category_id', (int)$categoryId)->get()->getResultArray();
            return $this->response->setJSON(['success' => true, 'data' => $rows]);
        } catch (\Exception $e) {
            return $this->response->setJSON(['success' => false, 'data' => []]);
        }
    }

    // Add product type (linked to listing type)
    public function addProductType()
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

        $db = \Config\Database::connect();
        $data = [
            'listing_type_id' => (int)$this->request->getPost('listing_type_id'),
            'name' => $this->request->getPost('name'),
            'created_at' => date('Y-m-d H:i:s'),
        ];

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

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

    // Add sub-category (linked to category)
    public function addSubCategory()
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

        $db = \Config\Database::connect();
        $data = [
            'category_id' => (int)$this->request->getPost('category_id'),
            'name' => $this->request->getPost('name'),
            'created_at' => date('Y-m-d H:i:s'),
        ];

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

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

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

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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 ($check = $this->checkSuperAdminAccess()) return $check;

        $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,
        ]);
    }

    // SUBSCRIPTION MANAGEMENT: Manage dynamic subscription pricing (IMPLEMENTED)
    public function manageSubscriptionLimits()
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

        $db = \Config\Database::connect();
        $subscriptionTiers = ['free', 'basic', 'pro', 'enterprise'];
        
        $data = [
            'user' => $this->userModel->find(session()->get('user_id')),
            'tiers' => $subscriptionTiers,
            'current_limits' => [], // Will be populated from helper
        ];

        // Get current limits from helper
        helper('price_calculator');
        foreach ($subscriptionTiers as $tier) {
            $data['current_limits'][$tier] = getSubscriptionLimits($tier);
        }

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

    public function updateSubscriptionLimit()
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

        $tier = $this->request->getPost('tier');
        $maxProducts = $this->request->getPost('max_products');
        $monthlyPrice = $this->request->getPost('monthly_price');
        $yearlyPrice = $this->request->getPost('yearly_price');

        $db = \Config\Database::connect();
        
        // Check if setting exists
        $existing = $db->table('subscription_tier_settings')
                       ->where('tier', $tier)
                       ->get()
                       ->getRowArray();

        $data = [
            'tier' => $tier,
            'max_products' => $maxProducts,
            'monthly_price' => $monthlyPrice,
            'yearly_price' => $yearlyPrice,
            'updated_at' => date('Y-m-d H:i:s'),
        ];

        if ($existing) {
            $db->table('subscription_tier_settings')
               ->where('tier', $tier)
               ->update($data);
        } else {
            $data['created_at'] = date('Y-m-d H:i:s');
            $db->table('subscription_tier_settings')->insert($data);
        }

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

    // POSTING LIMITS: Manage posting limits (IMPLEMENTED)
    public function managePostingLimits()
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

        $db = \Config\Database::connect();
        $postingLimits = $db->table('posting_limits')
                            ->orderBy('subscription_tier', 'ASC')
                            ->orderBy('limit_type', 'ASC')
                            ->get()
                            ->getResultArray();

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

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

    public function updatePostingLimit($limitId)
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

        $db = \Config\Database::connect();
        $data = [
            'max_posts' => $this->request->getPost('max_posts'),
            'charge_per_extra_post' => $this->request->getPost('charge_per_extra_post'),
            'updated_at' => date('Y-m-d H:i:s'),
        ];

        $db->table('posting_limits')
           ->where('id', $limitId)
           ->update($data);

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

    public function addPostingLimit()
    {
        if ($check = $this->checkSuperAdminAccess()) return $check;

        $db = \Config\Database::connect();
        $data = [
            'limit_type' => $this->request->getPost('limit_type'),
            'subscription_tier' => $this->request->getPost('subscription_tier'),
            'max_posts' => $this->request->getPost('max_posts'),
            'charge_per_extra_post' => $this->request->getPost('charge_per_extra_post'),
            'created_at' => date('Y-m-d H:i:s'),
        ];

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

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