/*
 * wifi_portal.c
 *
 *  Created on: 09/04/2026
 *      Author: carec
 */


#include "wifi_portal.h"
#include "esp_at.h"
#include "http_pages.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

static char saved_ssid[33];
static char saved_pass[65];

static void url_decode(char *dst, const char *src, int maxlen)
{
    int i = 0;
    while (*src && i < (maxlen - 1)) {
        if (*src == '+') {
            dst[i++] = ' ';
            src++;
        } else if (*src == '%' && src[1] && src[2]) {
            char hex[3] = {src[1], src[2], 0};
            dst[i++] = (char)strtol(hex, NULL, 16);
            src += 3;
        } else {
            dst[i++] = *src++;
        }
    }
    dst[i] = 0;
}

static int get_query_param(const char *req, const char *name, char *out, int outlen)
{
    const char *q = strchr(req, '?');
    if (!q) return 0;

    char key[32];
    snprintf(key, sizeof(key), "%s=", name);

    const char *p = strstr(q, key);
    if (!p) return 0;

    p += strlen(key);

    const char *end = strchr(p, '&');
    int len = end ? (end - p) : strcspn(p, " ");

    char tmp[128];
    if (len >= (int)sizeof(tmp)) len = sizeof(tmp) - 1;

    memcpy(tmp, p, len);
    tmp[len] = 0;

    url_decode(out, tmp, outlen);
    return 1;
}

static void save_credentials(const char *ssid, const char *pass)
{
    strncpy(saved_ssid, ssid, sizeof(saved_ssid) - 1);
    strncpy(saved_pass, pass, sizeof(saved_pass) - 1);

    // aqui metes EEPROM / FLASH / NVS emulador / o que quiseres
    // por agora fica em RAM
}

void WIFI_PORTAL_Init(void)
{
    saved_ssid[0] = 0;
    saved_pass[0] = 0;
}

void WIFI_PORTAL_HandleHttp(int link_id, const char *req)
{
    if (strncmp(req, "GET / ", 6) == 0) {
        ESP_SendLinkData(link_id, HTTP_Page_Index());
        ESP_CloseLink(link_id);
        return;
    }

    if (strncmp(req, "GET /save?", 10) == 0) {
        char ssid[33] = {0};
        char pass[65] = {0};

        get_query_param(req, "ssid", ssid, sizeof(ssid));
        get_query_param(req, "pass", pass, sizeof(pass));

        if (ssid[0]) {
            save_credentials(ssid, pass);
        }

        ESP_SendLinkData(link_id, HTTP_Page_Saved());
        ESP_CloseLink(link_id);
        return;
    }

    ESP_SendLinkData(link_id, HTTP_Page_404());
    ESP_CloseLink(link_id);
}
