<?php
require_once '../config/db.php';
header('Content-Type: application/json');

date_default_timezone_set('Asia/Colombo');
$today = date('Y-m-d');
$month = date('Y-m');

$response = [
    'summary' => [
        'bill_count' => 0,
        'sale' => 0,
        'income' => 0,
        'profit' => 0,
    ],
    'weekly_profit' => [
        'labels' => [],
        'values' => []
    ],
    'monthly_products' => [
        'labels' => [],
        'values' => []
    ]
];

$stmt = $pdo->prepare("SELECT COUNT(DISTINCT bill_number) AS bill_count FROM selling_data WHERE DATE(entered_date) = ?");
$stmt->execute([$today]);
$response['summary']['bill_count'] = (int)($stmt->fetch()['bill_count'] ?? 0);

$stmt = $pdo->prepare("SELECT
    COALESCE(SUM(purchaing_amount),0) AS sale_total,
    COALESCE(SUM(sell_amount),0) AS income_total,
    COALESCE(SUM(profit),0) AS profit_total
    FROM income_profit_data
    WHERE DATE(entered_date) = ?");
$stmt->execute([$today]);
$sumData = $stmt->fetch();
$response['summary']['sale'] = (float)$sumData['sale_total'];
$response['summary']['income'] = (float)$sumData['income_total'];
$response['summary']['profit'] = (float)$sumData['profit_total'];

$startOfWeek = date('Y-m-d', strtotime('monday this week'));
$endOfWeek = date('Y-m-d', strtotime('sunday this week'));

$weekMap = [];
$period = new DatePeriod(
    new DateTime($startOfWeek),
    new DateInterval('P1D'),
    (new DateTime($endOfWeek))->modify('+1 day')
);
foreach ($period as $date) {
    $formatted = $date->format('Y-n-j');
    $weekMap[$date->format('Y-m-d')] = ['label' => $formatted, 'value' => 0];
}

$stmt = $pdo->prepare("SELECT DATE(entered_date) AS day_date, COALESCE(SUM(profit),0) AS total_profit
    FROM income_profit_data
    WHERE DATE(entered_date) BETWEEN ? AND ?
    GROUP BY DATE(entered_date)
    ORDER BY DATE(entered_date)");
$stmt->execute([$startOfWeek, $endOfWeek]);
foreach ($stmt->fetchAll() as $row) {
    if (isset($weekMap[$row['day_date']])) {
        $weekMap[$row['day_date']]['value'] = (float)$row['total_profit'];
    }
}
foreach ($weekMap as $item) {
    $response['weekly_profit']['labels'][] = $item['label'];
    $response['weekly_profit']['values'][] = $item['value'];
}

$stmt = $pdo->prepare("SELECT product_name, COALESCE(SUM(qty),0) AS total_qty
    FROM billing_data
    WHERE DATE_FORMAT(entered_date, '%Y-%m') = ?
    GROUP BY product_name
    ORDER BY total_qty DESC");
$stmt->execute([$month]);
foreach ($stmt->fetchAll() as $row) {
    $response['monthly_products']['labels'][] = $row['product_name'];
    $response['monthly_products']['values'][] = (float)$row['total_qty'];
}

echo json_encode($response);