<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName = Branding::companyName();
$companyLogo = Branding::logoUrl();
$companyLogoFile = Branding::logoFilePath();


error_log("generate_top_selling_pdf.php accessed");
error_log("GET params: " . print_r($_GET, true));

require_once '../../vendor/autoload.php';
require_once '../../classes/Database.php';
require_once '../../classes/Sales.php';
require_once '../../classes/Branch.php';


session_start();
error_log("Session user_id: " . ($_SESSION['user_id'] ?? 'none'));
require_once '../../includes/auth.php';
$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);

if (!$auth->isSuperAdmin($_SESSION['user_id']) &&
    !$auth->isWarehousePersonnel($_SESSION['user_id']) &&
    !$auth->isBranchManager($_SESSION['user_id'])) {
    header('Location: /unauthorized.php');
    exit;
}


$startDate = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
$endDate = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-t');
$selectedBranchId = isset($_GET['branch_id']) ? (int)$_GET['branch_id'] : null;


$userId = $_SESSION['user_id'] ?? null;
$canSelectBranch = $auth->isSuperAdmin($userId) || $auth->isWarehousePersonnel($userId);
$userBranchId = $userId ? $auth->getUserBranch($userId) : null;


if (!$canSelectBranch) {
    $selectedBranchId = $userBranchId;
}


$branches = [];
if ($canSelectBranch) {
    $branchClass = new Branch($conn);
    $branchesResult = $branchClass->getAllBranches();
    $branches = $branchesResult ? $branchesResult->fetchAll(PDO::FETCH_ASSOC) : [];
}


$sales = new Sales($conn);
if ($selectedBranchId) {

    $salesStats = $sales->getBranchSalesStats($selectedBranchId, $startDate, $endDate);
    $topItems = $salesStats['top_items'] ?? [];
} elseif ($canSelectBranch) {

    $allTopItems = [];
    foreach ($branches as $branch) {
        $branchStats = $sales->getBranchSalesStats($branch['branch_id'], $startDate, $endDate);
        $branchTopItems = $branchStats['top_items'] ?? [];
        foreach ($branchTopItems as $item) {
            $item['branch_name'] = $branch['branch_name'];
            $allTopItems[] = $item;
        }
    }


    $aggregatedItems = [];
    foreach ($allTopItems as $item) {
        $key = $item['item_name'];
        if (!isset($aggregatedItems[$key])) {
            $aggregatedItems[$key] = [
                'item_name' => $item['item_name'],
                'item_details' => $item['item_details'] ?? '',
                'sales_count' => 0,
                'total_revenue' => 0,
                'branches' => []
            ];
        }
        $aggregatedItems[$key]['sales_count'] += $item['sales_count'];
        $aggregatedItems[$key]['total_revenue'] += $item['total_revenue'];
        if (!in_array($item['branch_name'], $aggregatedItems[$key]['branches'])) {
            $aggregatedItems[$key]['branches'][] = $item['branch_name'];
        }
    }


    usort($aggregatedItems, function($a, $b) {
        return $b['total_revenue'] <=> $a['total_revenue'];
    });
    $topItems = $aggregatedItems;
} else {

    $topItems = [];
}


$branchName = 'All Branches Combined';
if ($selectedBranchId) {
    $stmt = $conn->prepare("SELECT * FROM branches WHERE branch_id = ?");
    $stmt->execute([$selectedBranchId]);
    $reportBranch = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
    $branchName = $reportBranch['branch_name'] ?? 'Unknown Branch';
    $reportBranding = Branding::documentDetailsForBranch($reportBranch);
    $companyName = $reportBranding['name'];
    $companyLogo = $reportBranding['logo'];
    $companyLogoFile = $reportBranding['logo_file'];
}


$totalRevenue = 0;
$totalItems = 0;
foreach ($topItems as $item) {
    $totalRevenue += $item['total_revenue'];
    $totalItems += $item['sales_count'];
}

try {

    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);


$pdf->SetCreator($companyName);
$pdf->SetAuthor($_SESSION['username']);
$pdf->SetTitle('Top Selling Items Report - ' . $branchName);
$pdf->SetSubject('Top Selling Items Report for ' . $branchName);
$pdf->SetKeywords('top selling, items, sales, report, ' . $companyName);


$pdf->SetHeaderData(is_file($companyLogoFile) ? $companyLogoFile : '', 18, $companyName, "Top Selling Items Report\n" . $branchName . "\nPeriod: " . date('M d, Y', strtotime($startDate)) . ' - ' . date('M d, Y', strtotime($endDate)));


$pdf->setHeaderFont([PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN]);
$pdf->setFooterFont([PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA]);


$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);


$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);


$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);


$pdf->SetFont('helvetica', '', 10);


$pdf->AddPage();


$companyDetails = <<<EOD
$companyName
P.O. Box 109, Limbe, Malawi, South East Africa
Tel: +265 (0) 212 273 707 / Cell: +265 (0) 888 737 654
Email: blessvantengani@gmail.com / Web: www.brcomputers.mw
EOD;
$pdf->MultiCell(0, 10, $companyDetails, 0, 'C', 0, 1, '', '', true);
$pdf->Ln(5);


$reportDetails = <<<EOD
<b>Top Selling Items Report</b>
<b>Branch:</b> $branchName
<b>Period:</b> {$startDate} to {$endDate}
<b>Total Items:</b> $totalItems
<b>Total Revenue:</b> MWK {$totalRevenue}
EOD;
$pdf->writeHTML($reportDetails, true, false, true, false, '');
$pdf->Ln(5);


$html = '<table border="1" cellpadding="4">';
$html .= '<tr style="background-color:#f8f9fa;color:#2c3e50;font-weight:bold;">';
$html .= '<th width="8%">Rank</th>';
$html .= '<th width="42%">Item Name</th>';
if (!$selectedBranchId && $canSelectBranch) {
    $html .= '<th width="20%">Branches</th>';
}
$html .= '<th width="15%">Units Sold</th>';
$html .= '<th width="15%">Revenue</th>';
$html .= '</tr>';


if (empty($topItems)) {
    $colspan = $selectedBranchId ? 4 : 5;
    $html .= '<tr><td colspan="' . $colspan . '" style="text-align:center;">No sales data found for the selected period.</td></tr>';
} else {
    $rank = 1;
    foreach ($topItems as $item) {
        $html .= '<tr>';
        $html .= '<td style="text-align:center;font-weight:bold;">' . $rank++ . '</td>';
        $html .= '<td>' . htmlspecialchars(trim((string)$item['item_name'] . (!empty($item['item_details']) ? ' - ' . $item['item_details'] : ''))) . '</td>';
        if (!$selectedBranchId && $canSelectBranch && isset($item['branches'])) {
            $html .= '<td style="text-align:center;">' . htmlspecialchars(implode(', ', $item['branches'])) . '</td>';
        }
        $html .= '<td style="text-align:center;">' . $item['sales_count'] . '</td>';
        $html .= '<td style="text-align:right;">MWK ' . number_format($item['total_revenue'], 2) . '</td>';
        $html .= '</tr>';
    }
}
$html .= '</table>';


$pdf->writeHTML($html, true, false, true, false, '');


$filename = 'Top_Selling_Items_' . str_replace(' ', '_', $branchName) . '_' . date('Ymd', strtotime($startDate)) . '_to_' . date('Ymd', strtotime($endDate)) . '.pdf';
$pdf->Output($filename, 'D');
} catch (Exception $e) {
    echo "Error generating PDF: " . $e->getMessage();
}
?>
