#!/bin/bash

# File paths
CREDENTIALS_FILE="credentials.txt"
IDS_FILE="ids.txt"
COOKIE_FILE="cookies.txt"
RESPONSE_DIR="./response"

# Ensure credentials file exists
if [[ ! -f "$CREDENTIALS_FILE" ]]; then
  echo "[!] Error: Credentials file '$CREDENTIALS_FILE' not found."
  exit 1
fi

# Ensure IDs file exists
if [[ ! -f "$IDS_FILE" ]]; then
  echo "[!] Error: IDs file '$IDS_FILE' not found."
  exit 1
fi

# Create response folder if it does not exist
if [[ ! -d "$RESPONSE_DIR" ]]; then
  echo "[+] Creating response folder: $RESPONSE_DIR"
  mkdir -p "$RESPONSE_DIR"
fi

# Load credentials
source "$CREDENTIALS_FILE"

# Ensure credentials are set
if [[ -z "$USERNAME" || -z "$PASSWORD" || -z "$KLIENT" ]]; then
  echo "[!] Error: Credentials file '$CREDENTIALS_FILE' is missing required values."
  exit 1
fi

# Load employees and IDs into parallel arrays
EMPLOYEES=()
EMPLOYEE_IDS=()
while IFS='=' read -r name id; do
  EMPLOYEES+=("$name")
  EMPLOYEE_IDS+=("$id")
done < "$IDS_FILE"

# Ensure we get at least 3 arguments (1+ employees OR "all" + start and end date)
if [[ $# -lt 3 ]]; then
  echo "Usage: $0 <medarbejder1> [medarbejder2] ... <start-date(dd-mm-yyyy)> <end-date(dd-mm-yyyy)>"
  exit 1
fi

# Extract last two arguments as dates
START_DATE="${@: -2:1}"
END_DATE="${@: -1:1}"

# Extract medarbejdere (all arguments except last two)
if [[ "$(echo "$1" | tr '[:upper:]' '[:lower:]')" == "all" ]]; then
  MEDARBEJDERE=("${EMPLOYEES[@]}")
else
  MEDARBEJDERE=("${@:1:$#-2}")
fi

# Validate date format (dd-mm-yyyy)
if ! [[ $START_DATE =~ ^[0-9]{2}-[0-9]{2}-[0-9]{4}$ ]]; then
  echo "[!] Invalid start date format. Use dd-mm-yyyy."
  exit 1
fi

if ! [[ $END_DATE =~ ^[0-9]{2}-[0-9]{2}-[0-9]{4}$ ]]; then
  echo "[!] Invalid end date format. Use dd-mm-yyyy."
  exit 1
fi

# Convert dates to YYYYMMDD format manually
START_DATE_NUM=$(echo "$START_DATE" | sed -E 's/([0-9]{2})-([0-9]{2})-([0-9]{4})/\3\2\1/')
END_DATE_NUM=$(echo "$END_DATE" | sed -E 's/([0-9]{2})-([0-9]{2})-([0-9]{4})/\3\2\1/')

# Validate that the end date is after the start date
if [[ -z "$START_DATE_NUM" || -z "$END_DATE_NUM" ]]; then
  echo "[!] Error parsing dates. Make sure they are valid."
  exit 1
fi

if [[ $END_DATE_NUM -le $START_DATE_NUM ]]; then
  echo "[!] The end date must be later than the start date."
  exit 1
fi

# Login URL
LOGIN_URL="https://www.eadministration.dk/logon.asp"

# Check if previous session exists
if [[ -f "$COOKIE_FILE" ]]; then
  # Extract previous esession
  ESESSION=$(grep "esession" "$COOKIE_FILE" | awk '{print $NF}')
fi

# Function to log in and get a new esession
fetch_new_esession() {
  echo "[+] Logging in as $USERNAME..."
  curl -sS -o /dev/null -L -X POST "$LOGIN_URL" \
    -H "Content-Type: application/x-www-form-urlencoded" \
    --data "origin=&klient=$KLIENT&bruger=$USERNAME&kodeord=$PASSWORD&forgot=" \
    -c "$COOKIE_FILE"

    # Extract session token
    ESESSION=$(grep "esession" "$COOKIE_FILE" | awk '{print $NF}')

    if [[ -n "$ESESSION" ]]; then
      echo "[+] Successfully extracted new esession: $ESESSION"
    else
      echo "[!] Failed to extract 'esession'. Login may have failed."
      exit 1
    fi
  }

# If no valid esession, fetch a new one
if [[ -z "$ESESSION" ]]; then
  fetch_new_esession
else
  echo "[+] Reusing existing esession: $ESESSION"
fi

# Loop through each medarbejder
for MEDARBEJDER in "${MEDARBEJDERE[@]}"; do
  # Find the matching medarbejder ID
  MEDARBEJDER_ID=""
  for i in "${!EMPLOYEES[@]}"; do
    if [[ "${EMPLOYEES[$i]}" == "$MEDARBEJDER" ]]; then
      MEDARBEJDER_ID="${EMPLOYEE_IDS[$i]}"
      break
    fi
  done
  # Check if medarbejder is found
  if [[ -z "$MEDARBEJDER_ID" ]]; then
    echo "[!] Employee '$MEDARBEJDER' not found in IDs file. Skipping..."
    continue
  fi
  # Target Data URL
  DATA_URL="https://webdk206.eadministration.dk/medarbejderbookingliste_ajax.asp?browserklientid=415&lokation=0&medarbejder=$MEDARBEJDER_ID&status=-3&dag=$START_DATE&slutdag=$END_DATE"
  # Generate output filename inside response folder
  OUTPUT_FILE="${RESPONSE_DIR}/${MEDARBEJDER}-${START_DATE}-til-${END_DATE}.html"
  echo "[+] Fetching data for $MEDARBEJDER (ID: $MEDARBEJDER_ID) from $START_DATE to $END_DATE..."
  # Attempt fetching data with up to 3 retries
  RETRY_COUNT=0
  MAX_RETRIES=3
  SUCCESS=false
  while [[ $RETRY_COUNT -lt $MAX_RETRIES ]]; do
    # Temporary file to avoid creating an empty output file
    TEMP_FILE="${OUTPUT_FILE}.tmp"

      # Make request using existing esession and save to a temp file
      HTTP_STATUS=$(curl -s -o "$TEMP_FILE" -w "%{http_code}" -L -X GET "$DATA_URL" \
        -b "$COOKIE_FILE" \
        -H "Accept-Encoding: identity")

      # Check if request was successful (HTTP 200 OK) and file is not empty
      if [[ "$HTTP_STATUS" == "200" && -s "$TEMP_FILE" ]]; then
        # Check if file begins with expected HTML table structure
        if grep -q "^\s*<table cellspacing=\"0\" class=\"table-default\" ev-controls=\"all\">" "$TEMP_FILE"; then
          echo "[+] Data successfully fetched for $MEDARBEJDER with valid table format!"
          mv "$TEMP_FILE" "$OUTPUT_FILE"  # Move temp file to final location
          echo "[+] Output saved to '$OUTPUT_FILE'."
          SUCCESS=true
          break
        else
          echo "[!] Response received for $MEDARBEJDER but does not contain the expected table format."
          echo "[+] Getting a new session and retrying..."
          rm -f "$TEMP_FILE"  # Remove invalid response file
          fetch_new_esession  # Get a new session
        fi
      else
        rm -f "$TEMP_FILE"  # Remove temp file if request failed

        # If session expired, fetch a new one and retry
        if [[ "$HTTP_STATUS" == "401" || "$HTTP_STATUS" == "403" ]]; then
          echo "[!] Session expired. Fetching new session and retrying..."
          fetch_new_esession
        fi
        fi

      sleep 0.2 # Wait 200 milliseconds before retrying

      # Retry logic
      ((RETRY_COUNT++))
      echo "[!] Attempt $RETRY_COUNT failed for $MEDARBEJDER. Retrying..."
    done

# If all retries fail, log failure
if [[ "$SUCCESS" == false ]]; then
  echo "[!] Failed to retrieve data for $MEDARBEJDER after $MAX_RETRIES attempts."
fi

done
