<?php
// File 2/6
// Path: api/cash/daily_summary.php
// Table: cash_transactions
// column: direction='IN'/'OUT', transaction_date

header('Content-Type: application/json');
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../auth/check_session.php';

$date = $_GET['date'] ?? date('Y-m-d');
$from = $_GET['from'] ?? $date;
$to   = $_GET['to']   ?? $date;

try {
    $stmt = $pdo->prepare("
        SELECT
            COALESCE(SUM(
                CASE WHEN direction = 'IN' AND is_deleted = 0
                THEN amount ELSE 0 END
            ), 0) AS total_in,
            COALESCE(SUM(
                CASE WHEN direction = 'OUT' AND is_deleted = 0
                THEN amount ELSE 0 END
            ), 0) AS total_out,
            COUNT(
                CASE WHEN is_deleted = 0 THEN 1 END
            ) AS total_tx
        FROM cash_transactions
        WHERE transaction_date BETWEEN ? AND ?
    ");
    $stmt->execute([$from, $to]);
    $row = $stmt->fetch();

    echo json_encode([
        'ok'   => true,
        'data' => [
            'total_in'  => (float) $row['total_in'],
            'total_out' => (float) $row['total_out'],
            'net'       => (float) ($row['total_in'] - $row['total_out']),
            'total_tx'  => (int)   $row['total_tx'],
            'from'      => $from,
            'to'        => $to,
        ]
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'msg' => 'Server error']);
}
