<?php

namespace App\Modules\Admin;

use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Auth;
use App\Facades\DBconfig;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;

class AdldapController extends BaseController
{
    /**
     *	The layout that should be used for responses.
     */
    protected $layout = 'layouts.master';

    /**
     * Render the ldap settings page.
     *
     * @return null
     */
    public function index()
    {
        $settings = DBconfig::get('ldap');
        
        // Convert integer values to booleans for frontend compatibility
        $booleanFields = ['enabled', 'real_primarygroup', 'use_ssl', 'use_tls', 'recursive_groups', 'sso'];
        foreach ($booleanFields as $field) {
            if (isset($settings[$field])) {
                $settings[$field] = (bool) $settings[$field];
            }
        }
        
        $this->layout->content = View::make('admin::settings.adldap.index', compact('settings'));
    }

    /**
     * Updates the settings.
     *
     * @return array
     */
    public function store(Request $request)
    {
        // Always store boolean fields (checkboxes) regardless of presence
        DBconfig::store('ldap.enabled', $request->boolean('enabled'));
        DBconfig::store('ldap.real_primarygroup', $request->boolean('real_primarygroup'));
        DBconfig::store('ldap.use_ssl', $request->boolean('use_ssl'));
        DBconfig::store('ldap.use_tls', $request->boolean('use_tls'));
        DBconfig::store('ldap.recursive_groups', $request->boolean('recursive_groups'));
        DBconfig::store('ldap.sso', $request->boolean('sso'));
        
        // Store text fields only if present
        if ($request->has('account_suffix')) {
            DBconfig::store('ldap.account_suffix', $request->input('account_suffix'));
        }
        if ($request->has('base_dn')) {
            DBconfig::store('ldap.base_dn', $request->input('base_dn'));
        }
        if ($request->has('domain_controllers')) {
            DBconfig::store('ldap.domain_controllers', $request->input('domain_controllers', []));
        }
        if ($request->has('admin_password')) {
            DBconfig::store('ldap.admin_password', $request->input('admin_password'));
        }
        if ($request->has('admin_username')) {
            DBconfig::store('ldap.admin_username', $request->input('admin_username'));
        }
        if ($request->has('ad_port')) {
            DBconfig::store('ldap.ad_port', $request->input('ad_port', 389));
        }
        //Clear the cache before the retrieval.
        DBconfig::clear();
        
        // Get the updated settings
        $result = DBconfig::get('ldap');
        
        // Convert integer values back to booleans for frontend checkbox compatibility
        $booleanFields = ['enabled', 'real_primarygroup', 'use_ssl', 'use_tls', 'recursive_groups', 'sso'];
        foreach ($booleanFields as $field) {
            if (isset($result[$field])) {
                $result[$field] = (bool) $result[$field];
            }
        }
        
        return $result;
    }

    /**
     * Test the given settings.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function testSettings(Request $request)
    {
        try {
            // Get the current settings from database and merge with form data
            $currentSettings = DBconfig::get('ldap', []);
            $testSettings = array_merge($currentSettings, $request->all());
            
            // Get test credentials
            $testUsername = $testSettings['admin_username'] ?? '';
            $testPassword = $testSettings['admin_password'] ?? '';
            
            // Validate required fields
            if (empty($testUsername) || empty($testPassword)) {
                return [
                    'success' => false, 
                    'message' => 'Ldap username and password are required for testing'
                ];
            }
            
            if (empty($testSettings['domain_controllers']) || empty($testSettings['account_suffix']) || empty($testSettings['base_dn'])) {
                return [
                    'success' => false, 
                    'message' => 'Domain controllers, account suffix, and base DN are required'
                ];
            }
            
            // Log the test attempt
            \Log::info('LDAP test initiated', [
                'username' => $testUsername,
                'domain_controllers' => $testSettings['domain_controllers'] ?? 'not set',
                'account_suffix' => $testSettings['account_suffix'] ?? 'not set',
                'base_dn' => $testSettings['base_dn'] ?? 'not set'
            ]);
            
            // Attempt authentication
            $authResult = \LDAP::auth($testUsername, $testPassword, $testSettings);
            
            if ($authResult === false) {
                return [
                    'success' => false,
                    'message' => 'LDAP connection failed. Please check your settings and credentials.'
                ];
            }
            
            return [
                'success' => true,
                'message' => 'LDAP connection successful! User authenticated: ' . ($authResult['name'] ?? $testUsername)
            ];
            
        } catch (\Exception $e) {
            \Log::error('LDAP test error', [
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            
            return [
                'success' => false,
                'message' => 'LDAP test failed: ' . $e->getMessage()
            ];
        }
    }
}
