<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\RmtoService;
use Illuminate\Support\Facades\Log;

class RMTOController extends Controller
{
    /**
     * Display the RMTO test panel
     */
    public function index()
    {
        // Get current settings
        $settings = [
            'username' => env('RMTO_USERNAME', ''),
            'environment' => env('RMTO_ENVIRONMENT', 'test'),
            'client_code' => env('RMTO_CLIENT_CODE', ''),
            'neshan_map_api_key' => env('NESHAN_MAP_API_KEY', 'web.6fe810e9e53c4730af91d1607c3bd5a1'),
        ];

        return view('admin.rmto.index', compact('settings'));
    }
    
    /**
     * Get RMTO Service instance
     */
    protected function getRMTOService()
    {
        return app(RmtoService::class);
    }

    /**
     * Get RMTO settings
     */
    public function getSettings()
    {
        return response()->json([
            'success' => true,
            'data' => [
                'username' => env('RMTO_USERNAME', ''),
                'password' => env('RMTO_PASSWORD') ? '••••••••' : '',
                'environment' => env('RMTO_ENVIRONMENT', 'test'),
                'client_code' => env('RMTO_CLIENT_CODE', ''),
                'version' => env('RMTO_VERSION', '7.6'),
                'neshan_map_api_key' => env('NESHAN_MAP_API_KEY', 'web.6fe810e9e53c4730af91d1607c3bd5a1'),
            ]
        ]);
    }

    /**
     * Update RMTO settings
     */
    public function updateSettings(Request $request)
    {
        $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
            'environment' => 'required|in:test,production',
            'client_code' => 'nullable|string',
            'neshan_map_api_key' => 'nullable|string',
        ]);

        try {
            $envPath = base_path('.env');
            $envContent = file_get_contents($envPath);

            // Update or add each setting
            $settings = [
                'RMTO_USERNAME' => $request->username,
                'RMTO_PASSWORD' => $request->password,
                'RMTO_ENVIRONMENT' => $request->environment,
                'RMTO_CLIENT_CODE' => $request->client_code ?? '',
                'RMTO_VERSION' => '7.6',
                'NESHAN_MAP_API_KEY' => $request->neshan_map_api_key ?: 'web.6fe810e9e53c4730af91d1607c3bd5a1',
            ];

            foreach ($settings as $key => $value) {
                if (preg_match("/^{$key}=.*/m", $envContent)) {
                    $envContent = preg_replace("/^{$key}=.*/m", "{$key}={$value}", $envContent);
                } else {
                    $envContent .= "\n{$key}={$value}";
                }
            }

            file_put_contents($envPath, $envContent);

            return response()->json([
                'success' => true,
                'message' => 'تنظیمات با موفقیت ذخیره شد'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در ذخیره تنظیمات: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Test RMTO connection - Direct SOAP call
     */
    public function testConnection()
    {
        try {
            // Direct SOAP call to test date service
            $username = config('rmto.username', 'test');
            $password = config('rmto.password', '123456');
            
            $soapRequest = '<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
   <soapenv:Header/>
   <soapenv:Body>
      <tem:GetRmtoCurrentDate>
         <tem:UserID>' . $username . '</tem:UserID>
         <tem:Password>' . $password . '</tem:Password>
      </tem:GetRmtoCurrentDate>
   </soapenv:Body>
</soapenv:Envelope>';

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://bar-test.rmto.ir/TRNServiceV03.svc');
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $soapRequest);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: text/xml; charset=utf-8',
                'SOAPAction: "http://tempuri.org/TRNServiceV03/GetRmtoCurrentDate"'
            ]);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_VERBOSE, true);

            $response = curl_exec($ch);
            Log::info('RMTO SOAP Raw Response', ['response' => $response]);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            $verbose_log = curl_getinfo($ch, CURLINFO_HEADER_OUT);
            curl_close($ch);

            Log::info('RMTO Test Connection - Direct SOAP', [
                'http_code' => $httpCode,
                'response_length' => strlen($response),
                'error' => $error,
            ]);

            if ($error) {
                return response()->json([
                    'success' => false,
                    'message' => 'خطا در CURL',
                    'error' => $error,
                    'http_code' => $httpCode,
                ], 502);
            }

            if ($httpCode !== 200) {
                return response()->json([
                    'success' => false,
                    'message' => 'خطا در پاسخ سرور RMTO',
                    'error' => 'HTTP Error: ' . $httpCode,
                    'response' => substr($response, 0, 500),
                    'http_code' => $httpCode,
                ], 502);
            }

            // Check if response contains success indicator
            if (stripos($response, 'IsSuccessful') !== false && 
                (stripos($response, 'true') !== false || stripos($response, 'True') !== false)) {
                return response()->json([
                    'success' => true,
                    'message' => '✅ اتصال به RMTO موفق است',
                    'data' => [
                        'status' => 'connected',
                        'server' => 'bar-test.rmto.ir',
                        'response_time' => 'OK'
                    ]
                ]);
            }
            
            return response()->json([
                'success' => false,
                'message' => 'خطا در پاسخ RMTO',
                'error' => 'No successful response',
                'response' => substr($response, 0, 500),
            ], 502);
            
        } catch (\Exception $e) {
            Log::error('RMTO Test Connection Error: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => 'خطا در تست اتصال',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Test bill of lading registration
     */
    public function testBillOfLading(Request $request)
    {
        try {
            $result = $this->getRMTOService()->insertBillOfLading($request->all());

            if (!$result) {
                return response()->json([
                    'success' => false,
                    'message' => 'خطا در ثبت بارنامه',
                ], 400);
            }
            
            return response()->json([
                'success' => true,
                'message' => 'بارنامه با موفقیت ثبت شد',
                'data' => $result
            ]);
        } catch (\Exception $e) {
            Log::error('RMTO Bill Registration Error: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'خطا در ثبت بارنامه: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get driver information
     */
    public function getDriverInfo(Request $request)
    {
        try {
            $searchType = $request->input('search_type', 'smart_card');
            
            if ($searchType === 'smart_card') {
                $result = $this->getRMTOService()->getDriverBySmartCardNo($request->card_number);
            } else {
                $result = $this->getRMTOService()->getDriverByNationalId($request->national_code);
            }

            if (!$result) {
                return response()->json([
                    'success' => false,
                    'message' => 'خطا در دریافت اطلاعات راننده',
                ], 400);
            }
            
            return response()->json([
                'success' => true,
                'data' => $result
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت اطلاعات راننده: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get freighter information
     */
    public function getFreighterInfo(Request $request)
    {
        try {
            $result = $this->getRMTOService()->getFreighterBySmartCardNo($request->card_number);

            if (!$result) {
                return response()->json([
                    'success' => false,
                    'message' => 'خطا در دریافت اطلاعات ناوگان',
                ], 400);
            }
            
            return response()->json([
                'success' => true,
                'data' => $result
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت اطلاعات ناوگان: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Send OTP to driver
     */
    public function sendOTP(Request $request)
    {
        try {
            $result = $this->getRMTOService()->sendOTP($request->mobile);
            
            return response()->json([
                'success' => (bool) $result,
                'message' => $result ? 'کد تایید ارسال شد' : 'خطا در ارسال OTP',
                'data' => $result
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در ارسال OTP: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get RMTO current date
     */
    public function getCurrentDate()
    {
        try {
            $result = $this->getRMTOService()->getCurrentDate();

            if (!$result) {
                return response()->json([
                    'success' => false,
                    'message' => 'خطا در دریافت تاریخ',
                ], 400);
            }
            
            return response()->json([
                'success' => true,
                'date' => $result,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت تاریخ: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Inquiry real person by national code
     */
    public function inquiryRealPerson(Request $request)
    {
        try {
            $result = $this->getRMTOService()->inquiryLegalPerson($request->national_code);
            
            return response()->json([
                'success' => (bool) $result,
                'data' => $result
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در استعلام: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Inquiry postal code
     */
    public function inquiryPostalCode(Request $request)
    {
        try {
            $result = $this->getRMTOService()->inquiryPostalCode($request->postal_code);
            
            return response()->json([
                'success' => (bool) $result,
                'data' => $result
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در استعلام: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * ===========================================
     * MOCK ENDPOINTS FOR TESTING/DEMO
     * ===========================================
     * These endpoints return sample data for testing
     * the admin panel without needing RMTO server connectivity
     */

    /**
     * Mock getCurrentDate endpoint
     */
    public function mockGetCurrentDate()
    {
        return response()->json([
            'success' => true,
            'date' => '1404/02/05 14:35:22',
            'message' => 'داده‌های نمونه برای تست'
        ]);
    }

    /**
     * Mock inquiry legal person
     */
    public function mockInquiryLegalPerson(Request $request)
    {
        $mockData = [
            '10320685829' => [
                'name' => 'فولاد بوتیای ایرانیان',
                'last_name' => '',
                'is_successful' => 'true',
                'error_desc' => '',
                'full_address' => 'تهران - خیابان انقلاب - کوچه اول'
            ],
            '10320489932' => [
                'name' => 'احیا استیل فولاد',
                'last_name' => '',
                'is_successful' => 'true',
                'error_desc' => '',
                'full_address' => 'لار - خیابان فسن - پلاک ۲۸۵'
            ],
        ];

        $code = $request->national_code;
        $result = $mockData[$code] ?? null;

        if ($result) {
            return response()->json([
                'success' => true,
                'data' => $result,
                'message' => 'داده‌های نمونه برای تست'
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => 'اطلاعات پیدا نشد. برای تست از یکی از کدهای نمونه استفاده کنید: 10320685829, 10320489932'
        ]);
    }

    /**
     * Mock get driver info
     */
    public function mockGetDriverInfo(Request $request)
    {
        $mockData = [
            'card' => [
                '1234567' => [
                    'name' => 'علی',
                    'last_name' => 'احمدی',
                    'national_code' => '0012345678',
                    'license_number' => 'DL1234567',
                    'is_successful' => 'true',
                ]
            ],
            'national_id' => [
                '0012345678' => [
                    'name' => 'علی',
                    'last_name' => 'احمدی',
                    'national_code' => '0012345678',
                    'license_number' => 'DL1234567',
                    'is_successful' => 'true',
                ]
            ]
        ];

        $type = $request->input('type', 'card');
        $value = $request->input('value');
        $result = $mockData[$type][$value] ?? null;

        if ($result) {
            return response()->json([
                'success' => true,
                'data' => $result,
                'message' => 'داده‌های نمونه برای تست'
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => 'برای تست از شماره کارت یا کد ملی نمونه استفاده کنید'
        ]);
    }

    /**
     * Mock inquiry price
     */
    public function mockInquiryPrice(Request $request)
    {
        return response()->json([
            'success' => true,
            'data' => [
                'base_price' => 5000000,
                'company_commission' => 500000,
                'total_price' => 5500000,
                'currency' => 'ریال',
            ],
            'message' => 'داده‌های نمونه برای تست'
        ]);
    }
}
