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

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

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

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

// GET DATA
$startDate = $_POST['start_date'] ?? date('Y-01-01');
$endDate   = $_POST['end_date'] ?? date('Y-m-t');
$branchId  = $_POST['branch_id'] ?? null;
if ($branchId === 'all' || $branchId === '' || $branchId === null) {
    $branchId = null;
} else {
    $branchId = (int)$branchId;
}

// SALES
$salesData = $sales->getSalesForPeriod($startDate, $endDate, $branchId);

$totalSales = 0;
foreach ($salesData as $sale) {
    $totalSales += $sale['total_price'];
}

if ($branchId) {
    $layBuyStats = $laybuy->getBranchLayBuyStats($branchId, $startDate, $endDate);
    foreach ($layBuyStats as $layBuyPayment) {
        $totalSales += (float)($layBuyPayment['body_amount'] ?? 0);
    }
} else {
    foreach ($branch->getAllBranches()->fetchAll(PDO::FETCH_ASSOC) as $b) {
        $layBuyStats = $laybuy->getBranchLayBuyStats($b['branch_id'], $startDate, $endDate);
        foreach ($layBuyStats as $layBuyPayment) {
            $totalSales += (float)($layBuyPayment['body_amount'] ?? 0);
        }
    }
}

// EXPENSES
$totalExpenses = $expense->getTotalExpenses($startDate, $endDate, $branchId);

// BRANCH DATA
$branches = $branch->getAllBranches()->fetchAll(PDO::FETCH_ASSOC);

$branchLabels = [];
$branchSales = [];
$branchExpenses = [];
$branchProfits = [];

foreach ($branches as $b) {

    if ($branchId && $b['branch_id'] != $branchId) continue;

    $branchLabels[] = $b['branch_name'];

    $salesData = $sales->getSalesByBranch($b['branch_id'], $startDate, $endDate);

    $total = 0;
    foreach ($salesData as $s) {
        $total += $s['total_price'];
    }

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

    $branchSales[] = $total;

    $exp = $expense->getBranchExpenses($b['branch_id'], $startDate, $endDate);
    $branchExpenses[] = $exp;

    $branchProfits[] = ($total * $profitRate) - $exp;
}

// RETURN JSON
echo json_encode([
    'totalSales' => $totalSales,
    'totalExpenses' => $totalExpenses,
    'branchLabels' => $branchLabels,
    'branchSales' => $branchSales,
    'branchExpenses' => $branchExpenses,
    'branchProfits' => $branchProfits
]);
