<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/dashboard_helper.php';


$database = new Database();
$conn = $database->getConnection();


require_once __DIR__ . '/../../classes/Sales.php';
require_once __DIR__ . '/../../includes/auth.php';

$sales = new Sales($conn);
$auth = new Auth($conn);


$userRole = $_SESSION['role'] ?? '';
$userId = $_SESSION['user_id'] ?? null;
$userBranchId = $userId ? $auth->getUserBranch($userId) : null;


if (!$userId) {
    header('Location: ../../login.php');
    exit();
}


$canSelectBranch = $auth->isSuperAdmin($userId) || $auth->isWarehousePersonnel($userId);


error_log("Top Selling Items - User Role Check:");
error_log("  User ID: $userId");
error_log("  Session Role: $userRole");
error_log("  isSuperAdmin: " . ($auth->isSuperAdmin($userId) ? 'YES' : 'NO'));
error_log("  isWarehousePersonnel: " . ($auth->isWarehousePersonnel($userId) ? 'YES' : 'NO'));
error_log("  canSelectBranch: " . ($canSelectBranch ? 'YES' : 'NO'));

$selectedBranchId = $canSelectBranch ? ($_GET['branch_id'] ?? null) : $userBranchId;


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


$branches = [];
if ($canSelectBranch) {
    require_once __DIR__ . '/../../classes/Branch.php';
    $branchClass = new Branch($conn);
    $branchesResult = $branchClass->getAllBranches();
    $branches = $branchesResult ? $branchesResult->fetchAll(PDO::FETCH_ASSOC) : [];
}


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 = array_slice($aggregatedItems, 0, 10);
} else {
    $topItems = [];
}


$totalRevenue = 0;
$totalItems = 0;
foreach ($topItems as $item) {
    $totalRevenue += $item['total_revenue'];
    $totalItems += $item['sales_count'];
}
?>
<?php include '../../includes/header.php'; ?>

<style>
    .top-item-card {
        transition: transform 0.2s;
        border-left: 4px solid #28a745;
    }

    .top-item-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }

    .rank-badge {
        position: absolute;
        top: -10px;
        left: -10px;
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background: linear-gradient(45deg, #28a745, #20c997);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        font-size: 14px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    }

    .revenue-bar {
        height: 8px;
        background: linear-gradient(90deg, #28a745, #20c997);
        border-radius: 4px;
        margin-top: 10px;
    }

    .stats-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }


    .filter-form, .pdf-form {
        pointer-events: all !important;
    }

    .filter-form button, .pdf-form button {
        pointer-events: all !important;
        cursor: pointer !important;
    }
</style>

<script>

document.addEventListener('DOMContentLoaded', function() {

    const filterForm = document.getElementById('filterForm');
    const pdfForm = document.getElementById('pdfForm');

    if (filterForm) {

        filterForm.addEventListener('submit', function(e) {

            console.log('Filter form submitting normally');
        });
    }

    if (pdfForm) {

        pdfForm.addEventListener('submit', function(e) {

            console.log('PDF form submitting normally');
        });
    }


    const filterButton = document.getElementById('filterButton');
    const pdfButton = document.getElementById('pdfButton');

    if (filterButton) {
        filterButton.addEventListener('click', function(e) {
            console.log('Filter button clicked');
        });
    }

    if (pdfButton) {
        pdfButton.addEventListener('click', function(e) {
            console.log('PDF button clicked');
        });
    }
});
</script>

    <div class="row mb-4">
        <div class="col-12">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item">
                        <a href="<?php echo $canSelectBranch ? '../dashboard/admin.php' : '../dashboard/branch.php'; ?>">
                            Dashboard
                        </a>
                    </li>
                    <li class="breadcrumb-item active">Top Selling Items</li>
                </ol>
            </nav>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-12">
            <h2><i class="fas fa-trophy text-warning"></i> Top Selling Items Report</h2>
            <p class="text-muted">Performance analysis of best-selling products</p>
        </div>
    </div>


    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" class="row g-3 filter-form no-ajax" id="filterForm">
                <div class="col-md-3">
                    <label for="start_date" class="form-label">Start Date</label>
                    <input type="date" class="form-control" id="start_date" name="start_date"
                           value="<?php echo htmlspecialchars($startDate); ?>" required>
                </div>
                <div class="col-md-3">
                    <label for="end_date" class="form-label">End Date</label>
                    <input type="date" class="form-control" id="end_date" name="end_date"
                           value="<?php echo htmlspecialchars($endDate); ?>" required>
                </div>
                <?php if ($canSelectBranch): ?>
                <div class="col-md-3">
                    <label for="branch_id" class="form-label">Branch</label>
                    <select class="form-control" id="branch_id" name="branch_id">
                        <option value="">All Branches Combined</option>
                        <?php foreach ($branches as $branch): ?>
                            <option value="<?php echo htmlspecialchars($branch['branch_id']); ?>"
                                    <?php echo ($selectedBranchId == $branch['branch_id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($branch['branch_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <small class="text-muted">Admin/Warehouse access granted</small>
                </div>
                <?php else: ?>
                <div class="col-md-3">
                    <label class="form-label">Branch</label>
                    <div class="form-control bg-light">
                        <?php

                        $stmt = $conn->prepare("SELECT branch_name FROM branches WHERE branch_id = ?");
                        $stmt->execute([$userBranchId]);
                        $branchName = $stmt->fetchColumn() ?: 'Unknown Branch';
                        echo htmlspecialchars($branchName);
                        ?>
                    </div>
                    <small class="text-muted">Branch user - restricted to own branch</small>
                </div>
                <?php endif; ?>
                <div class="col-md-3 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary w-100" id="filterButton">
                        <i class="fas fa-search"></i> Filter Data
                    </button>
                </div>
            </form>
        </div>
    </div>


    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" action="generate_top_selling_pdf.php" target="_blank" class="pdf-form no-ajax" id="pdfForm">
                <input type="hidden" name="start_date" value="<?php echo htmlspecialchars($startDate); ?>">
                <input type="hidden" name="end_date" value="<?php echo htmlspecialchars($endDate); ?>">
                <?php if ($canSelectBranch && $selectedBranchId): ?>
                <input type="hidden" name="branch_id" value="<?php echo htmlspecialchars($selectedBranchId); ?>">
                <?php endif; ?>
                <input type="hidden" name="generate_pdf" value="1">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="mb-0">Generate PDF Report</h6>
                        <small class="text-muted">Export the current filtered data to PDF</small>
                    </div>
                    <button type="submit" class="btn btn-success" id="pdfButton">
                        <i class="fas fa-file-pdf"></i> Generate PDF
                    </button>
                </div>
            </form>
        </div>
    </div>


    <?php if (!empty($topItems)): ?>
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card stats-card text-white">
                <div class="card-body text-center">
                    <i class="fas fa-chart-line fa-2x mb-2"></i>
                    <h4>MWK <?php echo number_format($totalRevenue, 2); ?></h4>
                    <small>Total Revenue</small>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card stats-card text-white">
                <div class="card-body text-center">
                    <i class="fas fa-boxes fa-2x mb-2"></i>
                    <h4><?php echo number_format($totalItems); ?></h4>
                    <small>Total Units Sold</small>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card stats-card text-white">
                <div class="card-body text-center">
                    <i class="fas fa-trophy fa-2x mb-2"></i>
                    <h4><?php echo count($topItems); ?></h4>
                    <small>Top Products</small>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>


    <?php if (empty($topItems)): ?>
        <div class="card">
            <div class="card-body text-center">
                <i class="fas fa-chart-bar fa-4x text-muted mb-3"></i>
                <h4>No Sales Data Found</h4>
                <p class="text-muted">
                    <?php if ($selectedBranchId): ?>
                        No sales data available for the selected period and branch.
                    <?php else: ?>
                        Please select a branch to view top selling items.
                    <?php endif; ?>
                </p>
                <?php if (!$canSelectBranch): ?>
                    <a href="../dashboard/branch.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Back to Dashboard
                    </a>
                <?php endif; ?>
            </div>
        </div>
    <?php else: ?>
        <div class="row">
            <?php
            $rank = 1;
            foreach ($topItems as $item):
            ?>
                <div class="col-md-6 col-lg-4 mb-4">
                    <div class="card top-item-card position-relative">
                        <div class="rank-badge"><?php echo $rank++; ?></div>
                        <div class="card-body">
                            <h5 class="card-title"><?php echo htmlspecialchars(trim((string)$item['item_name'] . (!empty($item['item_details']) ? ' - ' . $item['item_details'] : ''))); ?></h5>

                            <div class="row text-center mb-3">
                                <div class="col-6">
                                    <div class="h4 text-primary mb-0"><?php echo $item['sales_count']; ?></div>
                                    <small class="text-muted">Units Sold</small>
                                </div>
                                <div class="col-6">
                                    <div class="h4 text-success mb-0">MWK <?php echo number_format($item['total_revenue'], 0); ?></div>
                                    <small class="text-muted">Revenue</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>


        <div class="row mt-4">
            <div class="col-12 text-center">
                <button class="btn btn-outline-primary" onclick="window.print()">
                    <i class="fas fa-print"></i> Print Report
                </button>
                <a href="<?php echo $canSelectBranch ? '../dashboard/admin.php' : '../dashboard/branch.php'; ?>" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Back to Dashboard
                </a>
            </div>
        </div>
    <?php endif; ?>
</div>

<style>
@media print {
    .breadcrumb, .btn, .card:not(.top-item-card), nav, .stats-card {
        display: none !important;
    }

    .container {
        margin: 0;
        padding: 0;
    }

    .top-item-card {
        break-inside: avoid;
        margin-bottom: 15px;
    }

    .rank-badge {
        background: #28a745 !important;
        -webkit-print-color-adjust: exact;
    }
}
</style>

<?php include '../../includes/footer.php'; ?>