#!/usr/bin/perl

use lib '/var/www/www.rcflightpath.com/lib/Utils';
use POSIX qw(strftime);
use CGI qw(:standard :html3 :all *table *Tr *td unescape);
use CGI::Cookie;
use Randpick;

my $debug = 0;
my $mode;
my $size;
my $html;
my $root = 'articles';;
my $docroot = '/var/www/www.rcflightpath.com';
my $base = "$docroot/$root";
my $side = $base.'/etc/sidebar_feature.html';
my $file = param('file'); $file =~ s/^\/$root//; $file =~ s/(\.\.)//g;
my $fullpath = $base.$file;
my $media = 'jpg|png|tif|jpeg|mp4|mp3|gif|pdf';
my $exclude = 'cgi|old|tgz|py|swp|disabled|html,v|json|db|current|pl|pl,v';
my $baseurl = "https://www.rcflightpath.com/$root";
my $weburl = "/$root".$file; $weburl =~ s/\/$//;
my $relpath = $file; $relpath =~ s/^\///; $relpath = '.' if (!$relpath);
my $breadcrumb;
my $myurl;
my $isfile;
my $words;

if (-f $relpath) {
  $isfile = 1;
  open (CHECK,$relpath);
  while (<CHECK>) {
    if ($_ =~ /^(Location|Status):/) {
      print "$_\n";
      exit if ($_ =~ /^(Location):/);
    }
    chomp;
    $html .= "$_\n";
    @line = split/\s+/;
    $words += scalar(@line);
    $doctype = 1 if ($_ =~ /DOCTYPE/);
    $no_sidebar = 1 if ($_ =~ /no_sidebar/i);
    $cond .= 'YT-' if ($_ =~ /youtube/i);
  }
  close CHECK;
  $adjusted = $words * .025; #<- THIS IS A PERCENTAGE REMOVED FOR WORD ESTIMATOR FOR THE HTML TAGS
  $adjusted = $words - $adjusted;
  $words = sprintf ("%2.0d",$adjusted);
}

@breadcrumb = split/\//,$weburl;
my $filename = pop(@breadcrumb) if ($isfile);
foreach (@breadcrumb) {
  $myurl .= "$_/";
  $breadcrumb .= "<a href='$myurl'>$_</a> // ";
}

if (($file =~ /\.($media)$/)&&(-e $fullpath)) {
  $mode .= 'media-';
  open (MEDIA,$fullpath);
  while (<MEDIA>) {
    print
  }
  close MEDIA; 
} elsif ($doctype) {
  print $html;
} elsif (-d $fullpath) {
  $mode .= 'explorer-';
  &print_header;
  print "<body>\n";
  &print_topnav;
  print "  <div class='container'>\n\n";
  #&print_hero("<span>$relpath</span> contents:",$breadcrumb);
  &print_hero(&get_title($relpath),$breadcrumb);

  &list_contents($fullpath);

  print "  </div> <!-- 'end container' -->\n";
  &print_footer;
  &print_script;
  print "</body>\n</html>\n";
} elsif (-f $fullpath) {
  $mode .= 'viewer-';
  &print_header;
  print "<body>\n";
  &print_topnav;
  print "  <div class='container'>\n\n";
  &print_hero(&get_title($relpath),$breadcrumb);

  &print_main($fullpath);

  print "  </div> <!-- 'end container' -->\n";
  &print_footer;
  &print_script;
  print "</body>\n</html>\n";
} else {
    print "Status: 404 Not Found\r\n";
    print "Content-Type: text/html\r\n\r\n";
    exit(1);
  $mode .= 'error-';
}
exit(0);

sub print_header {
  my $title = shift;
  if ($title eq 'not_found') {
    print "Status: 404 Not Found\r\n";
    print "Content-type: text/html\r\n\r\n";
  }
  print <<HEADER;
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>RC FlightPath — Web App Suite & Tool Hub</title>
  <link href="https://fonts.googleapis.com/css2?family=Big+Shoulders+Display:wght\@700;800&family=IBM+Plex+Mono:wght\@400;600&family=Inter:wght\@400;500;600;700&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Big+Shoulders:wght\@500;600;700;800&family=IBM+Plex+Mono:wght\@400;500;600&family=Inter:wght\@400;500;600&display=swap" rel="stylesheet">
  <link href='https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght\@0,400;0,600;0,700;1,400&family=DM+Sans:wght\@300;400;500;600&family=DM+Mono:wght\@400;500&display=swap' rel='stylesheet'>
  <link href="/new/style3.css" rel="stylesheet">
</head>
HEADER
}

sub print_main {
  print "    <section class='article-body'>\n";
  print "      <div class='article-grid'>\n";
  print "        <article class='article-content'>\n";
  $size = sprintf("%.2f",(-s $fullpath) / 1024); $size .= ' Kb';
  open (FILE,$fullpath);
  while (<FILE>) {
    chomp;

        if (($_ =~ /\<table/)&&($_ !~ /spec-table/)) {
          print "          <table class=\"spec-table\">\n";
        } else {
          if ($_ =~ /sec-head.*\<h2|h3/) {
            my $ptoc = $_;
            $ptoc =~ s/<h2>//;
            $ptoc =~ s/<\/h2>//;
            $ptoc =~ s/<h3>//;
            $ptoc =~ s/<\/h3>//;
            $ptoc =~ s/<\/div>//;
            $ptoc =~ s/<div.*>//;
            $ptoc =~ s/^\s+//;
            push (@toc,$ptoc);
            $id++;
            my $new = $_;
            $new =~ s/<h2/<h2 id=$id/;
            $new =~ s/<h3/<h3 id=$id/;
            $new =~ s/^\s+//;
            print "          $new\n";
          } elsif ($_ =~ /\<h2|h3/) {
            my $ptoc = $_;
            $ptoc =~ s/<h3>//;
            $ptoc =~ s/<\/h3>//;
            $ptoc =~ s/<h2>//;
            $ptoc =~ s/<\/h2>//;
            $ptoc =~ s/<\/div>//;
            $ptoc =~ s/<div.*>//;
            $ptoc =~ s/^\s+//;
            push (@toc,$ptoc);
            $id++;
            my $new = $_;
            $new =~ s/^\s+//;
            $new =~ s/<h2/<h2 id=$id/;
            print "          <div class='sec-head'>$new</div>\n";
          } else {
            print '          '.$_."\n";
          }
        }

  }
  close FILE;
  print "\n        </article><!-- 'end article-body' -->\n";
  foreach $ptoc(@toc) {
    $id2++;
    $toc .= "              <li><a href=\"\#$id2\">$ptoc</a></li>\n";
  }
  my $featured = &pick_featured;
  my @fullpath = split/\//,$fullpath;
  my $title    = pop(@fullpath);
     $title    =~ s/\_/ /g;
     $title    =~ s/\.html$//;
  my $related  = &pick_related(&get_title($relpath));
  &print_sidebar($featured,$toc,$related);
  print "      </div><!-- 'end article-grid' -->\n";
  print "    </section><!-- 'end article-content' -->\n";
}

sub print_topnav {
  print <<TOPNAV;
  <nav class="topnav">
    <div style="display: flex; align-items: center;">
      <a href="/"><img width=100 src="/images/logo6.png"></a>
      <a href="/library.cgi" class="brand">Article <span>Search</span></a>
    </div>
    <div class="nav-links">
      <a href="/">Home</a>
      <a href="/articles/RC_FlightPath/About_Us.html">About</a>
      <a href="/webapps">Apps</a>
      <a href="/airfields">Airfields</a>
      <a class="cta-btn" href="/#contact">Contact Us</a>
    </div>
  </nav>

TOPNAV
}

sub print_hero {
  my $title = shift;
  my $related;
  my $breadcrumb = shift;
  my $headline;
  if ($isfile) {
    $headline = 'Related Articles (by Title)';
    $related = &pick_related($title);
  } elsif ($weburl eq "/$root") {
    my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
    $headline = 'Latest Articles';
    chomp(my @all = `/usr/bin/find . | grep \\.html`);
    my %modtimes;
    foreach (@all) {
        # Use index 9 for mtime, and use $_ instead of $file
        next unless -e $_; # ensure file exists
        $modtimes{$_} = (stat($_))[9];
    }
    # Sort keys by their values (modtime) in descending order (newest first)
    $related = '<div>';
    my $c = 0;
    foreach my $file (sort { $modtimes{$b} <=> $modtimes{$a} } keys %modtimes) {
        next if ($file =~ /($exclude)$/);
        my @path = split /\//, $file;
        my $name = pop(@path);
        $name =~ s/\.html$//;
        $name =~ s/_/ /g;

        my ($mday, $mon, $year) = (localtime($modtimes{$file}))[3, 4, 5];
        my $date_str = sprintf("%s %d, %d", $months[$mon], $mday, $year + 1900);

        $related .= "<li><a href='$file'>$name</a> ($date_str)</li>\n";
        $c++; last if ($c >= 10);
    }
    $related .= '</div>';
  } else {
    $headline = "Related Topics in \"$relpath\"";
    chomp(my @all = `/usr/bin/find $relpath | grep \\.html | egrep -v \"RCS|,v\"`);
    foreach (my $i=0;$i<10;$i++) {
      my $total_items = scalar(@all);
      my $pick = int(rand($total_items));
      push (@rand,$all[$pick]) unless ($taken{$all[$pick]});
      $taken{$all[$pick]} = 1;
    }
    $related = '<div>';
    foreach (@rand) {
      my @array = split/\//,$_;
      my $filename = pop(@array);
      $filename =~ s/\.html$//;
      $filename =~ s/\_/ /g;
      next if ($filename eq 'index');
      $related .= "<li><a href=\"/$root/$_\">$filename</a></li>";
    }
    $related .= '</div>';
  }
  print <<HERO;

    <section class="hero">
      <section class="horizontal-section">
        <div class="box-left">
          <img class="hero-img" src="/images/articles_manuals.png">
          <div class="hero-tag">This is Learning - From the Ground, UP</div>
          <h1>$title</h1>
          <div class="breadcrumb">
            $breadcrumb
          </div>
          <br>
          <div><a href='/webapps' class='btn-launch btn-launch-hero'>&larr; WebApps</a>
          <a href='/library.cgi' class='btn-launch btn-launch-hero'>Search</a>
          <a href='/manuals' class='btn-launch btn-launch-hero'>Manuals &rarr;</a></div>
        </div>
        <div class="box-right">
          <div class="credit-box">
            <b>$headline:</b>
            $related
          </div>
        </div>
      </section>
    </section>

HERO
  undef $breadcrumb;
}

sub print_sidebar {
  my $featured = shift;
  my $toc      = shift;
  my $related  = shift;

  print <<SIDEBAR;

        <aside class="article-sidebar">
          <div class="sidebar-card">
            $featured
          </div>
          <div class="sidebar-card">
            <h4>File Sections (Easy Access):</h4>
            <ul class="toc-list">
              $toc
            </ul>
          </div>
          <div class="sidebar-card">
            <h4>Related Articles & Topics:</h4>
            <ul class="toc-list">
              $related
            </ul>
          </div>
        </aside>

SIDEBAR
}

sub print_footer {
  if ($debug) {
    chomp ($pwd = `/usr/bin/pwd`);
    print "<footer>\n";
    print "<center>\n";
    print "<table cellspacing=10 border=0>\n";
    print "<tr><td>filename</td><td>$filename</td></tr>\n",br;
    print "<tr><td>file</td><td>$file</td></tr>\n",br;
    print "<tr><td>pwd</td><td>$pwd</td></tr>\n",br;
    print "<tr><td>base</td><td>$base</td></tr>\n",br;
    print "<tr><td>fullpath</td><td>$fullpath</td></tr>\n",br;
    print "<tr><td>baseurl</td><td>$baseurl</td></tr>\n",br;
    print "<tr><td>weburl</td><td>$weburl</td></tr>\n",br;
    print "<tr><td>root</td><td>$root</td></tr>\n",br;
    print "<tr><td>relpath</td><td>$relpath</td></tr>\n",br;
    print "<tr><td>breadcrumb</td><td>$breadcrumb</td></tr>\n",br;
    print "<tr><td>isfile</td><td>$isfile</td></tr>\n",br;
    print "<tr><td>title</td><td>$title</td></tr>\n",br;
    print "<tr><td>title_word_count</td><td>$title_word_count</td></tr>\n",br;
    print "<tr><td>words</td><td>$words</td></tr>\n",br;
    print "<tr><td>mode</td><td>$mode</td></tr>\n",br;
    print "<tr><td>root</td><td>$root</td></tr>\n",br;
    print "<tr><td>genstr</td><td>$genstr</td></tr>\n",br;
    print "</table>\n";
    print "</center>\n";
    print "</footer>\n";
  } else {
    print <<FOOTER;

    <footer>
      <center>
      <table width=55% border=0>
        <tr>
          <td>
            <center>
              <strong>RC FlightPath</strong><br>
              Sunland, CA 91040 &nbsp;·&nbsp; Apollo XI Airfield, Van Nuys, CA<br>
              <a href="mailto:piroflip\@gmail.com">rcflightpath\@gmail.com</a> &nbsp;·&nbsp; (818) 600-1381<br>
              FAA Part 107 Certified &nbsp;·&nbsp; TRUST Certified &nbsp;·&nbsp; AMA Insured<br>
              © 2026 RC FlightPath. Flight Training · Custom Builds · Autonomous Drone Solutions. All rights reserved.
            </center>
          </td>
          <td>
            Proud supporters of
          </td>
          <td>
            <a href="https://www.facebook.com/hashtag/keeprchelisalive"><img height=100 src="/images/keep_rc_helis_alive.gif"></a>
          </td>
          <td>
            <a href="http://www.ircha.org"><img height=50 src="/images/ircha_logo.png"></a>
          </td>
        </tr>
      </table>
      </center>
    </footer>

FOOTER
  }
}

sub get_title {
  if ($weburl eq "/$root") {
    $mode .= 'root-';
    return "Article <em>Explorer</em>";
  } elsif (-d $relpath) {
    return "$relpath <span>Contents:</span>";
    print "              <a href='$weburl/$link' class='btn-launch'>$btn_msg &rarr;</a>\n";
  } elsif (-f $relpath) {
    my @array = split/\//,$file;
    $title_word_count = scalar(@array);
    $title = pop(@array);
    $title =~ s/\.html//;
    $title =~ s/\_/ /g;
    return $title;
  } else {
    return $relpath;
  }
}

sub list_contents {
  opendir (LS,$fullpath);
  @ls = readdir(LS);
  print "        <div class='ref-grid reveal'>\n";
  $type = 'article';
  $node = "$relpath Main Page";
  $info = 'Article';
  $desc = 'This is the Main Page for this topic. Start Here.';
  $badge = 'article';
  $btn_msg = 'Read Article';
  &print_appcard("$badge","$type","$node","$desc","$info","$weburl/index.html","$btn_msg") if (-f "$relpath/index.html");
  foreach $node (@ls) {
    next if (($node eq '.')||($node eq '..')||($node eq 'index.cgi')||($node eq 'RCS')||($node eq 'etc'));
    next if (($node eq 'images')||($node eq 'RCS')||($node eq 'admin')||($node eq 'backups'));
    next if ($node =~ /($exclude)$/);
    if ($node =~ /\.($media)$/) {
      $type = 'media';
      $desc = 'This is a media type - Click to Open';
      $btn_msg = 'Display Media';
      $badge = 'media';
      $size = sprintf("%.2f",(-s "$relpath/$node") / 1024); $size .= ' Kb';
    } elsif ($node =~ /\.(html)$/) {
      $type = 'article';
      open (ARTICLE,"$relpath/$node");
      while (<ARTICLE>) {
        chomp;
        $youtube = 1 if ($_ =~ /youtube\.com/i);
        $desc .= "$_," if ($_ =~ /<h2>/i);
        last if (length($desc) > 200);
      }
      close ARTICLE;
      $desc .= "Unable to get info for $relpath$node" if ((!$desc)&&(!$youtube));
      $desc =~ s/<(span|h2)>//g;
      $desc =~ s/<\/(span|h2|div)>//g;
      $desc =~ s/<(span|div)\s+class=(\"|')sec-(num|head)(\"|')>//ig;
      $desc =~ s/(1|2|3|4|5)\.\s/<li>/g;
      $desc =~ s/\,$//;
      $desc .= '<table cellspacing=10><tr><td><img width=30 src=/images/yt.png></td><td>Youtube Embedded Video</td></tr></table>' if ($youtube);
      $btn_msg = 'Read Article';
      $badge = 'article';
      $size = sprintf("%.2f",(-s "$relpath/$node") / 1024); $size .= ' Kb';
      $info = 'Article';
    } elsif (-d "$relpath/$node") {
      $type = 'topic';
      $type = 'gallery' if ($node eq 'images');
      $desc = "Articles on \"$node\" Topics";
      $btn_msg = 'View Topic';
      $badge = 'topic';
      $info = 'Folder';
    } else {
      $type = 'unknown';
      $btn_msg = 'Open File';
      $badge = 'unknown';
      $info = 'Unknown Filetype';
    }
    $link = $node;
    $node =~ s/\.(html)$//;
    $node =~ s/\_/ /g;
    &print_appcard("$badge","$type","$node","$desc","$info","$weburl/$link","$btn_msg");
    undef $desc;
    undef $youtube;
  }
  print "        </div> <!-- end 'ref-grid reveal' -->\n";
}

sub print_appcard {
    my $badge = shift;
    my $type = shift;
    my $node = shift;
    my $desc = shift;
    my $info = shift;
    my $href = shift;
    my $btn_msg = shift;
    print "          <div class='app-card'>\n";
    print "            <div class='card-top'>\n";
    print "              <div class='card-meta'>\n";
    print "                <span class='badge badge-$badge'>$type</span>\n";
    print "              </div>\n";
    print "              <h3>$node</h3>\n";
    print "              <div class='card-body'>\n";
    print "                <p><ul>$desc</ul></p>\n";
    print "              </div>\n";
    print "            </div>\n";
    print "            <div class='card-footer'>\n";
    print "              <span class='tech-stack'>$info</span>\n";
    print "              <a href='$href' class='btn-launch'>$btn_msg &rarr;</a>\n";
    print "            </div>\n";
    print "          </div>\n\n";
}

sub pick_related {
  my $keywords = shift;
  my $related;
  my %articles;
  my %used;
  $keywords =~ s/\s+(on|in|with|vs|and|index|to|a|make|your|now|rc|il|c|-|4)\s+/ /ig;
  $keywords =~ s/\s+/\|/g; $keywords =~ s/\|$//;
  chomp(my @array = `/usr/bin/find . | grep "\.html\"`);
  foreach (@array) {
    next if ($_ =~ /($exclude)/);
    @line = split/\//,$_;
    my $filename = pop(@line); $filename =~ s/(\s+)$//;
    my $filepath = join('/',@line);
    $articles{$filename} = $filepath;
  }
  @words = split/\|/,$keywords;
  foreach $word(@words) {
    $word = lc($word);
    $word =~ s/^\s+|\s+$//g; # Strip leading/trailing whitespace
    next if (($word eq 'on')||($word eq 'in')||($word eq 'with')||($word eq 'and')||($word eq 'index'));
    next if (($word eq 'a')||($word eq 'make')||($word eq 'how')||($word eq 'rc')||($word eq 'c'));
    next if (($word eq 'the')||($word eq 'make')||($word eq 'how')||($word eq 'for')||($word eq 'to'));
    next if (($word eq 'c')||($word eq '-')||($word eq '4')||($word eq 'is'));
    foreach (sort keys %articles) {
      if ($_ =~ /$word/i) {
        $name = $_;
        $name =~ s/\.html//;
        $name =~ s/\_/ /g;
        $related .= "<li><a alt=\"$word\" href=\"/$root/$articles{$_}/$_\">$name</a></li>" if (!$used{$_});
        $used{$_} = 1;
      }
    }
  }
  #return "<div>$related</div>";
  return $related;
}

sub pick_featured {
  opendir (FT,"$base/etc/featured");
  my @ft = readdir(FT);
  foreach (@ft) {
    next if ($_ !~ /\.(png|jpg)$/);
    push (@draw,$_);
  }
  my $total_items = scalar(@draw);
  my $pick = int(rand($total_items));
  my $image = '/articles/etc/featured/'.$draw[$pick];
  my $text = $image;
  my $desc;
  my $file_loc;
  $text =~ s/\.(jpg|png)/\.url/;
  $text =~ s/^\/articles\///;
  open (URL,"$text") || return "Unable to open $text";
  chomp (my $f_url = <URL>);
  my $file_loc = $f_url; $file_loc =~ s/^\///;
  open(ARTICLE,$file_loc);
  while (<ARTICLE>) {
    $desc = $_ if ($_ =~ /h1/i);
  }
  close ARTICLE;
  $desc =~ s/<h1>//;
  $desc =~ s/<\/h1>//;
  my $subtitle = 'Featured Article';
  $subtitle = 'Featured Webapp' if ($f_url =~ /webapp/i);
  return "<h4>$subtitle</h4><a href=\"$f_url\"><img width=255 alt=\"$desc\" src=\"$image\"></a><br><a href=\"$f_url\">$desc</a>";
}
