<?php
// Checked for PHP5.6 / 8.x compatibility

include("../../operainfo/getq3.php");

$filteryear = safetext2(isset($_GET['year']) ? $_GET['year'] : '');
$filtermonth = safetext2(isset($_GET['month']) ? $_GET['month'] : '');
$filterweek = safetext2(isset($_GET['week']) ? $_GET['week'] : '');

$s = "SELECT id, location, phpfile, datemodified, datecreated, filecode, notes FROM phplisting_auditlog ORDER BY datemodified";
$result = sqlquery($s);
$num = mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result))
{
    $filelocation = "".$row['location']."".$row['phpfile']."";
    $filemd5 = md5($filelocation);
    $lastmod[$filemd5] = $row['datemodified'];
    $lastcre[$filemd5] = $row['datecreated'];
    $originalfilecode = $row['filecode'];
    $filecodelist[$originalfilecode] = $originalfilecode;

    if ($row['datemodified'] != 1485955957 && $row['datemodified'] != 1575638715 && $row['datemodified'] != 1383743515 && $row['datemodified'] != 1575638825 && $row['notes'] != 'Vaimed Sync') {
        $yearcode = date("Y", $row['datemodified']);
        $monthyearcode = date("Yn", $row['datemodified']);
        $daymonthyearcode = date("dnY", $row['datemodified']);
        $monthcode = date("n", $row['datemodified']);
        $monthlist[$monthcode] = isset($monthlist[$monthcode]) ? $monthlist[$monthcode] + 1 : 1;
        $yeartotal[$yearcode] = isset($yeartotal[$yearcode]) ? $yeartotal[$yearcode] + 1 : 1;
        $monthyeartotal[$monthyearcode] = isset($monthyeartotal[$monthyearcode]) ? $monthyeartotal[$monthyearcode] + 1 : 1;
        $daymonthyeartotal[$daymonthyearcode] = isset($daymonthyeartotal[$daymonthyearcode]) ? $daymonthyeartotal[$daymonthyearcode] + 1 : 1;
        $daymonthyearlist[$daymonthyearcode] = isset($daymonthyearlist[$daymonthyearcode]) ? $daymonthyearlist[$daymonthyearcode] : '';
        $daymonthyearlist[$daymonthyearcode] .= "<tr><td>".$row['id']."</td><td>".$row['location']."</td><td>".$row['phpfile']."</td><td>".$row['notes']."</td><td><a href=\"view_assesment.php".$x."&lineid=".$row['id']."\" target=\"_assesment\"><img src=\"/intranet/images/mglass.png\" width=16></a></td></tr>";
    }
}


// Lets do some numbers
$yearssmessage = "";
$yearssmessage .= "<table class=CSSTable_n2><tr><Td>Year</td><Td>Number Updates</td></tr>";
ksort($yeartotal);
foreach ($yeartotal as $year => $yeartot) {
    $yearssmessage .= "<tr><Td><a href=\"javascript:void(0)\" onclick=\"updatetable('','','".$year."')\">$year</a></td><td><a href=\"javascript:void(0)\" onclick=\"updatetable('','','".$year."')\">$yeartot</a></td></tr>";
}
$yearssmessage .= "</table>";




$monthsmessage = "";
$monthsmessage .= "<table class=CSSTable_n2><tr><Td>Year</td>";
$month = 1;
while ($month < 13) {
    $monthsmessage .= "<td>$month</td>";
    $month++;
}
$monthsmessage .= "<td>Total</td></tr>";

foreach ($yeartotal as $year => $yeartot) {
    $monthsmessage .= "<tr><Td><a href=\"javascript:void(0)\" onclick=\"updatetable('','','".$year."')\">$year</a></td>";
    $month = 1;
    $linetotal = 0;
    while ($month < 13) {
        $monthyearcode = $year . $month;
        $monthyeartotal[$monthyearcode] = isset($monthyeartotal[$monthyearcode]) ? $monthyeartotal[$monthyearcode] : 0;
        $monthsmessage .= "<Td><a href=\"javascript:void(0)\" onclick=\"updatetable('',".$month.",'".$year."')\">".$monthyeartotal[$monthyearcode]."</a></td>";
        $linetotal = $linetotal + $monthyeartotal[$monthyearcode];
        $month++;
    }
    $monthsmessage .= "<td><a href=\"javascript:void(0)\" onclick=\"updatetable('','','".$year."')\">$linetotal</a></td></tr>";
}
$monthsmessage .= "</table>";



$monthsmessage .= "</table>";



$weekmessage = "";
$weekreport = "";

if ($filteryear != '' && $filtermonth != '' && $filterweek == '') {
    // Show weeks for selected month (Friday -> Thursday)
    $weekmessage = "Weeks for $filtermonth / $filteryear <br><table class=CSSTable_n2><tr><td>Week</td><td>Period</td><td>Updates</td></tr>";
    
    // Calculate first Friday of the month
    $firstDayOfMonth = mktime(0, 0, 0, $filtermonth, 1, $filteryear);
    $firstDayWeekday = date('w', $firstDayOfMonth); // 0=Sunday, 5=Friday
    
    // Find first Friday (if 1st is not Friday, go back to previous Friday)
    $daysToFriday = ($firstDayWeekday >= 5) ? ($firstDayWeekday - 5) : ($firstDayWeekday + 2);
    $firstFriday = strtotime("-".$daysToFriday." days", $firstDayOfMonth);
    
    $totallines = 0;
    $weeknum = 1;
    
    // Generate up to 6 weeks to cover the month
    for ($w = 0; $w < 6; $w++) {
        $weekStart = strtotime("+".$w." weeks", $firstFriday);
        $weekEnd = strtotime("+6 days", $weekStart);
        
        // Check if week overlaps with target month
        $weekStartMonth = date('n', $weekStart);
        $weekEndMonth = date('n', $weekEnd);
        $weekStartYear = date('Y', $weekStart);
        $weekEndYear = date('Y', $weekEnd);
        
        // Skip if week is entirely before or after target month
        if ($weekEndMonth != $filtermonth && $weekStartMonth != $filtermonth) {
            if ($weekStartMonth > $filtermonth || $weekStartYear > $filteryear) {
                break;
            }
            continue;
        }
        
        // Count updates in this week
        $weekcount = 0;
        $weekdetails = '';
        $currentDay = $weekStart;
        while ($currentDay <= $weekEnd) {
            $daycode = date("dnY", $currentDay);
            if (isset($daymonthyeartotal[$daycode])) {
                $weekcount = $weekcount + $daymonthyeartotal[$daycode];
            }
            if (isset($daymonthyearlist[$daycode])) {
                $weekdetails .= $daymonthyearlist[$daycode];
            }
            $currentDay = strtotime("+1 day", $currentDay);
        }
        
        $periodLabel = date("j M", $weekStart)." - ".date("j M", $weekEnd);
        $weekStartStr = date("Y-m-d", $weekStart);
        $weekEndStr = date("Y-m-d", $weekEnd);
        
        $weekmessage .= "<tr><td>Week ".$weeknum."</td><td>".$periodLabel."</td><td><a href=\"javascript:void(0)\" onclick=\"updatetable('".$weeknum."','".$filtermonth."','".$filteryear."')\">".$weekcount."</a></td></tr>";
        
        // Store week details for report view
        $weekdetailscode = $filteryear.$filtermonth.$weeknum;
        $weekdetailstore[$weekdetailscode] = $weekdetails;
        
        $totallines = $totallines + $weekcount;
        $weeknum++;
    }
    
    $weekmessage .= "<tr><td colspan=2> Total </td><td>$totallines</td></tr>";
    $weekmessage .= "</table>";
}

if ($filterweek != '' && $filteryear != '' && $filtermonth != '') {
    // Show individual updates for selected week
    // Rebuild week details since this is a fresh request
    $firstDayOfMonth = mktime(0, 0, 0, $filtermonth, 1, $filteryear);
    $firstDayWeekday = date('w', $firstDayOfMonth);
    $daysToFriday = ($firstDayWeekday >= 5) ? ($firstDayWeekday - 5) : ($firstDayWeekday + 2);
    $firstFriday = strtotime("-".$daysToFriday." days", $firstDayOfMonth);
    
    $targetWeekStart = strtotime("+".(intval($filterweek)-1)." weeks", $firstFriday);
    $targetWeekEnd = strtotime("+6 days", $targetWeekStart);
    
    $weekreport = "<br><div style='background:#f5f5f5;border:1px solid #ddd;padding:15px;margin-bottom:15px;border-radius:5px;font-family:monospace;white-space:pre-wrap;'>AI Prompt\nKeep the raw update list exactly as generated from the system.\nAdd a short technical development summary underneath each entry.\nFocus on:\n- Why the change was made\n- What functionality changed\n- What future problem it helps solve\n- Any side effects or intended future expansion</div><table class=CSSTable_n2><tr><td>Update ID</td><td>Date</td><td>Location</td><td>File</td><Td>Notes</td><td><img src=\"/intranet/images/mglass.png\" width=16></td></tr>";
    $currentDay = $targetWeekStart;
    while ($currentDay <= $targetWeekEnd) {
        $daycode = date("dnY", $currentDay);
        $dateStr = date("d M Y", $currentDay);
        if (isset($daymonthyearlist[$daycode])) {
            $dayRows = $daymonthyearlist[$daycode];
            // The pre-built rows are: <tr><td>ID</td><td>location</td>...
            // We need: <tr><td>ID</td><td>DATE</td><td>location</td>...
            // So replace the FIRST </td><td> after <tr><td> with </td><td>DATE</td><td>
            $dayRows = preg_replace('/<tr><td>([^<]+)<\/td><td>/', '<tr><td>$1</td><td>' . $dateStr . '</td><td>', $dayRows);
            $weekreport .= $dayRows;
        }
        $currentDay = strtotime("+1 day", $currentDay);
    }
    $weekreport .= "</table><br>";
}




print "$weekmessage";
print "$weekreport";
?>