<?php
include("../../operainfo/getq2.php");

// Checked for PHP5.6 / 8.x compatibility

$stkref = safetext2(isset($_GET['stk']) ? $_GET['stk'] : '');
$hostcompanyid = safetext2(isset($_GET['hostcompanyid']) ? $_GET['hostcompanyid'] : '');
$currentYear = date("Y");

// Fetch sales for last 5 years
$years = [];
for ($i = 4; $i >= 0; $i--) {
    $years[] = $currentYear - $i;
}

$salesData = [];
$decliningSales = [];
$companyDetails = [];



// Fetch status and action options separately
$statusOptions = [];
$actionOptions = [];

$s = "SELECT id, description, type , colourcode FROM viamedquotecontactstockstatuslist ORDER BY id ASC";
$stmt = pdoquery($s);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
    if ((int)$row['type'] === 2) {
        $statusOptions[$row['id']] = $row['description'];
        $statusOptions[$row['id'] . '_color'] = !empty($row['colourcode']) ? $row['colourcode'] : '#cce5ff'; // default blue
    } elseif ((int)$row['type'] === 1) {
        $actionOptions[$row['id']] = $row['description'];
        $actionOptions[$row['id'] . '_color'] = !empty($row['colourcode']) ? $row['colourcode'] : '#cce5ff'; // default blue
    }
}

// Fetch latest used status per company for this stock and typedata='LostCustomer'
$latestStatusPerCompany = [];
$s = "SELECT companyid, statusid , addedon FROM viamedquotecontactstockstatus WHERE stock_ref = ? AND hostcompanyid = ? AND typedata = 'LostCustomer' ORDER BY addedon DESC";
$stmt = pdoquery($s, array($stkref, $hostcompanyid));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
    $cid = $row['companyid'];
    if (!isset($latestStatusPerCompany[$cid])) {
    $latestStatusPerCompany[$cid] = [
        'statusid' => $row['statusid'],
        'addedon' => $row['addedon']
    ];
    }
}

// Fetch latest used action per company for this stock and typedata='LostCustomerAction'
$latestActionPerCompany = [];
$s = "SELECT companyid, statusid , addedon FROM viamedquotecontactstockstatus WHERE stock_ref = ? AND hostcompanyid = ? AND typedata = 'LostCustomerAction' ORDER BY addedon DESC";
$stmt = pdoquery($s, array($stkref, $hostcompanyid));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
    $cid = $row['companyid'];
    if (!isset($latestActionPerCompany[$cid])) {
            $latestActionPerCompany[$cid] = [
        'statusid' => $row['statusid'],
        'addedon' => $row['addedon']
    ];
    }
}

// Query sales data (now grouping by company_id)
// Query sales data (grouping by company_id)
foreach ($years as $year) {
    $startDate = mktime(0, 0, 0, 1, 1, $year);
    $endDate = mktime(23, 59, 59, 12, 31, $year);

    $s = "SELECT vqoi.companyid, COUNT(vqoid.barcode) AS total_items_sold FROM viamedquote_orders_invoices vqoi JOIN viamedquote_orders_invoices_details vqoid ON vqoid.invoiceref = vqoi.invoiceref WHERE vqoi.hostcompanyid = ? AND vqoid.stockref = ? AND vqoi.invoicecommitedon BETWEEN ? AND ? GROUP BY vqoi.companyid";

    //print "$s<br>";  // Debugging: Print SQL query

    $stmt = pdoquery($s, array($hostcompanyid, $stkref, $startDate, $endDate));
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rows as $row) {
        $company_id = $row['companyid'];
        $salesData[$company_id]['sales'][$year] = $row['total_items_sold'];
    }
}

// Identify declining sales (compare last 2 years)
$previousYear = $currentYear - 2;
$lastYear = $currentYear - 1;

foreach ($salesData as $company_id => $data) {
    $salesPrev = isset($data['sales'][$previousYear]) ? $data['sales'][$previousYear] : 0;
    $salesLast = isset($data['sales'][$lastYear]) ? $data['sales'][$lastYear] : 0;

    if ($salesLast < $salesPrev) {
        $decliningSales[$company_id] = true;
    }
}

// Fetch company details and order alphabetically
$s = "SELECT ID, COMPANY, blacklist, hideme, preferedcid FROM viamedquoteaddress ORDER BY COMPANY ASC";
$stmt = pdoquery($s);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
    $company_id = $row['ID'];
    $companyDetails[$company_id] = [
        'company_name' => $row['COMPANY'],
        'blacklist' => trim($row['blacklist']),
        'hideme' => trim($row['hideme']),
        'preferedcid' => (int) $row['preferedcid']
    ];
}







// Buttons for filtering
echo "<h1>Lost Sales for $stkref ($hostcompanyid) - Last 5 Years</h1>";
echo "<button onclick='filterTable(\"all\")'>Show All</button> ";
echo "<button onclick='filterTable(\"losing\")'>Show Losing Sales Only</button> ";
echo "<button onclick='filterTable(\"losing-no-blacklist\")'>Show Losing Sales & No Blacklist</button>";

echo "<table id='salesTable' class='CSSTable_n2'>";
echo "<tr><th>CID</th><th>Company</th><th>Account Status</th>";

foreach ($years as $year) {
    echo "<th>$year Sales</th>";
}
echo "<th>Trend</th><th> Status </th><th> Action </th></tr>";

// Display data sorted by company name
foreach ($companyDetails as $company_id => $companyInfo) {
    if (!isset($salesData[$company_id])) {
        continue;
    }
    
    // Skip hidden companies
    if (!empty($companyInfo['hideme'])) {
        continue;
    }

    $companyName = $companyInfo['company_name'];
    $blacklist = $companyInfo['blacklist'];
    $preferedcid = $companyInfo['preferedcid'];

    // Determine row class for filtering
    $rowClass = "row-all";
    if (isset($decliningSales[$company_id])) {
        $rowClass .= " row-losing";
        if (!empty($blacklist)) {
            $rowClass .= " row-losing-blacklist";
        }
    }

    echo "<tr class='$rowClass'>";
    echo "<td>".linkcrm($x,$company_id,'')."$company_id</td><Td>$companyName</td>";

    // Account Status Column
    echo "<td>";

    // Show merged account notice
    if ($preferedcid > 0) {
        echo "<b>Use CID $preferedcid</b><br>";
    }

    // Show blacklist icon if applicable
    if (!empty($blacklist)) {
        echo "<span title='Blacklisted: $blacklist' style='cursor:pointer;' onclick='alert(\"Blacklisted Reason: $blacklist\");'>⚠</span>";
    }

    echo "</td>";

    // Sales Data Columns
    foreach ($years as $year) {
        $sales = isset($salesData[$company_id]['sales'][$year]) ? $salesData[$company_id]['sales'][$year] : 0;
        echo "<td>$sales</td>";
    }

    // Highlight declining sales
    if (isset($decliningSales[$company_id])) {
        echo "<td style='color: red; font-weight: bold;'>⬇ Losing Sales</td>";
    } else {
        echo "<td>✔ Stable</td>";
    }
$currentStatusId = isset($latestStatusPerCompany[$company_id]) ? $latestStatusPerCompany[$company_id]['statusid'] : '';
$currentStatusDate = isset($latestStatusPerCompany[$company_id]) ? $latestStatusPerCompany[$company_id]['addedon'] : '';

echo "<td>";
$statusBgColor = isset($statusOptions[$currentStatusId . '_color']) ? $statusOptions[$currentStatusId . '_color'] : '#cce5ff';
echo "<select class='status-select' data-cid='$company_id' style='background-color:$statusBgColor;' onchange='saveStatus($company_id, \"$stkref\",$hostcompanyid)'>";


// First add the "Unselected" option
echo "<option value='0'" . ($currentStatusId == '' ? " selected" : "") . ">-- Unselected --</option>";

foreach ($statusOptions as $statusId => $desc) {
    if (!is_numeric($statusId)) continue; // <-- Skip the *_color entries
    $selected = ($statusId == $currentStatusId) ? "selected" : "";
    echo "<option value='$statusId' $selected>$desc</option>";
}

echo "</select>";
if (!empty($currentStatusDate)) {
    echo "<div style='font-size:10px;color:#555;'>Set on: ".date("d M Y",$currentStatusDate)."</div>";
}
echo "</td>";

$currentActionId = isset($latestActionPerCompany[$company_id]) ? $latestActionPerCompany[$company_id]['statusid'] : '';
$currentActionDate = isset($latestActionPerCompany[$company_id]) ? $latestActionPerCompany[$company_id]['addedon'] : '';

echo "<td>";
$actionBgColor = isset($actionOptions[$currentActionId . '_color']) ? $actionOptions[$currentActionId . '_color'] : '#cce5ff';
echo "<select class='action-select' data-cid='$company_id' style='background-color:$actionBgColor;' onchange='saveAction($company_id, \"$stkref\",$hostcompanyid)'>";

echo "<option value='0'" . ($currentActionId == '' ? " selected" : "") . ">-- No Action Selected --</option>";

foreach ($actionOptions as $actionId => $desc) {
    if (!is_numeric($actionId)) continue; // <-- Skip the *_color entries
    $selected = ($actionId == $currentActionId) ? "selected" : "";
    echo "<option value='$actionId' $selected>$desc</option>";
}
echo "</select>";
if (!empty($currentActionDate)) {
    echo "<div style='font-size:10px;color:#555;'>Set on: ".date("d M Y",$currentActionDate)."</div>";
}

echo "</td>";

    echo "</tr>";
}

echo "</table>";

?>
<div id='test2'>Test Debug Area</div>

<style>
#test {
    margin-top: 20px;
    padding: 10px;
    font-family: monospace;
    font-size: 13px;
    background: #f8f8f8;
    border: 1px solid #ccc;
    white-space: pre-wrap;
}
</style>

</body></html>