<?php
include '../config.php';

header('Content-Type: application/json');

try {
    // Opening cash for today
    $opening_cash = 0;
    $stmt = $conn->prepare("SELECT amount FROM opening_cash WHERE cash_date = CURDATE()");
    if ($stmt) {
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        if ($row) {
            $opening_cash = floatval($row['amount']);
        }
    }
    // Today's sales
    $today_sales = $conn->query("
        SELECT COALESCE(SUM(total_amount), 0) as total 
        FROM sales 
        WHERE DATE(sale_date) = CURDATE()
    ")->fetch_assoc()['total'];
    
    // Total products
    $total_products = $conn->query("SELECT COUNT(*) as count FROM products")->fetch_assoc()['count'];
    
    // Low stock products (less than 10)
    $low_stock = $conn->query("SELECT COUNT(*) as count FROM products WHERE stock < 10")->fetch_assoc()['count'];
    
    // Total customers
    $total_customers = $conn->query("SELECT COUNT(*) as count FROM customers")->fetch_assoc()['count'];
    
    echo json_encode([
        'todaySales' => number_format($today_sales, 2),
        'totalProducts' => $total_products,
        'lowStock' => $low_stock,
        'totalCustomers' => $total_customers,
        'openingCash' => $opening_cash
    ]);
    
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?>
