<?php

namespace App\Modules\Admin;

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

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

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $settings = $this->getSettings();

        return view('admin::settings.ews.index', compact('settings'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        if (request()->has('enabled')) {
            DBconfig::set('ews::config.enabled', request()->get('enabled', false));
        }

        if (request()->has('server')) {
            DBconfig::set('ews::config.server', request()->get('server'));
        }

        if (request()->has('username')) {
            DBconfig::set('ews::config.username', request()->get('username'));
        }

        if (request()->has('password')) {
            DBconfig::set('ews::config.password', request()->get('password'));
        }

        if (request()->has('version')) {
            DBconfig::set('ews::config.version', request()->get('version', 'Exchange2010_SP1'));
        }

        return Response::json(['success' => true, 'message' => 'EWS configuration updated']);
    }

    /**
     * Test EWS connection
     *
     * @return Response
     */
    public function testConnection()
    {
        try {
            // Test EWS connection logic here
            $result = ['success' => true, 'message' => 'Connection successful'];
        } catch (\Exception $e) {
            $result = ['success' => false, 'message' => 'Connection failed: ' . $e->getMessage()];
        }

        return Response::json($result);
    }

    /**
     * Retrieves all settings as an array.
     *
     * @return array
     */
    protected function getSettings()
    {
        $settings = DBconfig::get('ews::config');
        if (! isset($settings['version']) || ! $settings['version']) {
            $settings['version'] = 'Exchange2010_SP1';
        }
        
        // Ensure all expected keys exist with defaults
        $defaults = [
            'enabled' => false,
            'server' => '',
            'username' => '',
            'password' => '',
            'version' => 'Exchange2010_SP1'
        ];
        
        return array_merge($defaults, $settings ?: []);
    }
}
