<?php

header('Content-Type: application/json; charset=utf-8');

$json_file_path = 'airports.json';
$json_data = file_get_contents($json_file_path);

// Decode the JSON data into an associative array
$airports = json_decode($json_data, true);

function old_airport() {
  $query = $_POST["query"];
  $url = 'https://tripadvisor16.p.rapidapi.com/api/v1/flights/searchAirport?query=' . urlencode($query);
  $headers = array(
      'X-RapidAPI-Key: ed73991f9amshff52a7add90bbc2p1ae9afjsn62d6e5f808db',
      'X-RapidAPI-Host: tripadvisor16.p.rapidapi.com'
  );

  $curl = curl_init($url);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

  $response = curl_exec($curl);
  if ($response === false) {
      print_r($response);
      echo 'Error occurred: ' . curl_error($curl);
  } else {
      $data = json_decode($response, true);
      // print_r($data);
      $new_data = [];
      // echo json_encode($data);
      if (isset($data['data']) && is_array($data['data'])) {
          foreach ($data['data'] as $airport) {
              $airport_data = [
                  "name" => $airport["name"],
                  "code" => $airport["airportCode"],
                  "place_name" => $airport["details"]["parent_name"],
                  "country" => $airport["details"]["grandparent_name"]
              ];
              // print_r($airport);
              array_push($new_data, $airport_data);
          }
          echo json_encode($new_data);
      } else {
          echo json_encode(["error" => true, "message" => "some error occurred"]);
      }
  }

  curl_close($curl);
}

function getAirportNameAndLocation($iata_code) {
    global $airports;
    foreach ($airports as $airport) {
        if (isset($airport['iata']) && $airport['iata'] === $iata_code) {
            return [
                'airport_name' => $airport['airport_name'],
                'city' => $airport['city'],
                'country' => $airport['country']
            ];
        }
    }
    return null; // Return null if the airport code is not found
}

if(isset($_POST["search_airport"])) {
  $query = $_POST["query"];
  $url = 'https://sky-scrapper.p.rapidapi.com/api/v1/flights/searchAirport?query=' . urlencode($query);
  $headers = array(
      'X-RapidAPI-Key: ed73991f9amshff52a7add90bbc2p1ae9afjsn62d6e5f808db',
      'X-RapidAPI-Host: sky-scrapper.p.rapidapi.com'
  );

  $curl = curl_init($url);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

  $response = curl_exec($curl);
  if ($response === false) {
      print_r($response);
      echo 'Error occurred: ' . curl_error($curl);
  } else {
      $data = json_decode($response, true);
      // echo json_encode($data);
      $formatted_data = [];
      // echo json_encode($data);
      if (isset($data['data']) && is_array($data['data'])) {
        foreach ($data['data'] as $airport) {
          $formatted_data[] = [
              'airport_name' => $airport['presentation']['title'] ?? '',
              'suggested_title' => $airport['presentation']['suggestionTitle'] ?? '',
              'city' => $airport['presentation']['localizedName'] ?? '',
              'country' => $airport['presentation']['subtitle'] ?? '',
              'iata_code' => $airport['skyId'] ?? '',
              'relevantFlightParams' => [
                  'entityId' => $airport['navigation']['relevantFlightParams']['entityId'] ?? '',
                  'skyId' => $airport['navigation']['relevantFlightParams']['skyId'] ?? '',
                  'localizedName' => $airport['navigation']['relevantFlightParams']['localizedName'] ?? ''
              ],
              'relevantHotelParams' => [
                'entityId' => $airport['navigation']['relevantHotelParams']['entityId'] ?? '',
                'entityType' => $airport['navigation']['relevantHotelParams']['entityType'] ?? '',
                'localizedName' => $airport['navigation']['relevantHotelParams']['localizedName'] ?? ''
              ]
          ];
        }

        // Send the formatted data as a JSON response
        echo json_encode([
            "error" => false,
            "message" => "Data fetched successfully",
            "airports" => $formatted_data
        ]);
      } else {
          echo json_encode(["error" => true, "message" => "some error occurred"]);
      }
  }

  curl_close($curl);
}

if(isset($_POST["search_flights"])) {
  $params = [
        'originSkyId' => isset($_POST['originSkyId']) ? htmlspecialchars($_POST['originSkyId']) : null,
        'destinationSkyId' => isset($_POST['destinationSkyId']) ? htmlspecialchars($_POST['destinationSkyId']) : null,
        'originEntityId' => isset($_POST['originEntityId']) ? htmlspecialchars($_POST['originEntityId']) : null,
        'destinationEntityId' => isset($_POST['destinationEntityId']) ? htmlspecialchars($_POST['destinationEntityId']) : null,
        'date' => isset($_POST['date']) ? htmlspecialchars($_POST['date']) : null,
        'cabinClass' => isset($_POST['cabinClass']) ? htmlspecialchars($_POST['cabinClass']) : 'economy',
        'adults' => isset($_POST['adults']) ? (int)htmlspecialchars($_POST['adults']) : 1,
        'childrens' => isset($_POST['childrens']) ? (int)htmlspecialchars($_POST['childrens']) : 0,
        'infants' => isset($_POST['infants']) ? (int)htmlspecialchars($_POST['infants']) : 0,
        'cabinClass' => isset($_POST['cabinClass']) ? htmlspecialchars($_POST['cabinClass']) : 'economy',
        'sortBy' => isset($_POST['sortBy']) ? htmlspecialchars($_POST['sortBy']) : 'best',
        'currency' => isset($_POST['currency']) ? htmlspecialchars($_POST['currency']) : 'USD',
        'market' => isset($_POST['market']) ? htmlspecialchars($_POST['market']) : 'en-US',
        'countryCode' => isset($_POST['countryCode']) ? htmlspecialchars($_POST['countryCode']) : 'US',
    ];

    if (isset($_POST['tripType']) && $_POST['tripType'] === 'ROUND_TRIP') {
        $params['returnDate'] = isset($_POST['returnDate']) ? htmlspecialchars($_POST['returnDate']) : null;
    }

    $params = array_filter($params, function($value) {
        return !is_null($value);
    });

    // print_r($params);

    $queryString = http_build_query($params);
    $url = 'https://sky-scrapper.p.rapidapi.com/api/v1/flights/searchFlights?' . $queryString;

    $headers = array(
        'X-RapidAPI-Key: ed73991f9amshff52a7add90bbc2p1ae9afjsn62d6e5f808db',
        'X-RapidAPI-Host: sky-scrapper.p.rapidapi.com'
    );

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    $response = curl_exec($curl);

    if ($response === false) {
        echo json_encode(['error' => true, 'message' => 'Error occurred: ' . curl_error($curl)]);
    } else {
        $data = json_decode($response, true);
        $all_flights = [];

        if (isset($data['data']['itineraries']) && is_array($data['data']['itineraries'])) {
            foreach ($data['data']['itineraries'] as $itinerary) {
                $outbound_leg = [];
                $return_leg = null;

                foreach ($itinerary['legs'] as $index => $leg) {
                    $flightSegments = [];

                    foreach ($leg['segments'] as $segment) {
                        $carrierCode = $segment['marketingCarrier']['alternateId'] ?? '';
                        $flightNumber = $segment['flightNumber'] ?? '';
                        $flightSegments[] = trim($carrierCode . ' ' . $flightNumber);
                    }

                    $flight_id = implode(', ', $flightSegments);
                    $leg_info = [
                        'flight_id' => $flight_id,
                        'price' => $itinerary['price']['formatted'] ?? 'N/A',
                        'from_airport' => [
                            'name' => $leg['origin']['name'] ?? '',
                            'city' => $leg['origin']['city'] ?? '',
                            'country' => $leg['origin']['country'] ?? '',
                            'airport_code' => $leg['origin']['displayCode'] ?? '',
                            'entity_id' => $leg['origin']['entityId'] ?? ''
                        ],
                        'to_airport' => [
                            'name' => $leg['destination']['name'] ?? '',
                            'city' => $leg['destination']['city'] ?? '',
                            'country' => $leg['destination']['country'] ?? '',
                            'airport_code' => $leg['destination']['displayCode'] ?? '',
                            'entity_id' => $leg['destination']['entityId'] ?? ''
                        ],
                        'departure_time' => $leg['departure'] ?? '',
                        'arrival_time' => $leg['arrival'] ?? '',
                        'duration_in_minutes' => $leg['durationInMinutes'] ?? 0,
                        'stop_count' => $leg['stopCount'] ?? 0,
                        'airline' => [
                            'name' => $leg['carriers']['marketing'][0]['name'] ?? '',
                            'logo_url' => $leg['carriers']['marketing'][0]['logoUrl'] ?? ''
                        ]
                    ];

                    // Assume the first leg is the outbound flight and the second leg is the return flight
                    if ($index === 0) {
                        $outbound_leg = $leg_info;
                    } else {
                        $return_leg = $leg_info;
                    }
                }

                $all_flights[] = [
                    'outbound_flight' => $outbound_leg,
                    'return_flight' => $return_leg,
                    'flight' => $itinerary,
                    'total_price' => $itinerary['price']['formatted'] ?? 'N/A'
                ];
            }

            echo json_encode([
                "error" => false,
                "message" => "Flights fetched successfully",
                "flights" => $all_flights
            ]);
        } else {
            echo json_encode(['error' => true, 'message' => 'No flights found.']);
        }
    }

    curl_close($curl);
}

if(isset($_POST["search_flights2"])) {
  $params = [
        'originSkyId' => isset($_POST['originSkyId']) ? htmlspecialchars($_POST['originSkyId']) : null,
        'destinationSkyId' => isset($_POST['destinationSkyId']) ? htmlspecialchars($_POST['destinationSkyId']) : null,
        'originEntityId' => isset($_POST['originEntityId']) ? htmlspecialchars($_POST['originEntityId']) : null,
        'destinationEntityId' => isset($_POST['destinationEntityId']) ? htmlspecialchars($_POST['destinationEntityId']) : null,
        'date' => isset($_POST['date']) ? htmlspecialchars($_POST['date']) : null,
        'cabinClass' => isset($_POST['cabinClass']) ? htmlspecialchars($_POST['cabinClass']) : 'economy',
        'adults' => isset($_POST['adults']) ? (int)htmlspecialchars($_POST['adults']) : 1,
        'childrens' => isset($_POST['childrens']) ? (int)htmlspecialchars($_POST['childrens']) : 0,
        'infants' => isset($_POST['infants']) ? (int)htmlspecialchars($_POST['infants']) : 0,
        'cabinClass' => isset($_POST['cabinClass']) ? htmlspecialchars($_POST['cabinClass']) : 'economy',
        'sortBy' => isset($_POST['sortBy']) ? htmlspecialchars($_POST['sortBy']) : 'best',
        'currency' => isset($_POST['currency']) ? htmlspecialchars($_POST['currency']) : 'USD',
        'market' => isset($_POST['market']) ? htmlspecialchars($_POST['market']) : 'en-US',
        'countryCode' => isset($_POST['countryCode']) ? htmlspecialchars($_POST['countryCode']) : 'US',
    ];

    if (isset($_POST['tripType']) && $_POST['tripType'] === 'ROUND_TRIP') {
        $params['returnDate'] = isset($_POST['returnDate']) ? htmlspecialchars($_POST['returnDate']) : null;
    }

    $params = array_filter($params, function($value) {
        return !is_null($value);
    });

    // print_r($params);

    $queryString = http_build_query($params);
    $url = 'https://sky-scrapper.p.rapidapi.com/api/v1/flights/searchFlights?' . $queryString;

    $headers = array(
        'X-RapidAPI-Key: ed73991f9amshff52a7add90bbc2p1ae9afjsn62d6e5f808db',
        'X-RapidAPI-Host: sky-scrapper.p.rapidapi.com'
    );

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    $response = curl_exec($curl);

    if ($response === false) {
        echo json_encode(['error' => true, 'message' => 'Error occurred: ' . curl_error($curl)]);
    } else {
        $data = json_decode($response, true);
        echo json_encode($data);
    }
    //     $all_flights = [];
    //
    //     if (isset($data['data']['itineraries']) && is_array($data['data']['itineraries'])) {
    //         foreach ($data['data']['itineraries'] as $itinerary) {
    //             $outbound_leg = [];
    //             $return_leg = null;
    //
    //             foreach ($itinerary['legs'] as $index => $leg) {
    //                 $flightSegments = [];
    //
    //                 foreach ($leg['segments'] as $segment) {
    //                     $carrierCode = $segment['marketingCarrier']['alternateId'] ?? '';
    //                     $flightNumber = $segment['flightNumber'] ?? '';
    //                     $flightSegments[] = trim($carrierCode . ' ' . $flightNumber);
    //                 }
    //
    //                 $flight_id = implode(', ', $flightSegments);
    //                 $leg_info = [
    //                     'flight_id' => $flight_id,
    //                     'price' => $itinerary['price']['formatted'] ?? 'N/A',
    //                     'from_airport' => [
    //                         'name' => $leg['origin']['name'] ?? '',
    //                         'city' => $leg['origin']['city'] ?? '',
    //                         'country' => $leg['origin']['country'] ?? '',
    //                         'airport_code' => $leg['origin']['displayCode'] ?? '',
    //                         'entity_id' => $leg['origin']['entityId'] ?? ''
    //                     ],
    //                     'to_airport' => [
    //                         'name' => $leg['destination']['name'] ?? '',
    //                         'city' => $leg['destination']['city'] ?? '',
    //                         'country' => $leg['destination']['country'] ?? '',
    //                         'airport_code' => $leg['destination']['displayCode'] ?? '',
    //                         'entity_id' => $leg['destination']['entityId'] ?? ''
    //                     ],
    //                     'departure_time' => $leg['departure'] ?? '',
    //                     'arrival_time' => $leg['arrival'] ?? '',
    //                     'duration_in_minutes' => $leg['durationInMinutes'] ?? 0,
    //                     'stop_count' => $leg['stopCount'] ?? 0,
    //                     'airline' => [
    //                         'name' => $leg['carriers']['marketing'][0]['name'] ?? '',
    //                         'logo_url' => $leg['carriers']['marketing'][0]['logoUrl'] ?? ''
    //                     ]
    //                 ];
    //
    //                 // Assume the first leg is the outbound flight and the second leg is the return flight
    //                 if ($index === 0) {
    //                     $outbound_leg = $leg_info;
    //                 } else {
    //                     $return_leg = $leg_info;
    //                 }
    //             }
    //
    //             $all_flights[] = [
    //                 'outbound_flight' => $outbound_leg,
    //                 'return_flight' => $return_leg,
    //                 'flight' => $itinerary,
    //                 'total_price' => $itinerary['price']['formatted'] ?? 'N/A'
    //             ];
    //         }
    //
    //         echo json_encode([
    //             "error" => false,
    //             "message" => "Flights fetched successfully",
    //             "flights" => $all_flights
    //         ]);
    //     } else {
    //         echo json_encode(['error' => true, 'message' => 'No flights found.']);
    //     }
    // }

    curl_close($curl);
}


function old_flight_search() {
  $sourceAirportCode = htmlspecialchars($_POST['sourceAirportCode']);
  $sourceAirportName = htmlspecialchars($_POST['sourceAirportName']);
  $destinationAirportCode = htmlspecialchars($_POST['destinationAirportCode']);
  $destinationAirportName = htmlspecialchars($_POST['destinationAirportName']);
  $date = htmlspecialchars($_POST['date']);
  $returnDate = htmlspecialchars($_POST['returnDate']);
  $numAdults = (int) htmlspecialchars($_POST['numAdults']);
  $tripType = htmlspecialchars($_POST['tripType']);

  function extractAirportCode($input) {
      $trimmedString = trim($input);
      $lastSpacePosition = strrpos($trimmedString, ' ');
      if ($lastSpacePosition !== false) {
          return substr($trimmedString, $lastSpacePosition + 1);
      }
      return $input; // Return the input if no space is found
  }

  $sourceAirportCode = extractAirportCode($sourceAirportCode);
  $destinationAirportCode = extractAirportCode($destinationAirportCode);

  // Prepare the request parameters
  $requestData = array(
      'sourceAirportCode' => $sourceAirportCode,
      'destinationAirportCode' => $destinationAirportCode,
      'date' => $date,
      'returnDate' => $returnDate,
      'itineraryType' => $tripType,
      'sortOrder' => 'PRICE',
      'numAdults' => $numAdults,
      'numSeniors' => 0,
      'classOfService' => 'ECONOMY',
      'pageNumber' => 1,
      'currencyCode' => 'USD'
  );

  // Build the query string
  $queryString = http_build_query($requestData);

  // Construct the API URL
  $url = 'https://tripadvisor16.p.rapidapi.com/api/v1/flights/searchFlights?' . $queryString;

  // Set up the request headers
  $headers = array(
      'X-RapidAPI-Key: some', // Replace with your actual RapidAPI key
      'X-RapidAPI-Host: tripadvisor16.p.rapidapi.com'
  );

  // Initialize cURL session
  $curl = curl_init($url);

  // Set cURL options
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

  // Execute the cURL session
  $response = curl_exec($curl);

  // Check for errors
  if ($response === false) {
      echo 'Error occurred: ' . curl_error($curl);
  } else {
      // Decode the JSON response
      $data = json_decode($response, true);
      $all_flights = [];

      // Check if flights are found
      if (isset($data['data'])) {
          foreach ($data['data']['flights'] as $flight) {
              $all_segments = []; // Array to hold all segments for this flight

              foreach ($flight['segments'] as $segment) {
                  if (isset($segment['legs'][0])) {
                      $first_leg = $segment['legs'][0];
                      $last_leg = end($segment['legs']);
                      $airlineName = isset($first_leg['operatingCarrier']['displayName']) ? $first_leg['operatingCarrier']['displayName'] : 'Unknown Airline';
                      $departureDateTime = new DateTime($first_leg['departureDateTime']);
                      $departureDateTimeUnformatted = $first_leg['departureDateTime'];
                      $arrivalDateTimeUnformatted = $last_leg['arrivalDateTime'];
                      $formattedDepartureDateTime = $departureDateTime->format('h:i A');
                      $arrivalDateTime = new DateTime($last_leg['arrivalDateTime']);
                      $formattedArrivalDateTime = $arrivalDateTime->format('h:i A');

                      $totalPrice = isset($flight['purchaseLinks'][0]['totalPricePerPassenger']) ? $flight['purchaseLinks'][0]['totalPricePerPassenger'] : 'N/A';
                      $numStops = count($segment['legs']) - 1; // Total number of stops

                      $apiPath = isset($first_leg['operatingCarrier']['logoUrl']) ? $first_leg['operatingCarrier']['logoUrl'] : '';

                      // Create flight_id by concatenating all leg flight numbers
                      $flightIds = [];
                      foreach ($segment['legs'] as $leg) {
                          $flightIds[] = $leg['marketingCarrierCode'] . ' ' . $leg['flightNumber'];
                      }
                      $flightId = implode(', ', $flightIds);

                      // Add segment data to the all_segments array
                      $current_segment = [
                          'flight_image' => $apiPath,
                          'flight_name' => $airlineName,
                          'from_airport' => getAirportNameAndLocation($first_leg['originStationCode']),
                          'from_airport_code' => $first_leg['originStationCode'],
                          'to_airport' => getAirportNameAndLocation($last_leg['destinationStationCode']),
                          'to_airport_code' => $last_leg['destinationStationCode'],
                          'departure_time' => $formattedDepartureDateTime,
                          'arrival_time' => $formattedArrivalDateTime,
                          'total_price' => $totalPrice,
                          'num_stops' => $numStops,
                          'departure_time_full' => $departureDateTimeUnformatted,
                          'arrival_time_full' => $arrivalDateTimeUnformatted,
                          'flight_id' => $flightId,
                      ];
                      array_push($all_segments, $current_segment);
                  } else {
                      echo 'Segment data is missing legs information.<br>';
                  }
              }

              // Create the final flight data structure, including both outbound and return segments
              $current_flight = [
                  'outbound_segment' => isset($all_segments[0]) ? $all_segments[0] : null,
                  'return_segment' => isset($all_segments[1]) ? $all_segments[1] : null,
                  'all_data' => $flight
              ];

              array_push($all_flights, $current_flight);
          }
          echo json_encode($all_flights);
      } else {
          // print_r($data);
          echo json_encode(['error' => true, 'message' => 'No flight found.']);
      }
  }

  // Close cURL session
  curl_close($curl);
}
