<?php
session_start();
require_once '../config/db.php';

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

if (!isset($_SESSION['username']) || $_SESSION['role'] != 'admin') {
    die(json_encode(['success' => false, 'message' => 'Unauthorized']));
}

try {
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (empty($data['date'])) {
        throw new Exception('Date is required');
    }

    // Get detailed financial data following IFRS standards
    $stmt = $pdo->prepare("
        SELECT 
            -- Revenue (IFRS 15)
            SUM(total) as gross_revenue,
            SUM(discount) as revenue_deductions,
            SUM(total - discount) as net_revenue,
            
            -- Cost of Sales (IAS 2)
            SUM(total - profit) as cost_of_goods_sold,
            
            -- Gross Profit
            SUM(profit) as gross_profit,
            
            -- Operating Data
            COUNT(DISTINCT id) as transaction_count,
            
            -- Tax Information (IAS 12)
            SUM(total * 0.07) as vat_collected, -- Assuming 7% VAT
            
            -- Segment Information (IFRS 8)
            SUM(CASE WHEN payment_method1 = 'Cash' OR payment_method2 = 'Cash' 
                THEN COALESCE(payment_amount1, 0) + COALESCE(payment_amount2, 0) 
                ELSE 0 END) as cash_sales,
            
            SUM(CASE WHEN payment_method1 = 'Transfer' OR payment_method2 = 'Transfer' 
                THEN COALESCE(payment_amount1, 0) + COALESCE(payment_amount2, 0) 
                ELSE 0 END) as transfer_sales,
                
            SUM(CASE WHEN payment_method1 = 'POS' OR payment_method2 = 'POS' 
                THEN COALESCE(payment_amount1, 0) + COALESCE(payment_amount2, 0) 
                ELSE 0 END) as pos_sales
                
        FROM sales 
        WHERE DATE(sale_date) = ?
    ");

    $stmt->execute([$data['date']]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($result && $result['gross_revenue'] > 0) {
        // Calculate financial ratios and metrics
        $result['gross_profit_margin'] = ($result['gross_profit'] / $result['gross_revenue']) * 100;
        $result['average_transaction_value'] = $result['gross_revenue'] / $result['transaction_count'];
        
        // Format monetary values to 2 decimal places
        foreach ($result as $key => $value) {
            if (is_numeric($value) && strpos($key, 'count') === false && strpos($key, 'margin') === false) {
                $result[$key] = number_format($value, 2, '.', '');
            }
        }

        echo json_encode([
            'success' => true,
            'data' => [
                'revenue' => [
                    'gross' => $result['gross_revenue'],
                    'deductions' => $result['revenue_deductions'],
                    'net' => $result['net_revenue']
                ],
                'costs' => [
                    'cogs' => $result['cost_of_goods_sold']
                ],
                'profitability' => [
                    'gross_profit' => $result['gross_profit'],
                    'gross_margin_percent' => $result['gross_profit_margin']
                ],
                'tax' => [
                    'vat_collected' => $result['vat_collected']
                ],
                'segment_analysis' => [
                    'cash' => $result['cash_sales'],
                    'transfer' => $result['transfer_sales'],
                    'pos' => $result['pos_sales']
                ],
                'metrics' => [
                    'transaction_count' => $result['transaction_count'],
                    'average_transaction_value' => $result['average_transaction_value']
                ]
            ],
            'meta' => [
                'date' => $data['date'],
                'reporting_standard' => 'IFRS',
                'currency' => 'NGN'
            ]
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'No sales data found for selected date'
        ]);
    }

} catch (Exception $e) {
    error_log("Financial Data Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'code' => 'IFRS_DATA_ERROR'
    ]);
}