<?php
class SettingsController {
    public function index(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requirePermission('settings.view');

        $tid = Auth::tenantId();
        $tenant = Auth::tenant();
        
        // Load settings from DB (key-value pairs)
        $stmt = db()->prepare("SELECT * FROM settings WHERE tenant_id=?");
        $stmt->execute([$tid]);
        $settingsRaw = $stmt->fetchAll();
        $settings = [];
        foreach ($settingsRaw as $s) { $settings[$s['setting_key']] = $s['setting_value']; }

        // Fetch locations for default dropdown
        $locStmt = db()->prepare("SELECT id, name FROM locations WHERE tenant_id=?");
        $locStmt->execute([$tid]);
        $locations = $locStmt->fetchAll();

        // Fetch customers for default dropdown
        $custStmt = db()->prepare("SELECT id, name FROM customers WHERE tenant_id=? AND is_active=1 ORDER BY name ASC");
        $custStmt->execute([$tid]);
        $customers = $custStmt->fetchAll();

        $pageTitle = 'Business Settings';
        ob_start();
        include APP_ROOT . '/views/tenant/settings/index.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }

    public function updateBusiness(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('settings.view');

        $tid = Auth::tenantId();
        
        // Validation
        $business_name = trim($_POST['business_name'] ?? '');
        $business_email = trim($_POST['business_email'] ?? '');
        $business_phone = trim($_POST['business_phone'] ?? '');
        $business_address = trim($_POST['business_address'] ?? '');
        
        if (empty($business_name)) {
            flash('error', 'Business name is required');
            redirect('settings');
            return;
        }
        
        if (empty($business_email)) {
            flash('error', 'Business email is required');
            redirect('settings');
            return;
        }
        
        if (!filter_var($business_email, FILTER_VALIDATE_EMAIL)) {
            flash('error', 'Please enter a valid email address');
            redirect('settings');
            return;
        }
        
        $data = [
            'business_name'    => Security::sanitize($business_name),
            'business_email'   => Security::sanitize($business_email),
            'business_phone'   => Security::sanitize($business_phone),
            'business_address' => Security::sanitize($business_address)
        ];

        // Handle logo upload
        if (!empty($_FILES['logo']['name'])) {
            $uploadDir = UPLOAD_PATH . "/{$tid}";
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
            
            // Validate file
            $allowedTypes = ['jpg', 'jpeg', 'png', 'webp'];
            $maxSize = 2 * 1024 * 1024; // 2MB
            
            if ($_FILES['logo']['error'] !== UPLOAD_ERR_OK) {
                flash('error', 'File upload failed');
                redirect('settings');
                return;
            }
            
            if ($_FILES['logo']['size'] > $maxSize) {
                flash('error', 'Logo file size must be less than 2MB');
                redirect('settings');
                return;
            }
            
            $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
            if (!in_array($ext, $allowedTypes)) {
                flash('error', 'Logo must be a JPG, PNG, or WebP file');
                redirect('settings');
                return;
            }
            
            // Validate file is actually an image
            $imageInfo = @getimagesize($_FILES['logo']['tmp_name']);
            if ($imageInfo === false) {
                flash('error', 'Invalid image file');
                redirect('settings');
                return;
            }
            
            // Check file size (max 2MB for logo)
            if ($_FILES['logo']['size'] > 2 * 1024 * 1024) {
                flash('error', 'Logo file must be less than 2MB');
                redirect('settings');
                return;
            }
            
            $filename = "logo_" . bin2hex(random_bytes(8)) . "." . $ext;
            if (move_uploaded_file($_FILES['logo']['tmp_name'], "{$uploadDir}/{$filename}")) {
                $data['logo'] = $filename;
            } else {
                flash('error', 'Failed to save logo file');
                redirect('settings');
                return;
            }
        }

        $updates = implode(',', array_map(fn($k) => "`$k`=?", array_keys($data)));
        db()->prepare("UPDATE tenants SET $updates WHERE id=?")->execute([...array_values($data), $tid]);

        // Refresh tenant data in session
        $updatedTenant = TenantModel::findById($tid);
        if ($updatedTenant) {
            $_SESSION['tenant'] = $updatedTenant;
        }

        flash('success', 'Business profile updated successfully');
        redirect('settings');
    }

    public function updatePreferences(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('settings.view');

        $tid = Auth::tenantId();
        $prefs = $_POST['prefs'] ?? [];
        
        // Validate preferences
        $validatedPrefs = [];
        $allowedKeys = [
            'sale_prefix', 'purchase_prefix', 'tax_rate', 'tax_enabled',
            'currency_symbol', 'low_stock_threshold', 'default_tax_group_id', 
            'allow_negative_stock', 'rounding', 'default_customer_id', 'default_location_id'
        ];
        
        foreach ($prefs as $key => $val) {
            if (!in_array($key, $allowedKeys)) {
                continue; // Skip invalid keys
            }
            
            $val = trim($val);
            
            // Specific validations
            switch ($key) {
                case 'sale_prefix':
                case 'purchase_prefix':
                    if (strlen($val) > 10) {
                        flash('error', 'Prefix must be 10 characters or less');
                        redirect('settings');
                        return;
                    }
                    break;
                    
                case 'tax_rate':
                    if (!is_numeric($val) || $val < 0 || $val > 100) {
                        flash('error', 'Tax rate must be between 0 and 100');
                        redirect('settings');
                        return;
                    }
                    $val = number_format((float)$val, 2);
                    break;
                    
                case 'currency_symbol':
                    if (strlen($val) > 5) {
                        flash('error', 'Currency symbol must be 5 characters or less');
                        redirect('settings');
                        return;
                    }
                    break;
                    
                case 'low_stock_threshold':
                    if (!is_numeric($val) || $val < 0 || $val > 9999) {
                        flash('error', 'Low stock threshold must be between 0 and 9999');
                        redirect('settings');
                        return;
                    }
                    $val = (int)$val;
                    break;
                case 'allow_negative_stock':
                    $val = $val ? 1 : 0;
                    break;
            }
            
            $validatedPrefs[$key] = $val;
        }

        db()->beginTransaction();
        try {
            foreach ($validatedPrefs as $key => $val) {
                $stmt = db()->prepare("INSERT INTO settings (tenant_id, setting_key, setting_value) VALUES (?,?,?) ON DUPLICATE KEY UPDATE setting_value=?");
                $stmt->execute([$tid, $key, $val, $val]);
            }
            db()->commit();
            clearSettingsCache($tid);
            flash('success', 'Preferences updated successfully');
        } catch (Exception $e) {
            db()->rollBack();
            flash('error', 'Failed to update preferences');
        }
        redirect('settings');
    }

    // Categories Management
    public function categories(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requirePermission('categories.manage');

        $categories = Category::getAllWithParentNames(Auth::tenantId());
        
        $pageTitle = 'Categories';
        ob_start();
        include APP_ROOT . '/views/tenant/settings/categories.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }

    public function storeCategory(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('categories.manage');

        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $parentId = (int)($_POST['parent_id'] ?? 0);

        if (empty($name)) {
            flash('error', 'Category name is required');
            redirect('settings/categories');
            return;
        }

        try {
            Category::create([
                'name' => $name,
                'description' => $description,
                'parent_id' => $parentId > 0 ? $parentId : null
            ]);
            flash('success', 'Category created successfully');
        } catch (Exception $e) {
            flash('error', 'Failed to create category');
        }
        
        redirect('settings/categories');
    }

    public function updateCategory(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('categories.manage');

        $id = (int)($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $parentId = (int)($_POST['parent_id'] ?? 0);

        if (empty($name)) {
            flash('error', 'Category name is required');
            redirect('settings/categories');
            return;
        }

        try {
            Category::update($id, [
                'name' => $name,
                'description' => $description,
                'parent_id' => $parentId > 0 ? $parentId : null
            ]);
            flash('success', 'Category updated successfully');
        } catch (Exception $e) {
            flash('error', 'Failed to update category');
        }
        
        redirect('settings/categories');
    }

    public function deleteCategory(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('categories.manage');

        $id = (int)($_POST['id'] ?? 0);

        try {
            if (Category::delete($id)) {
                flash('success', 'Category deleted successfully');
            } else {
                flash('error', 'Cannot delete category that contains products or subcategories');
            }
        } catch (Exception $e) {
            flash('error', 'Failed to delete category');
        }
        
        redirect('settings/categories');
    }

    // Units Management
    public function units(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requirePermission('units.manage');

        $units = Unit::all();
        
        $pageTitle = 'Units';
        ob_start();
        include APP_ROOT . '/views/tenant/settings/units.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }

    public function storeUnit(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('units.manage');

        $name = trim($_POST['name'] ?? '');
        $abbreviation = trim($_POST['abbreviation'] ?? '');
        $description = trim($_POST['description'] ?? '');

        if (empty($name)) {
            flash('error', 'Unit name is required');
            redirect('settings/units');
            return;
        }

        try {
            Unit::create([
                'name' => $name,
                'abbreviation' => $abbreviation,
                'description' => $description
            ]);
            flash('success', 'Unit created successfully');
        } catch (Exception $e) {
            flash('error', 'Failed to create unit');
        }
        
        redirect('settings/units');
    }

    public function updateUnit(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('units.manage');

        $id = (int)($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $abbreviation = trim($_POST['abbreviation'] ?? '');
        $description = trim($_POST['description'] ?? '');

        if (empty($name)) {
            flash('error', 'Unit name is required');
            redirect('settings/units');
            return;
        }

        try {
            Unit::update($id, [
                'name' => $name,
                'abbreviation' => $abbreviation,
                'description' => $description
            ]);
            flash('success', 'Unit updated successfully');
        } catch (Exception $e) {
            flash('error', 'Failed to update unit');
        }
        
        redirect('settings/units');
    }

    public function deleteUnit(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('units.manage');

        $id = (int)($_POST['id'] ?? 0);

        try {
            if (Unit::delete($id)) {
                flash('success', 'Unit deleted successfully');
            } else {
                flash('error', 'Cannot delete unit that is being used by products');
            }
        } catch (Exception $e) {
            flash('error', 'Failed to delete unit');
        }
        
        redirect('settings/units');
    }

    public function toggleUnitStatus(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('units.manage');

        $id = (int)($_POST['id'] ?? 0);

        try {
            Unit::toggleStatus($id);
            flash('success', 'Unit status updated successfully');
        } catch (Exception $e) {
            flash('error', 'Failed to update unit status');
        }
        
        redirect('settings/units');
    }

    // Brands Management
    public function brands(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requirePermission('categories.manage');

        $brands = Brand::all();
        
        $pageTitle = 'Brands';
        ob_start();
        include APP_ROOT . '/views/tenant/settings/brands.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }

    public function storeBrand(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('categories.manage');

        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');

        if (empty($name)) {
            flash('error', 'Brand name is required');
            redirect('settings/brands');
            return;
        }

        try {
            Brand::create([
                'name' => $name,
                'description' => $description
            ]);
            flash('success', 'Brand created successfully');
        } catch (Exception $e) {
            flash('error', 'Failed to create brand');
        }
        
        redirect('settings/brands');
    }

    public function updateBrand(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('categories.manage');

        $id = (int)($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');

        if (empty($name)) {
            flash('error', 'Brand name is required');
            redirect('settings/brands');
            return;
        }

        try {
            Brand::update($id, [
                'name' => $name,
                'description' => $description
            ]);
            flash('success', 'Brand updated successfully');
        } catch (Exception $e) {
            flash('error', 'Failed to update brand');
        }
        
        redirect('settings/brands');
    }

    public function deleteBrand(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('categories.manage');

        $id = (int)($_POST['id'] ?? 0);

        try {
            if (Brand::delete($id)) {
                flash('success', 'Brand deleted successfully');
            } else {
                flash('error', 'Cannot delete brand that is being used by products');
            }
        } catch (Exception $e) {
            flash('error', 'Failed to delete brand');
        }
        
        redirect('settings/brands');
    }

    // Batch/Expiry Management
    public function batchExpiry(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requirePermission('settings.view');

        $tid = Auth::tenantId();
        
        // Get products with batch tracking enabled
        $stmt = db()->prepare("
            SELECT p.*, COUNT(b.id) as batch_count 
            FROM products p 
            LEFT JOIN batches b ON p.id = b.product_id 
            WHERE p.tenant_id = ? AND p.batch_tracking = 1 
            GROUP BY p.id
            ORDER BY p.name
        ");
        $stmt->execute([$tid]);
        $batchProducts = $stmt->fetchAll();

        // Get expiring batches (within 30 days)
        $stmt = db()->prepare("
            SELECT b.*, p.name as product_name, p.sku
            FROM batches b
            JOIN products p ON b.product_id = p.id
            WHERE p.tenant_id = ? AND b.expiry_date <= DATE_ADD(CURDATE(), INTERVAL 30 DAY)
            ORDER BY b.expiry_date ASC
            LIMIT 50
        ");
        $stmt->execute([$tid]);
        $expiringBatches = $stmt->fetchAll();
        
        $pageTitle = 'Batch & Expiry Management';
        ob_start();
        include APP_ROOT . '/views/tenant/settings/batch-expiry.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }

    public function updateBatchTracking(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('settings.view');

        $productId = (int)($_POST['product_id'] ?? 0);
        $enable = (int)($_POST['enable_batch_tracking'] ?? 0);

        try {
            $stmt = db()->prepare("UPDATE products SET batch_tracking = ? WHERE id = ? AND tenant_id = ?");
            $stmt->execute([$enable, $productId, Auth::tenantId()]);
            
            $action = $enable ? 'enabled' : 'disabled';
            flash('success', "Batch tracking $action successfully");
        } catch (Exception $e) {
            flash('error', 'Failed to update batch tracking');
        }
        
        redirect('settings/batch-expiry');
    }

    public function deleteBatch(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('settings.view');

        $batchId = (int)($_POST['batch_id'] ?? 0);

        try {
            // Check if batch has stock
            $stmt = db()->prepare("SELECT SUM(quantity) as total_stock FROM stock WHERE batch_id = ?");
            $stmt->execute([$batchId]);
            $stock = $stmt->fetch();

            if ($stock && $stock['total_stock'] > 0) {
                flash('error', 'Cannot delete batch that contains stock');
            } else {
                $stmt = db()->prepare("DELETE FROM batches WHERE id = ?");
                $stmt->execute([$batchId]);
                flash('success', 'Batch deleted successfully');
            }
        } catch (Exception $e) {
            flash('error', 'Failed to delete batch');
        }
        
        redirect('settings/batch-expiry');
    }

    // Locations (Warehouses/Shops) Management
    public function locations(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requirePermission('settings.view');

        $locations = Location::withStockSummary();
        
        $pageTitle = 'Warehouses & Shops';
        ob_start();
        include APP_ROOT . '/views/tenant/settings/locations.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }

    public function storeLocation(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('settings.view');
        PlanGuard::enforce('locations');

        $name = trim($_POST['name'] ?? '');
        $code = trim($_POST['code'] ?? '');
        $type = trim($_POST['type'] ?? 'store');
        $address = trim($_POST['address'] ?? '');
        $phone = trim($_POST['phone'] ?? '');

        if (empty($name)) {
            flash('error', 'Location name is required');
            redirect('settings/locations');
            return;
        }

        if (empty($code)) {
            flash('error', 'Location code is required');
            redirect('settings/locations');
            return;
        }

        // Validate type
        if (!in_array($type, ['warehouse', 'store', 'outlet'])) {
            flash('error', 'Invalid location type');
            redirect('settings/locations');
            return;
        }

        try {
            Location::create([
                'name' => $name,
                'code' => strtoupper($code),
                'type' => $type,
                'address' => $address,
                'phone' => $phone
            ]);
            flash('success', 'Location created successfully');
        } catch (Exception $e) {
            flash('error', 'Failed to create location. Code may already exist.');
        }
        
        redirect('settings/locations');
    }

    public function updateLocation(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('settings.view');

        $id = (int)($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $code = trim($_POST['code'] ?? '');
        $type = trim($_POST['type'] ?? 'store');
        $address = trim($_POST['address'] ?? '');
        $phone = trim($_POST['phone'] ?? '');

        if (empty($name)) {
            flash('error', 'Location name is required');
            redirect('settings/locations');
            return;
        }

        if (empty($code)) {
            flash('error', 'Location code is required');
            redirect('settings/locations');
            return;
        }

        // Validate type
        if (!in_array($type, ['warehouse', 'store', 'outlet'])) {
            flash('error', 'Invalid location type');
            redirect('settings/locations');
            return;
        }

        try {
            Location::update($id, [
                'name' => $name,
                'code' => strtoupper($code),
                'type' => $type,
                'address' => $address,
                'phone' => $phone
            ]);
            flash('success', 'Location updated successfully');
        } catch (Exception $e) {
            flash('error', 'Failed to update location. Code may already exist.');
        }
        
        redirect('settings/locations');
    }

    public function deleteLocation(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('settings.view');

        $id = (int)($_POST['id'] ?? 0);

        try {
            // Check if location has stock
            $stmt = db()->prepare("SELECT COUNT(*) as stock_count FROM stock WHERE location_id = ?");
            $stmt->execute([$id]);
            $stock = $stmt->fetch();

            if ($stock && $stock['stock_count'] > 0) {
                flash('error', 'Cannot delete location that contains stock');
            } else {
                if (Location::delete($id)) {
                    flash('success', 'Location deleted successfully');
                } else {
                    flash('error', 'Failed to delete location');
                }
            }
        } catch (Exception $e) {
            flash('error', 'Failed to delete location');
        }
        
        redirect('settings/locations');
    }

    public function toggleLocationStatus(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('settings.view');

        $id = (int)($_POST['id'] ?? 0);

        try {
            $stmt = db()->prepare("UPDATE locations SET is_active = NOT is_active WHERE id = ? AND tenant_id = ?");
            $stmt->execute([$id, Auth::tenantId()]);
            flash('success', 'Location status updated successfully');
        } catch (Exception $e) {
            flash('error', 'Failed to update location status');
        }
        
        redirect('settings/locations');
    }

    public function setDefaultLocation(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('settings.view');

        $id = (int)($_POST['id'] ?? 0);

        try {
            db()->beginTransaction();

            // Remove default from all locations
            $stmt = db()->prepare("UPDATE locations SET is_default = 0 WHERE tenant_id = ?");
            $stmt->execute([Auth::tenantId()]);

            // Set new default
            $stmt = db()->prepare("UPDATE locations SET is_default = 1 WHERE id = ? AND tenant_id = ?");
            $stmt->execute([$id, Auth::tenantId()]);

            db()->commit();
            flash('success', 'Default location updated successfully');
        } catch (Exception $e) {
            db()->rollBack();
            flash('error', 'Failed to update default location');
        }

        redirect('settings/locations');
    }

    // Payment Methods Management
    public function paymentMethods(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Auth::requirePermission('settings.view');

        $tid = Auth::tenantId();

        // Load settings from DB
        $stmt = db()->prepare("SELECT * FROM settings WHERE tenant_id=?");
        $stmt->execute([$tid]);
        $settingsRaw = $stmt->fetchAll();
        $settings = [];
        foreach ($settingsRaw as $s) { $settings[$s['setting_key']] = $s['setting_value']; }

        $pageTitle = 'Payment Methods';
        ob_start();
        include APP_ROOT . '/views/tenant/settings/payment-methods.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }

    public function savePaymentMethods(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        Auth::requirePermission('settings.view');

        $tid = Auth::tenantId();
        $paymentMethods = $_POST['payment_methods'] ?? [];
        $methodLabels = $_POST['method_labels'] ?? [];
        $defaultPaymentMethod = $_POST['default_payment_method'] ?? 'cash';

        if (empty($paymentMethods)) {
            flash('error', 'At least one payment method must be enabled');
            redirect('settings/payment-methods');
            return;
        }

        if (!in_array($defaultPaymentMethod, $paymentMethods)) {
            flash('error', 'Default payment method must be one of the enabled methods');
            redirect('settings/payment-methods');
            return;
        }

        db()->beginTransaction();
        try {
            // Save payment methods array
            $stmt = db()->prepare("INSERT INTO settings (tenant_id, setting_key, setting_value) VALUES (?,?,?) ON DUPLICATE KEY UPDATE setting_value=?");
            $stmt->execute([$tid, 'payment_methods', json_encode($paymentMethods), json_encode($paymentMethods)]);

            // Save method labels
            $stmt = db()->prepare("INSERT INTO settings (tenant_id, setting_key, setting_value) VALUES (?,?,?) ON DUPLICATE KEY UPDATE setting_value=?");
            $stmt->execute([$tid, 'payment_method_labels', json_encode($methodLabels), json_encode($methodLabels)]);

            // Save default payment method
            $stmt = db()->prepare("INSERT INTO settings (tenant_id, setting_key, setting_value) VALUES (?,?,?) ON DUPLICATE KEY UPDATE setting_value=?");
            $stmt->execute([$tid, 'default_payment_method', $defaultPaymentMethod, $defaultPaymentMethod]);

            db()->commit();
            flash('success', 'Payment methods saved successfully');
        } catch (Exception $e) {
            db()->rollBack();
            flash('error', 'Failed to save payment methods');
        }

        redirect('settings/payment-methods');
    }

    /**
     * Factory Reset: Clears all transactional data for the current tenant.
     * Restricted to Admin role only as requested.
     */
    public function factoryReset(): void {
        Auth::requireLogin();
        Security::checkCsrf();
        
        // Strict requirement for 'admin' role only as per user request
        if (Auth::role() !== 'admin') {
            flash('error', 'Unauthorized access. Only system administrators can perform a reset.');
            redirect('settings');
            return;
        }

        $tid = Auth::tenantId();
        
        try {
            db()->beginTransaction();

            // List of tables to clear based on tenant_id
            $tables = [
                'sale_items', 'sales',
                'purchase_items', 'purchases',
                'stock_movements',
                'stock_adjustments',
                'stock_taking_items', 'stock_takings',
                'stock_transfer_items', 'stock_transfers',
                'stock',
                'payments',
                'customer_ledger',
                'supplier_ledger',
                'notifications',
                'audit_logs'
            ];

            // Verify table existence safely before deleting
            foreach ($tables as $table) {
                // Some tables use CASCADE, but we'll be explicit to ensure all data is wiped
                db()->prepare("DELETE FROM `$table` WHERE tenant_id = ?")->execute([$tid]);
            }

            // We can also reset custom sequential numbers if they are stored in settings
            // But currently the system uses random IDs/uniqid.

            db()->commit();
            flash('success', 'System reset successful. All transactional records have been wiped.');
        } catch (Exception $e) {
            db()->rollBack();
            flash('error', 'Reset failed: ' . $e->getMessage());
        }

        redirect('settings');
    }
}
