#!/usr/bin/perl

use strict;
use warnings;

use LWP::UserAgent;
use HTML::TreeBuilder;

my $agent = LWP::UserAgent->new;

my $ticketListPage = "https://company.com/ticketList";

# Get Infoman front page
my $req = HTTP::Request->new(GET => $ticketListPage);
$req->header('Accept' => 'text/html');
# Supply username/password
$req->authorization_basic('username', 'password');

$agent->request($req);

sleep 10;

my $response = $agent->request($req);
my $content = $response->content;

# Now parse the content!
# The rows we care about start at @0.1.5.1
my $tree = HTML::TreeBuilder->new;
$tree->parse($content);
#$tree->dump;
my @contList = (((($tree->content_list())[1])->content_list())[5])->content_list();

foreach my $elem (@contList) {
    my @line;
    eval { @line = $elem->content_list() };
    next if $@;
    my $date = $line[3];
    next if !defined $date or $date->as_text =~ /DateOccurred/;
    my $dateText = $date->as_text;
    $dateText =~ s/\s//g;

    # Is this record for today?
    my (undef, undef, undef, $mday, $mon, $year) = localtime(time);
    $mon += 1;
    $year %= 100;
    my $today = ($mon < 10  ? "0$mon"  : $mon)  . "/"
              . ($mday < 10 ? "0$mday" : $mday) . "/"
              . ($year < 10 ? "0$year" : $year);
    next unless $dateText eq $today;

    # We have a record from today - get other info
    my $ticketNum = $line[1];
    my $time      = $line[4];
    my $desc      = $line[5];

    my $ticketNumText = $ticketNum->as_text;
    my $timeText      = $time->as_text;
    my $descText      = $desc->as_text;

    $ticketNumText =~ s/\s//g;
    $timeText      =~ s/\s//g;
    $descText      =~ s/(^\s+)|(\s+$)//g;

    my $msg = "New ticket:\n"
    . "DATE: $dateText\n"
    . "TIME: $timeText\n"
    . "TICKET NUMBER: $ticketNumText\n"
    . "DESCRIPTION: $descText\n";

    # HERE IS THE PROBLEM:
    #system "net send machinename $descText";
    print $msg;
}
