<?php
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/functions.php';

header('Content-Type: application/json; charset=utf-8');

try {
  $totalProducts = (int)$pdo->query("SELECT COUNT(*) FROM products")->fetchColumn();
  $lowStockThreshold = 5;
  $stmt = $pdo->prepare("SELECT COUNT(*) FROM products WHERE stock <= ?");
  $stmt->execute([$lowStockThreshold]);
  $lowStockCount = (int)$stmt->fetchColumn();
  $totalCustomers = (int)$pdo->query("SELECT COUNT(*) FROM customers")->fetchColumn();

  $stmt = $pdo->prepare("SELECT COUNT(*) as invoices_count, COALESCE(SUM(total),0) as sales_sum, COALESCE(SUM(profit),0) as profit_sum FROM sales WHERE DATE(created_at) = CURDATE()");
  $stmt->execute();
  $row = $stmt->fetch(PDO::FETCH_ASSOC);

  $todayInvoices = (int)($row['invoices_count'] ?? 0);
  $todaySales = (float)($row['sales_sum'] ?? 0);
  $todayProfit = (float)($row['profit_sum'] ?? 0);

  if(function_exists('getCashSummary')){
    $c = getCashSummary($pdo, date('Y-m-d'), date('Y-m-d'));
    $cashIn = (float)($c['in'] ?? 0);
    $cashOut = (float)($c['out'] ?? 0);
    $cashBalance = (float)($c['balance'] ?? 0);
  } else { $cashIn=$cashOut=$cashBalance=0.0; }

  echo json_encode([
    'ok'=>1,
    'todayInvoices'=>$todayInvoices,
    'todaySales'=>$todaySales,
    'todayProfit'=>$todayProfit,
    'totalProducts'=>$totalProducts,
    'lowStockCount'=>$lowStockCount,
    'totalCustomers'=>$totalCustomers,
    'cashIn'=>$cashIn,
    'cashOut'=>$cashOut,
    'cashBalance'=>$cashBalance,
    'time'=>date('Y-m-d H:i:s')
  ]);
} catch(Exception $e){
  echo json_encode(['ok'=>0,'error'=>$e->getMessage()]);
}
