//+------------------------------------------------------------------+
//|                                               UE_Diagnostic.mq5 |
//|                                              Ultimate Extractor |
//|                                    https://ultimateextractor.com |
//+------------------------------------------------------------------+
#property copyright "Ultimate Extractor"
#property link      "https://ultimateextractor.com"
#property version   "1.01"
#property script_show_inputs

input string ApiKey = "";  // Your API Key (optional - for full test)

//+------------------------------------------------------------------+
//| Script program start function                                     |
//+------------------------------------------------------------------+
void OnStart()
{
   Print("=======================================================");
   Print("   ULTIMATE EXTRACTOR - CONNECTION DIAGNOSTIC");
   Print("=======================================================");
   Print("");

   // 1. Check Terminal Info
   Print("--- TERMINAL INFO ---");
   Print("MT5 Build: ", TerminalInfoInteger(TERMINAL_BUILD));
   Print("Terminal Path: ", TerminalInfoString(TERMINAL_PATH));
   Print("Trade Allowed: ", TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) ? "YES" : "NO <-- PROBLEM!");
   Print("DLLs Allowed: ", TerminalInfoInteger(TERMINAL_DLLS_ALLOWED) ? "YES" : "NO");
   Print("Connected: ", TerminalInfoInteger(TERMINAL_CONNECTED) ? "YES" : "NO");
   Print("");

   // 2. Check MQL permissions
   Print("--- MQL PERMISSIONS ---");
   Print("MQL Trade Allowed: ", MQLInfoInteger(MQL_TRADE_ALLOWED) ? "YES" : "NO");
   Print("MQL Signals Allowed: ", MQLInfoInteger(MQL_SIGNALS_ALLOWED) ? "YES" : "NO");
   Print("");

   // 3. Test basic internet connectivity
   Print("--- CONNECTIVITY TESTS ---");

   // Test 1: httpbin.org (known working test endpoint)
   Print("");
   Print("Test 1: httpbin.org (external test server)...");
   TestWebRequest("https://httpbin.org/get", "httpbin.org");

   // Test 2: Ultimate Extractor health check
   Print("");
   Print("Test 2: ultimateextractor.com (our server)...");
   TestWebRequest("https://ultimateextractor.com/api/health", "Ultimate Extractor");

   // Test 3: If API key provided, test actual sync endpoint
   if(StringLen(ApiKey) > 10)
   {
      Print("");
      Print("Test 3: API Key validation...");
      TestApiKey(ApiKey);
   }
   else
   {
      Print("");
      Print("Test 3: Skipped (no API key provided)");
   }

   Print("");
   Print("=======================================================");
   Print("   DIAGNOSTIC COMPLETE - Check results above");
   Print("=======================================================");
   Print("");
   Print("If you see 'Error 1001' or 'Error 4060' above:");
   Print("1. Go to Tools -> Options -> Expert Advisors");
   Print("2. Check 'Allow WebRequest for listed URL'");
   Print("3. Add: https://ultimateextractor.com");
   Print("4. Add: https://httpbin.org (for testing)");
   Print("5. Click OK and RESTART MT5 completely");
   Print("");
}

//+------------------------------------------------------------------+
//| Test a WebRequest to a URL                                        |
//+------------------------------------------------------------------+
void TestWebRequest(string url, string name)
{
   char post[], result[];
   string headers;

   ResetLastError();

   int res = WebRequest(
      "GET",
      url,
      "",
      5000,
      post,
      result,
      headers
   );

   int error = GetLastError();

   if(res == -1)
   {
      Print("   *** ", name, ": FAILED ***");
      Print("   Error Code: ", error);

      switch(error)
      {
         case 1001:
            Print("   Reason: ERR_INTERNAL_ERROR - No connection / Request blocked");
            Print("   Fix: This usually means MT5 cannot make outbound connections.");
            Print("         - Check if VPS/firewall is blocking MT5 network access");
            Print("         - Try running MT5 as Administrator");
            Print("         - Verify URLs are in allowed list and restart MT5");
            break;
         case 4014:
            Print("   Reason: WebRequest not allowed!");
            Print("   Fix: Enable 'Allow WebRequest' in Options -> Expert Advisors");
            break;
         case 4060:
            Print("   Reason: URL not in allowed list!");
            Print("   Fix: Add URL to Tools -> Options -> Expert Advisors");
            break;
         case 5200:
            Print("   Reason: Invalid URL format");
            Print("   Fix: Check the URL is correct");
            break;
         case 5201:
            Print("   Reason: Failed to connect to server");
            Print("   Fix: Check internet connection or server is online");
            break;
         case 5202:
            Print("   Reason: Timeout waiting for response");
            Print("   Fix: Server may be slow or unreachable, try again");
            break;
         case 5203:
            Print("   Reason: Connection failed / timeout");
            Print("   Fix: Check internet connection or firewall");
            break;
         default:
            Print("   Reason: Unknown error (", error, ")");
            Print("   Fix: Search MT5 documentation for error code ", error);
            break;
      }
   }
   else if(res >= 200 && res < 300)
   {
      Print("   ", name, ": SUCCESS (HTTP ", res, ")");
      Print("   Response size: ", ArraySize(result), " bytes");

      if(ArraySize(result) > 0 && ArraySize(result) < 500)
      {
         string response = CharArrayToString(result);
         Print("   Response: ", StringSubstr(response, 0, 200));
      }
   }
   else
   {
      Print("   ", name, ": WARNING - Unexpected HTTP ", res);
      Print("   The server responded but with an error status.");

      if(ArraySize(result) > 0)
      {
         string response = CharArrayToString(result);
         Print("   Response: ", StringSubstr(response, 0, 300));
      }
   }
}

//+------------------------------------------------------------------+
//| Test API Key with actual endpoint                                  |
//+------------------------------------------------------------------+
void TestApiKey(string apiKey)
{
   string url = "https://ultimateextractor.com/api/sync";

   // Build minimal test payload
   string jsonPayload = "{\"api_key\":\"" + apiKey + "\",\"account\":{\"login\":0,\"balance\":0,\"equity\":0,\"profit\":0,\"margin_free\":0,\"server\":\"\",\"company\":\"\",\"currency\":\"\"},\"deals\":[],\"version\":\"Diagnostic\"}";

   char post[], result[];
   string headers = "Content-Type: application/json\r\n";

   ArrayResize(post, StringToCharArray(jsonPayload, post, 0, WHOLE_ARRAY, CP_UTF8) - 1);

   ResetLastError();

   int res = WebRequest(
      "POST",
      url,
      headers,
      10000,
      post,
      result,
      headers
   );

   int error = GetLastError();

   if(res == -1)
   {
      Print("   API Test: FAILED (Error ", error, ")");
   }
   else
   {
      Print("   API Test: Response received (HTTP ", res, ")");

      if(ArraySize(result) > 0)
      {
         string response = CharArrayToString(result);
         Print("   Response: ", response);

         if(StringFind(response, "success") >= 0 || res == 200)
            Print("   Status: API Key is VALID and working!");
         else if(StringFind(response, "Invalid API key") >= 0)
            Print("   Status: API Key is INVALID - check your key");
         else if(StringFind(response, "No linked account") >= 0)
            Print("   Status: API Key valid but no account linked yet");
      }
   }
}
//+------------------------------------------------------------------+
