<?php

require_once '../../includes/header.php';


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


require_once '../../classes/Sales.php';
require_once '../../classes/Expense.php';
require_once '../../classes/Laybuy.php';
require_once '../../classes/SystemSettings.php';


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


$sales = new Sales($conn);
$expense = new Expense($conn);
$laybuy = new Laybuy($conn);
$systemSettings = new SystemSettings();
$profitRate = $systemSettings->profitRate();


$selectedBranchId = isset($_GET['branch_id']) ? (int)$_GET['branch_id'] : null;


$allBranchesQuery = "SELECT branch_id, branch_name FROM branches WHERE branch_id != 7 ORDER BY branch_name";
$allBranchesStmt = $conn->prepare($allBranchesQuery);
$allBranchesStmt->execute();
$allBranches = $allBranchesStmt->fetchAll(PDO::FETCH_ASSOC);


if ($selectedBranchId) {

    $branches = array_filter($allBranches, function($branch) use ($selectedBranchId) {
        return $branch['branch_id'] == $selectedBranchId;
    });
} else {

    $branches = $allBranches;
}


$branchData = [];
$totalRevenue = 0;
$totalExpenses = 0;


$salesData = $sales->getSalesForPeriod($startDate, $endDate);
foreach ($branches as $branch) {
    $branchId = $branch['branch_id'];
    $branchName = $branch['branch_name'];


    $branchRevenue = 0;
    if (!empty($salesData)) {
        foreach ($salesData as $sale) {
            if ($sale['branch_id'] == $branchId) {
                $branchRevenue += $sale['total_price'];
            }
        }
    }

    $totalLaybuy = 0;
    $layBuyStats = $laybuy->getBranchLayBuyStats($branchId, $startDate, $endDate);
    foreach ($layBuyStats as $layBuyPayment) {
        $totalLaybuy += (float)($layBuyPayment['body_amount'] ?? 0);
    }
    $branchRevenue += $totalLaybuy;


    $branchExpenses = $expense->getTotalExpenses($startDate, $endDate, $branchId);


    $actualBranchRevenue = $branchRevenue * $profitRate;
    $branchProfit = $actualBranchRevenue - $branchExpenses;
    $branchMargin = ($branchRevenue > 0) ? ($branchProfit / $branchRevenue) * 100 : 0;


    $branchData[$branchName] = [
        'revenue' => $branchRevenue,
        'expenses' => $branchExpenses,
        'profit' => $branchProfit,
        'margin' => $branchMargin
    ];


    $totalRevenue += $branchRevenue;
    $totalExpenses += $branchExpenses;
}


$actualRevenue = $totalRevenue * $profitRate;
$totalProfit = $actualRevenue - $totalExpenses;
$profitMargin = ($totalRevenue > 0) ? ($totalProfit / $totalRevenue) * 100 : 0;


if (isset($_POST['btn_filter'])){
	
	$startDate = $_POST['start_date'];
	$endDate = $_POST['end_date'];
	//header("location:login.php?id=3");
	//exit; 
}


?>

<div class="container-fluid mt-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h2><i class="fas fa-chart-line me-2"></i>Profit & Loss Analysis</h2>
                    <p class="text-muted mb-0">Monitor your business performance and financial health</p>
                </div>
                <div class="text-end">
                    <small class="text-muted">
                        Period: <?php echo date('M d, Y', strtotime($startDate)); ?> - <?php echo date('M d, Y', strtotime($endDate)); ?>
                    </small>
                </div>
            </div>
        </div>
    </div>


    <div class="card mb-4">
        <div class="card-header">
            <h5><i class="fas fa-filter me-2"></i>Filter Options</h5>
        </div>
        <div class="card-body">
            <form class="row g-3">
                <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 $startDate; ?>">
                </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 $endDate; ?>">
                </div>
                <div class="col-md-3">
                    <label for="branch_id" class="form-label">Branch</label>
                    <select class="form-select" id="branch_id" name="branch_id">
                        <option value="">All Branches</option>
                        <?php foreach ($allBranches as $branchItem): ?>
                            <option value="<?php echo $branchItem['branch_id']; ?>" <?php echo (isset($_GET['branch_id']) && $_GET['branch_id'] == $branchItem['branch_id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($branchItem['branch_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary w-100" name="btn_filter" onclick="refresh()">
                        <i class="fas fa-search me-2"></i>Apply Filter
                    </button>
                </div>
            </form>
        </div>
    </div>


    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card border-primary">
                <div class="card-body text-center">
                    <div class="text-primary mb-2">
                        <i class="fas fa-chart-line fa-2x"></i>
                    </div>
                    <h5 class="card-title">Total Revenue</h5>
                    <h3 class="text-primary">MWK <?php echo number_format($totalRevenue, 2); ?></h3>
                    <small class="text-muted">Gross Sales</small>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card border-warning">
                <div class="card-body text-center">
                    <div class="text-warning mb-2">
                        <i class="fas fa-receipt fa-2x"></i>
                    </div>
                    <h5 class="card-title">Total Expenses</h5>
                    <h3 class="text-warning">MWK <?php echo number_format($totalExpenses, 2); ?></h3>
                    <small class="text-muted">Operating Costs</small>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card <?php echo ($totalProfit >= 0) ? 'border-success' : 'border-danger'; ?>">
                <div class="card-body text-center">
                    <div class="<?php echo ($totalProfit >= 0) ? 'text-success' : 'text-danger'; ?> mb-2">
                        <i class="fas <?php echo ($totalProfit >= 0) ? 'fa-arrow-trend-up' : 'fa-arrow-trend-down'; ?> fa-2x"></i>
                    </div>
                    <h5 class="card-title">Net Profit/Loss</h5>
                    <h3 class="<?php echo ($totalProfit >= 0) ? 'text-success' : 'text-danger'; ?>">
                        MWK <?php echo number_format($totalProfit, 2); ?>
                    </h3>
                    <small class="<?php echo ($totalProfit >= 0) ? 'text-success' : 'text-danger'; ?>">
                        <?php echo number_format($profitMargin, 2); ?>% Margin
                    </small>
                </div>
            </div>
        </div>
    </div>


    <div class="card mb-4">
        <div class="card-header">
            <h5><i class="fas fa-bar-chart me-2"></i>Profit/Loss by Branch</h5>
        </div>
        <div class="card-body">
            <div style="height: 400px;">
                <canvas id="branchProfitChart"></canvas>
            </div>
        </div>
    </div>


    <div class="card">
        <div class="card-header">
            <h5><i class="fas fa-table me-2"></i>Branch Performance Details</h5>
        </div>
        <div class="card-body">
            <?php if (empty($branchData)): ?>
                <div class="text-center py-4">
                    <i class="fas fa-chart-pie fa-3x text-muted mb-3"></i>
                    <h6 class="text-muted">No Data Available</h6>
                    <p class="text-muted">No data found for the selected period. Please try a different date range.</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-light">
                            <tr>
                                <th><i class="fas fa-store me-2"></i>Branch</th>
                                <th class="text-end"><i class="fas fa-money-bill-wave me-2"></i>Revenue</th>
                                <th class="text-end"><i class="fas fa-receipt me-2"></i>Expenses</th>
                                <th class="text-end"><i class="fas fa-chart-line me-2"></i>Profit/Loss</th>
                                <th class="text-end"><i class="fas fa-percentage me-2"></i>Margin</th>
                                <th class="text-center"><i class="fas fa-flag me-2"></i>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($branchData as $branch => $data): ?>
                                <tr>
                                    <td class="fw-bold"><?php echo htmlspecialchars($branch); ?></td>
                                    <td class="text-end fw-bold">MWK <?php echo number_format($data['revenue'], 2); ?></td>
                                    <td class="text-end fw-bold">MWK <?php echo number_format($data['expenses'], 2); ?></td>
                                    <td class="text-end fw-bold <?php echo ($data['profit'] >= 0) ? 'text-success' : 'text-danger'; ?>">
                                        MWK <?php echo number_format($data['profit'], 2); ?>
                                    </td>
                                    <td class="text-end fw-bold"><?php echo number_format($data['margin'], 2); ?>%</td>
                                    <td class="text-center">
                                        <span class="badge <?php echo ($data['profit'] >= 0) ? 'bg-success' : 'bg-danger'; ?>">
                                            <?php echo ($data['profit'] >= 0) ? 'Profitable' : 'Loss'; ?>
                                        </span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
	function refresh() {
		  var start_date = $("#start_date").val();
		  var end_date = $("#end_date").val();
		  var branch_id = $("#branch_id").val();
		  window.location.assign("profit_loss.php?start_date="+start_date+"&end_date="+end_date+"&branch_id="+branch_id);
		}
    const branchData = <?php echo json_encode($branchData); ?>;

    if (Object.keys(branchData).length > 0) {

        const branchLabels = Object.keys(branchData);
        const branchProfits = Object.values(branchData).map(data => data.profit);
        const branchRevenues = Object.values(branchData).map(data => data.revenue);
        const branchExpenses = Object.values(branchData).map(data => data.expenses);


        const ctx = document.getElementById('branchProfitChart').getContext('2d');

        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: branchLabels,
                datasets: [
                    {
                        label: 'Revenue',
                        data: branchRevenues,
                        backgroundColor: 'rgba(13, 110, 253, 0.8)',
                        borderColor: 'rgba(13, 110, 253, 1)',
                        borderWidth: 1,
                    },
                    {
                        label: 'Expenses',
                        data: branchExpenses,
                        backgroundColor: 'rgba(255, 193, 7, 0.8)',
                        borderColor: 'rgba(255, 193, 7, 1)',
                        borderWidth: 1,
                    },
                    {
                        label: 'Profit/Loss',
                        data: branchProfits,
                        backgroundColor: branchProfits.map(profit =>
                            profit >= 0 ? 'rgba(25, 135, 84, 0.8)' : 'rgba(220, 53, 69, 0.8)'
                        ),
                        borderColor: branchProfits.map(profit =>
                            profit >= 0 ? 'rgba(25, 135, 84, 1)' : 'rgba(220, 53, 69, 1)'
                        ),
                        borderWidth: 1,
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                let label = context.dataset.label || '';
                                if (label) {
                                    label += ': ';
                                }
                                label += 'MWK ' + context.parsed.y.toLocaleString();
                                return label;
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return 'MWK ' + value.toLocaleString();
                            }
                        }
                    }
                }
            }
        });
    } else {

        document.getElementById('branchProfitChart').parentElement.style.display = 'none';
    }
</script>

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