<?php
// review_product.php

require 'vendor/autoload.php'; // Pastikan path ini benar untuk PhpSpreadsheet
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\Fill;

// Database configuration
define('DB_HOST', 'localhost');
define('DB_USER', 'wiselie_nanda');
define('DB_PASS', 'Clemira123');
define('DB_NAME', 'wiselie_inventory');

// Initialize variables
$error = '';
$performance_data = [];
$warehouses = ['Jakarta', 'Makassar', 'Bali', 'Semarang', 'Bandung', 'Surabaya'];

// Set default period (current month)
$start_date = date('Y-m-01');
$end_date = date('Y-m-t');
if (isset($_GET['start_date'])) {
    $start_date = $_GET['start_date'];
}
if (isset($_GET['end_date'])) {
    $end_date = $_GET['end_date'];
}

// Handle Excel export first
if (isset($_GET['export'])) {
    exportToExcel($start_date, $end_date);
    exit;
}

// Calculate days in period
$days_in_period = (new DateTime($start_date))->diff(new DateTime($end_date))->days + 1;

try {
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    
    if ($conn->connect_error) {
        throw new Exception("Database connection failed: " . $conn->connect_error);
    }

    // Get sales data from awb_data
    $sales_query = "SELECT 
                        part_number,
                        SUM(CASE WHEN loc = 'Jakarta' THEN quantity ELSE 0 END) as jakarta,
                        SUM(CASE WHEN loc = 'Makassar' THEN quantity ELSE 0 END) as makassar,
                        SUM(CASE WHEN loc = 'Bali' THEN quantity ELSE 0 END) as bali,
                        SUM(CASE WHEN loc = 'Semarang' THEN quantity ELSE 0 END) as semarang,
                        SUM(CASE WHEN loc = 'Bandung' THEN quantity ELSE 0 END) as bandung,
                        SUM(CASE WHEN loc = 'Surabaya' THEN quantity ELSE 0 END) as surabaya,
                        SUM(quantity) as total_sales
                    FROM awb_data
                    WHERE date_scan BETWEEN ? AND ?
                    GROUP BY part_number
                    ORDER BY total_sales DESC";
    
    $stmt = $conn->prepare($sales_query);
    $stmt->bind_param("ss", $start_date, $end_date);
    $stmt->execute();
    $result = $stmt->get_result();

    // Get product prices for sales value calculation
    $products = [];
    $product_query = "SELECT part_number, buy_price FROM products WHERE categorie_id = 7"; // Assuming categorie_id 7 is relevant
    $product_result = $conn->query($product_query);
    while ($row = $product_result->fetch_assoc()) {
        $products[$row['part_number']] = $row['buy_price'];
    }

    // Process performance data
    while ($row = $result->fetch_assoc()) {
        $total_sales = $row['total_sales'];
        $daily_sales = $total_sales / $days_in_period;
        
        // Performance classification
        if ($daily_sales >= 5) {
            $performance = 'Fast Moving';
            $performance_class = 'fast-moving';
        } elseif ($daily_sales >= 1) {
            $performance = 'Normal';
            $performance_class = 'normal';
        } else {
            $performance = 'Slow Moving';
            $performance_class = 'slow-moving';
        }
        
        $performance_data[] = [
            'part_number' => $row['part_number'],
            'buy_price' => $products[$row['part_number']] ?? 0,
            'total_sales' => $total_sales,
            'daily_sales' => round($daily_sales, 2),
            'sales_amount' => $total_sales * ($products[$row['part_number']] ?? 0),
            'jakarta' => $row['jakarta'],
            'makassar' => $row['makassar'],
            'bali' => $row['bali'],
            'semarang' => $row['semarang'],
            'bandung' => $row['bandung'],
            'surabaya' => $row['surabaya'],
            'performance' => $performance,
            'performance_class' => $performance_class
        ];
    }

    // --- Mulai Logika Analisis Mendalam ---
    $analysis_summary = [
        'total_products_analyzed' => count($performance_data),
        'fast_moving_count' => 0,
        'normal_moving_count' => 0,
        'slow_moving_count' => 0,
        'top_5_fast_moving' => [],
        'top_5_sales_amount' => [],
        'total_sales_value_all_products' => 0,
        'warehouse_sales_summary' => []
    ];

    // Initialize warehouse sales
    foreach ($warehouses as $wh) {
        $analysis_summary['warehouse_sales_summary'][$wh] = 0;
    }

    // Create a copy of performance_data for sorting, as original is used for display
    $sortable_performance_data = $performance_data;

    foreach ($sortable_performance_data as $item) {
        // Count performance categories
        if ($item['performance'] === 'Fast Moving') {
            $analysis_summary['fast_moving_count']++;
        } elseif ($item['performance'] === 'Normal') {
            $analysis_summary['normal_moving_count']++;
        } else {
            $analysis_summary['slow_moving_count']++;
        }
        
        // Top 5 Sales Amount
        $analysis_summary['total_sales_value_all_products'] += $item['sales_amount'];

        // Warehouse Sales Summary
        foreach ($warehouses as $wh) {
            $analysis_summary['warehouse_sales_summary'][$wh] += $item[strtolower($wh)];
        }
    }

    // Sort for Top 5 Fast Moving (by daily_sales)
    usort($sortable_performance_data, function($a, $b) {
        return $b['daily_sales'] <=> $a['daily_sales'];
    });
    $analysis_summary['top_5_fast_moving'] = array_slice($sortable_performance_data, 0, 5);

    // Re-sort for Top 5 Sales Amount (important to sort again after previous usort)
    usort($sortable_performance_data, function($a, $b) {
        return $b['sales_amount'] <=> $a['sales_amount'];
    });
    $analysis_summary['top_5_sales_amount'] = array_slice($sortable_performance_data, 0, 5);
    
    // Calculate percentages for categories
    if ($analysis_summary['total_products_analyzed'] > 0) {
        $analysis_summary['fast_moving_percentage'] = round(($analysis_summary['fast_moving_count'] / $analysis_summary['total_products_analyzed']) * 100, 2);
        $analysis_summary['normal_moving_percentage'] = round(($analysis_summary['normal_moving_count'] / $analysis_summary['total_products_analyzed']) * 100, 2);
        $analysis_summary['slow_moving_percentage'] = round(($analysis_summary['slow_moving_count'] / $analysis_summary['total_products_analyzed']) * 100, 2);
    } else {
        $analysis_summary['fast_moving_percentage'] = 0;
        $analysis_summary['normal_moving_percentage'] = 0;
        $analysis_summary['slow_moving_percentage'] = 0;
    }

    // Determine best performing warehouse
    $best_warehouse = ['name' => 'N/A', 'sales' => 0];
    if (!empty($analysis_summary['warehouse_sales_summary'])) {
        arsort($analysis_summary['warehouse_sales_summary']); // Sort by value, descending
        $best_warehouse = [
            'name' => key($analysis_summary['warehouse_sales_summary']),
            'sales' => current($analysis_summary['warehouse_sales_summary'])
        ];
    }
    // --- Akhir Logika Analisis Mendalam ---


} catch (Exception $e) {
    $error = $e->getMessage();
} finally {
    if (isset($conn)) $conn->close();
}

function exportToExcel($start_date, $end_date) {
    // Create new database connection for export
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    
    if ($conn->connect_error) {
        die("Database connection failed: " . $conn->connect_error);
    }

    // Calculate days in period
    $days_in_period = (new DateTime($start_date))->diff(new DateTime($end_date))->days + 1;

    // Get sales data for export
    $sales_query = "SELECT 
                        part_number,
                        SUM(CASE WHEN loc = 'Jakarta' THEN quantity ELSE 0 END) as jakarta,
                        SUM(CASE WHEN loc = 'Makassar' THEN quantity ELSE 0 END) as makassar,
                        SUM(CASE WHEN loc = 'Bali' THEN quantity ELSE 0 END) as bali,
                        SUM(CASE WHEN loc = 'Semarang' THEN quantity ELSE 0 END) as semarang,
                        SUM(CASE WHEN loc = 'Bandung' THEN quantity ELSE 0 END) as bandung,
                        SUM(CASE WHEN loc = 'Surabaya' THEN quantity ELSE 0 END) as surabaya,
                        SUM(quantity) as total_sales
                    FROM awb_data
                    WHERE date_scan BETWEEN ? AND ?
                    GROUP BY part_number
                    ORDER BY total_sales DESC";
    
    $stmt = $conn->prepare($sales_query);
    $stmt->bind_param("ss", $start_date, $end_date);
    $stmt->execute();
    $result = $stmt->get_result();

    // Get product prices
    $products = [];
    $product_query = "SELECT part_number, buy_price FROM products WHERE categorie_id = 7";
    $product_result = $conn->query($product_query);
    while ($row = $product_result->fetch_assoc()) {
        $products[$row['part_number']] = $row['buy_price'];
    }

    // Process data for export
    $export_data = [];
    while ($row = $result->fetch_assoc()) {
        $total_sales = $row['total_sales'];
        $daily_sales = $total_sales / $days_in_period;
        
        // Performance classification
        if ($daily_sales >= 5) {
            $performance = 'Fast Moving';
        } elseif ($daily_sales >= 1) {
            $performance = 'Normal';
        } else {
            $performance = 'Slow Moving';
        }
        
        $export_data[] = [
            'part_number' => $row['part_number'],
            'buy_price' => $products[$row['part_number']] ?? 0,
            'total_sales' => $total_sales,
            'daily_sales' => round($daily_sales, 2),
            'sales_amount' => $total_sales * ($products[$row['part_number']] ?? 0),
            'jakarta' => $row['jakarta'],
            'makassar' => $row['makassar'],
            'bali' => $row['bali'],
            'semarang' => $row['semarang'],
            'bandung' => $row['bandung'],
            'surabaya' => $row['surabaya'],
            'performance' => $performance
        ];
    }

    $conn->close();

    if (empty($export_data)) {
        die("No data available for export");
    }
    
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setTitle('Product Performance');
    
    // Report header
    $sheet->mergeCells('A1:M1');
    $sheet->setCellValue('A1', 'PRODUCT PERFORMANCE REPORT - ' . strtoupper(date('F Y', strtotime($start_date))));
    $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
    $sheet->getStyle('A1')->getAlignment()->setHorizontal('center');
    
    $sheet->setCellValue('A2', 'Period: ' . date('d M Y', strtotime($start_date)) . ' - ' . date('d M Y', strtotime($end_date)));
    $sheet->setCellValue('A3', 'Export Date: ' . date('d M Y H:i:s'));
    
    // Column headers
    $headers = [
        'No',
        'Part Number', 
        'Buy Price', 
        'Total Sales', 
        'Daily Sales', 
        'Sales Amount',
        'Jakarta', 
        'Makassar', 
        'Bali', 
        'Semarang', 
        'Bandung', 
        'Surabaya',
        'Category'
    ];
    $sheet->fromArray($headers, null, 'A5');
    
    // Data rows
    $row = 6;
    $no = 1;
    foreach ($export_data as $item) {
        $sheet->setCellValue('A' . $row, $no);
        $sheet->setCellValue('B' . $row, $item['part_number']);
        $sheet->setCellValue('C' . $row, $item['buy_price']);
        $sheet->setCellValue('D' . $row, $item['total_sales']);
        $sheet->setCellValue('E' . $row, $item['daily_sales']);
        $sheet->setCellValue('F' . $row, $item['sales_amount']);
        $sheet->setCellValue('G' . $row, $item['jakarta']);
        $sheet->setCellValue('H' . $row, $item['makassar']);
        $sheet->setCellValue('I' . $row, $item['bali']);
        $sheet->setCellValue('J' . $row, $item['semarang']);
        $sheet->setCellValue('K' . $row, $item['bandung']);
        $sheet->setCellValue('L' . $row, $item['surabaya']);
        $sheet->setCellValue('M' . $row, $item['performance']);
        
        $no++;
        $row++;
    }
    
    // Number formatting
    $sheet->getStyle('C6:C' . ($row-1))->getNumberFormat()->setFormatCode('#,##0.00'); // Buy Price
    $sheet->getStyle('E6:E' . ($row-1))->getNumberFormat()->setFormatCode('#,##0.00'); // Daily Sales
    $sheet->getStyle('F6:F' . ($row-1))->getNumberFormat()->setFormatCode('#,##0.00'); // Sales Amount
    
    // Auto-size columns
    foreach (range('A', 'M') as $col) {
        $sheet->getColumnDimension($col)->setAutoSize(true);
    }
    
    // Column header style
    $headerStyle = [
        'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
        'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '3498db']],
        'alignment' => ['horizontal' => 'center']
    ];
    $sheet->getStyle('A5:M5')->applyFromArray($headerStyle);
    
    // Data borders
    $borderStyle = [
        'borders' => [
            'allBorders' => [
                'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                'color' => ['rgb' => '000000']
            ]
        ]
    ];
    $sheet->getStyle('A5:M' . ($row-1))->applyFromArray($borderStyle);
    
    // Conditional formatting for categories
    $conditionalStyles = [
        'Fast Moving' => 'FF90EE90', // Light green
        'Normal' => 'FFADD8E6',     // Light blue
        'Slow Moving' => 'FFFF9999'  // Light red
    ];
    
    foreach ($conditionalStyles as $text => $color) {
        $conditional = new Conditional();
        $conditional->setConditionType(Conditional::CONDITION_CELLIS);
        $conditional->setOperatorType(Conditional::OPERATOR_EQUAL);
        $conditional->addCondition('"' . $text . '"');
        $conditional->getStyle()->getFill()->setFillType(Fill::FILL_SOLID)
            ->getEndColor()->setARGB($color);
        
        // Apply to the 'Category' column (M)
        $sheet->getStyle('M6:M' . ($row-1))->setConditionalStyles([$conditional]);
    }
    
    // Output the file
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="product_performance_'.date('Ymd_His').'.xlsx"');
    header('Cache-Control: max-age=0');
    
    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');
    exit;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product Performance Review</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 20px;
            color: #333;
        }
        .container {
            max-width: 1600px;
            margin: 0 auto;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            padding: 20px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #2c3e50;
            margin: 0;
        }
        .date-filter {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .date-filter label {
            margin-right: 10px;
            font-weight: bold;
        }
        .date-filter input {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-right: 15px;
        }
        .date-filter button {
            padding: 8px 15px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .export-btn {
            padding: 8px 15px;
            background-color: #2ecc71;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
        }
        .performance-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .performance-table th, 
        .performance-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        .performance-table th {
            background-color: #f2f2f2;
            font-weight: bold;
            position: sticky;
            top: 0;
        }
        .performance-table tr:hover {
            background-color: #f9f9f9;
        }
        .fast-moving {
            color: #27ae60;
            font-weight: bold;
            background-color: #e8f5e9;
        }
        .normal {
            color: #3498db;
            background-color: #e3f2fd;
        }
        .slow-moving {
            color: #e74c3c;
            font-weight: bold;
            background-color: #ffebee;
        }
        .legend {
            display: flex;
            gap: 20px;
            margin: 15px 0;
            padding: 10px;
            background: white;
            border-radius: 5px;
            box-shadow: 0 0 5px rgba(0,0,0,0.1);
        }
        .legend-item {
            display: flex;
            align-items: center;
        }
        .legend-color {
            width: 20px;
            height: 20px;
            margin-right: 8px;
            border: 1px solid #ddd;
        }
        .error-message {
            background-color: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            border: 1px solid #f5c6cb;
        }
        
        /* CSS for Analysis Section */
        .analysis-section {
            background-color: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            margin-top: 30px;
        }
        .analysis-section h2 {
            color: #2c3e50;
            margin-top: 0;
            margin-bottom: 20px;
            border-bottom: 2px solid #eee;
            padding-bottom: 10px;
        }
        .analysis-summary h3 {
            color: #34495e;
            margin-top: 20px;
            margin-bottom: 10px;
        }
        .analysis-summary ul {
            list-style-type: none;
            padding: 0;
            margin-left: 15px;
        }
        .analysis-summary ul li {
            margin-bottom: 8px;
            line-height: 1.4;
        }
        .analysis-summary ol {
            margin-left: 20px;
        }
        .analysis-summary ol li {
            margin-bottom: 5px;
        }
        .analysis-summary p {
            margin-left: 15px;
        }
        /* Specific colors for analysis summary list items if needed, overrides general .fast-moving etc. */
        .analysis-summary .fast-moving {
            color: #27ae60;
            font-weight: bold;
        }
        .analysis-summary .normal {
            color: #3498db;
            font-weight: bold;
        }
        .analysis-summary .slow-moving {
            color: #e74c3c;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Product Performance Review</h1>
            <div class="date-filter">
                <form method="GET" action="">
                    <label for="start_date">Start Date:</label>
                    <input type="date" name="start_date" value="<?= htmlspecialchars($start_date) ?>">
                    
                    <label for="end_date">End Date:</label>
                    <input type="date" name="end_date" value="<?= htmlspecialchars($end_date) ?>">
                    
                    <button type="submit">Filter</button>
                    <a href="?export=1&start_date=<?= $start_date ?>&end_date=<?= $end_date ?>" class="export-btn">Export to Excel</a>
                </form>
                <p style="margin-top: 10px; font-size: 14px; color: #7f8c8d;">
                    Period: <?= htmlspecialchars($start_date) ?> to <?= htmlspecialchars($end_date) ?>
                </p>
            </div>
        </div>
        
        <?php if (!empty($error)): ?>
            <div class="error-message">
                <strong>Error:</strong> <?= htmlspecialchars($error) ?>
            </div>
        <?php endif; ?>
        
        <?php if (empty($performance_data)): ?>
            <div style="background: white; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0,0,0,0.1);">
                <p>No sales data found for the selected period.</p>
            </div>
        <?php else: ?>
            <div class="legend">
                <div class="legend-item">
                    <div class="legend-color" style="background-color: #e8f5e9;"></div>
                    <span>Fast Moving (≥5 sales/day)</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color" style="background-color: #e3f2fd;"></div>
                    <span>Normal (1-4 sales/day)</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color" style="background-color: #ffebee;"></div>
                    <span>Slow Moving (&lt;1 sales/day)</span>
                </div>
            </div>
            
            <div style="overflow-x: auto;">
                <table class="performance-table">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Part Number</th>
                            <th>Buy Price</th>
                            <th>Total Sales</th>
                            <th>Daily Sales</th>
                            <th>Sales Amount</th>
                            <th>Jakarta</th>
                            <th>Makassar</th>
                            <th>Bali</th>
                            <th>Semarang</th>
                            <th>Bandung</th>
                            <th>Surabaya</th>
                            <th>Performance</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $no = 1; foreach ($performance_data as $item): ?>
                            <tr>
                                <td><?= $no ?></td>
                                <td><?= htmlspecialchars($item['part_number']) ?></td>
                                <td><?= number_format($item['buy_price'], 2) ?></td>
                                <td><?= number_format($item['total_sales']) ?></td>
                                <td><?= number_format($item['daily_sales'], 2) ?></td>
                                <td><?= number_format($item['sales_amount'], 2) ?></td>
                                <td><?= number_format($item['jakarta']) ?></td>
                                <td><?= number_format($item['makassar']) ?></td>
                                <td><?= number_format($item['bali']) ?></td>
                                <td><?= number_format($item['semarang']) ?></td>
                                <td><?= number_format($item['bandung']) ?></td>
                                <td><?= number_format($item['surabaya']) ?></td>
                                <td class="<?= $item['performance_class'] ?>"><?= $item['performance'] ?></td>
                            </tr>
                        <?php $no++; endforeach; ?>
                    </tbody>
                </table>
            </div>

            <div class="analysis-section">
                <h2>Analisis Mendalam Kinerja Produk</h2>
                <div class="analysis-summary">
                    <h3>Ringkasan Kategori Performa Produk:</h3>
                    <ul>
                        <li>Total Produk Dianalisis: **<?= htmlspecialchars($analysis_summary['total_products_analyzed']) ?>**</li>
                        <li class="fast-moving">Produk Fast Moving: **<?= htmlspecialchars($analysis_summary['fast_moving_count']) ?>** (<?= htmlspecialchars($analysis_summary['fast_moving_percentage']) ?>%)</li>
                        <li class="normal">Produk Normal: **<?= htmlspecialchars($analysis_summary['normal_moving_count']) ?>** (<?= htmlspecialchars($analysis_summary['normal_moving_percentage']) ?>%)</li>
                        <li class="slow-moving">Produk Slow Moving: **<?= htmlspecialchars($analysis_summary['slow_moving_count']) ?>** (<?= htmlspecialchars($analysis_summary['slow_moving_percentage']) ?>%)</li>
                    </ul>

                    <h3>Produk 5 Teratas (Berdasarkan Rata-rata Penjualan Harian):</h3>
                    <ol>
                        <?php if (!empty($analysis_summary['top_5_fast_moving'])): ?>
                            <?php foreach ($analysis_summary['top_5_fast_moving'] as $item): ?>
                                <li>**<?= htmlspecialchars($item['part_number']) ?>**: <?= number_format($item['daily_sales'], 2) ?> unit/hari (Total Sales: <?= number_format($item['total_sales']) ?>)</li>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <li>Tidak ada data untuk produk fast moving.</li>
                        <?php endif; ?>
                    </ol>

                    <h3>Produk 5 Teratas (Berdasarkan Nilai Penjualan - Sales Amount):</h3>
                    <ol>
                        <?php if (!empty($analysis_summary['top_5_sales_amount'])): ?>
                            <?php foreach ($analysis_summary['top_5_sales_amount'] as $item): ?>
                                <li>**<?= htmlspecialchars($item['part_number']) ?>**: Rp<?= number_format($item['sales_amount'], 2) ?> (Total Sales: <?= number_format($item['total_sales']) ?>)</li>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <li>Tidak ada data untuk nilai penjualan.</li>
                        <?php endif; ?>
                    </ol>

                    <h3>Ringkasan Penjualan per Gudang:</h3>
                    <ul>
                        <?php if (!empty($analysis_summary['warehouse_sales_summary'])): ?>
                            <?php foreach ($analysis_summary['warehouse_sales_summary'] as $warehouse_name => $total_sales_qty): ?>
                                <li>**<?= htmlspecialchars($warehouse_name) ?>**: Total Penjualan <?= number_format($total_sales_qty) ?> unit</li>
                            <?php endforeach; ?>
                            <?php if ($best_warehouse['sales'] > 0): ?>
                                <li style="font-weight: bold;">Gudang Dengan Kinerja Penjualan Terbaik: **<?= htmlspecialchars($best_warehouse['name']) ?>** dengan <?= number_format($best_warehouse['sales']) ?> unit.</li>
                            <?php endif; ?>
                        <?php else: ?>
                            <li>Tidak ada data penjualan per gudang.</li>
                        <?php endif; ?>
                    </ul>

                    <h3>Total Nilai Penjualan Keseluruhan:</h3>
                    <p style="font-size: 1.2em; font-weight: bold;">
                        Rp<?= number_format($analysis_summary['total_sales_value_all_products'], 2) ?>
                    </p>

                    <h3>Saran dan Tindakan:</h3>
                    <ul>
                        <li>**Fokus pada Fast Moving:** Pastikan stok produk-produk ini selalu terpenuhi di semua gudang yang relevan. Pertimbangkan promosi silang (bundling) dengan produk normal/slow moving untuk meningkatkan penjualan keseluruhan.</li>
                        <li>**Evaluasi Produk Slow Moving:** Identifikasi penyebab rendahnya penjualan (misalnya, harga, pemasaran, kualitas, atau tren pasar). Pertimbangkan strategi diskon, promosi khusus, atau bahkan penghapusan stok untuk membebaskan modal dan ruang penyimpanan.</li>
                        <li>**Optimasi Stok Antar Gudang:** Berdasarkan data penjualan per gudang, pertimbangkan untuk mentransfer stok produk dari gudang dengan penjualan rendah ke gudang dengan permintaan tinggi untuk produk tertentu. Ini akan membantu mengurangi biaya penyimpanan dan mencegah kehabisan stok di area permintaan tinggi.</li>
                        <li>**Analisis Tren Berkelanjutan:** Lakukan analisis kinerja produk ini secara berkala (misalnya, mingguan atau bulanan) untuk memantau tren, mengukur efektivitas strategi yang diterapkan, dan membuat penyesuaian yang diperlukan secara proaktif.</li>
                        <li>**Korelasikan dengan Data Lain:** Untuk wawasan yang lebih mendalam, coba korelasikan data penjualan ini dengan data lain seperti biaya pemasaran, ulasan pelanggan, atau siklus hidup produk.</li>
                    </ul>
                </div>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>