<?php

namespace App\Modules\Admin;

use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;

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

    /**
     * Display the API keys management page.
     *
     * @return void
     */
    public function index()
    {
        // Get current 3CX API key from database settings or config
        $threecxApiKey = $this->getThreeCXApiKey();
        
        $this->layout->content = View::make('admin::settings.api-keys.index', [
            'threecx_api_key' => $threecxApiKey
        ]);
    }

    /**
     * Generate a new 3CX API key.
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function generate(Request $request)
    {
        try {
            // Generate a new random API key
            $newApiKey = 'threecx_' . Str::random(32);
            
            // Store in database or config - using a simple approach with database
            $this->saveThreeCXApiKey($newApiKey);
            
            return Redirect::route('admin.settings.api-keys.index')
                ->with('message', 'New 3CX API key generated successfully: ' . $newApiKey);
                
        } catch (\Exception $e) {
            return Redirect::route('admin.settings.api-keys.index')
                ->with('error', 'Failed to generate API key: ' . $e->getMessage());
        }
    }

    /**
     * Regenerate the 3CX API key.
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function regenerate(Request $request)
    {
        return $this->generate($request);
    }

    /**
     * Generate and download 3CX CRM Integration XML file.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function downloadXml(Request $request)
    {
        try {
            $apiKey = $this->getThreeCXApiKey();
            
            if (!$apiKey) {
                return Redirect::route('admin.settings.api-keys.index')
                    ->with('error', 'Please generate an API key first before downloading the XML configuration.');
            }

            $baseUrl = url('/');
            
            $xmlContent = $this->generateThreeCXXml($baseUrl, $apiKey);
            
            return response($xmlContent)
                ->header('Content-Type', 'application/xml')
                ->header('Content-Disposition', 'attachment; filename="seraph-3cx-integration.xml"');
                
        } catch (\Exception $e) {
            return Redirect::route('admin.settings.api-keys.index')
                ->with('error', 'Failed to generate XML: ' . $e->getMessage());
        }
    }

    /**
     * Get the current 3CX API key.
     *
     * @return string|null
     */
    private function getThreeCXApiKey()
    {
        // Check if we have a settings table or use a simple config approach
        try {
            // Try to get from a simple key-value settings approach
            $setting = DB::table('settings')->where('key', 'threecx_api_key')->first();
            return $setting ? $setting->value : null;
        } catch (\Exception $e) {
            // If settings table doesn't exist, create a simple one or use file-based storage
            return null;
        }
    }

    /**
     * Save the 3CX API key.
     *
     * @param string $apiKey
     * @return void
     */
    private function saveThreeCXApiKey($apiKey)
    {
        try {
            // First, check what columns exist in the settings table
            $columns = DB::select("SHOW COLUMNS FROM settings");
            $columnNames = array_column($columns, 'Field');
            
            $hasTimestamps = in_array('created_at', $columnNames) && in_array('updated_at', $columnNames);
            
            // Check if the record exists
            $exists = DB::table('settings')->where('key', 'threecx_api_key')->exists();
            
            if ($exists) {
                // Update existing record
                if ($hasTimestamps) {
                    DB::table('settings')->where('key', 'threecx_api_key')->update([
                        'value' => $apiKey,
                        'updated_at' => DB::raw('NOW()')
                    ]);
                } else {
                    DB::table('settings')->where('key', 'threecx_api_key')->update([
                        'value' => $apiKey
                    ]);
                }
            } else {
                // Insert new record
                if ($hasTimestamps) {
                    DB::table('settings')->insert([
                        'key' => 'threecx_api_key',
                        'value' => $apiKey,
                        'created_at' => DB::raw('NOW()'),
                        'updated_at' => DB::raw('NOW()')
                    ]);
                } else {
                    DB::table('settings')->insert([
                        'key' => 'threecx_api_key',
                        'value' => $apiKey
                    ]);
                }
            }
        } catch (\Exception $e) {
            // If settings table doesn't exist, create it with proper structure including timestamps
            try {
                DB::statement('CREATE TABLE IF NOT EXISTS settings (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    `key` VARCHAR(255) NOT NULL UNIQUE,
                    value TEXT,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
                )');
                
                // Insert the record with timestamps
                DB::table('settings')->insert([
                    'key' => 'threecx_api_key',
                    'value' => $apiKey,
                    'created_at' => DB::raw('NOW()'),
                    'updated_at' => DB::raw('NOW()')
                ]);
            } catch (\Exception $createException) {
                // If that fails, try creating without timestamps and add them
                try {
                    // Create basic table first
                    DB::statement('CREATE TABLE IF NOT EXISTS settings (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        `key` VARCHAR(255) NOT NULL UNIQUE,
                        value TEXT
                    )');
                    
                    // Try to add timestamp columns if they don't exist
                    try {
                        DB::statement('ALTER TABLE settings ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP');
                        DB::statement('ALTER TABLE settings ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP');
                    } catch (\Exception $alterException) {
                        // Columns might already exist, that's okay
                    }
                    
                    // Insert the record
                    DB::table('settings')->insert([
                        'key' => 'threecx_api_key',
                        'value' => $apiKey
                    ]);
                } catch (\Exception $finalException) {
                    throw new \Exception('Failed to create settings table or save API key: ' . $finalException->getMessage());
                }
            }
        }
    }

    /**
     * Generate the 3CX CRM Integration XML content.
     *
     * @param string $baseUrl
     * @param string $apiKey
     * @return string
     */
    private function generateThreeCXXml($baseUrl, $apiKey)
    {
        $xml = '<?xml version="1.0"?>
<Crm xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Country="GB" Name="Seraph" Version="1" SupportsEmojis="true">
  <Number Prefix="AsIs" MaxLength="20" />
  <Connection MaxConcurrentRequests="5" />
  <Parameters>
    <Parameter Name="BaseUrl" Type="String" Parent="General Configuration" Editor="String" Title="Base URL:" Default="https://your-seraph-url.com" />
    <Parameter Name="ApiKey" Type="String" Parent="General Configuration" Editor="String" Title="API Key:" Default="YOUR_API_KEY_HERE" />
  </Parameters>
  <Authentication Type="No" />
  <Scenarios>
    <Scenario Id="" Type="REST">
      <Request Url="[BaseUrl]/search.php?number=[Number]&amp;api_key=[ApiKey]" MessagePasses="0" RequestEncoding="UrlEncoded" RequestType="Get" ResponseType="Json" />
      <Rules>
        <Rule Type="Any">id</Rule>
      </Rules>
      <Variables>
        <Variable Name="ContactID" Path="id">
          <Filter />
        </Variable>
        <Variable Name="FirstName" Path="firstname">
          <Filter />
        </Variable>
        <Variable Name="LastName" Path="lastname">
          <Filter />
        </Variable>
        <Variable Name="CompanyName" Path="company">
          <Filter />
        </Variable>
        <Variable Name="Email" Path="email">
          <Filter />
        </Variable>
        <Variable Name="PhoneBusiness" Path="phone">
          <Filter />
        </Variable>
        <Variable Name="PhoneMobile" Path="number">
          <Filter />
        </Variable>
        <Variable Name="ContactUrl" Path="url">
          <Filter />
        </Variable>
      </Variables>
      <Outputs AllowEmpty="false">
        <Output Type="ContactID" Passes="0" Value="[ContactID]" />
        <Output Type="FirstName" Passes="0" Value="[FirstName]" />
        <Output Type="LastName" Passes="0" Value="[LastName]" />
        <Output Type="CompanyName" Passes="0" Value="[CompanyName]" />
        <Output Type="Email" Passes="0" Value="[Email]" />
        <Output Type="PhoneBusiness" Passes="0" Value="[PhoneBusiness]" />
        <Output Type="PhoneMobile2" Passes="0" Value="[PhoneMobile2]" />
        <Output Type="ContactUrl" Passes="0" Value="[ContactUrl]" />
        <Output Type="EntityId" Passes="0" Value="[ContactID]" />
        <Output Type="EntityType" Passes="0" Value="Contacts" />
      </Outputs>
    </Scenario>
  </Scenarios>
</Crm>';

        return $xml;
    }
}