<?php
require_once '../config/init.php';
require_once '../includes/auth.php';
requireAuth();

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

try {
    $db = getDB();
    $response = ['success' => false, 'message' => '', 'data' => null];

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $invoice_id = $_POST['invoice_id'] ?? 0;
        
        // Begin transaction
        $db->exec('BEGIN');
        
        // Update invoice status
        $stmt = $db->prepare('UPDATE invoices SET status = "paid", payment_date = CURRENT_DATE WHERE id = :id');
        $stmt->bindValue(':id', $invoice_id, SQLITE3_INTEGER);
        $stmt->execute();

        // Get updated invoice data
        $stmt = $db->prepare('
            SELECT 
                i.id,
                i.consumption_id,
                s.meter_number,
                s.full_name,
                s.family_members,
                c.previous_reading,
                c.current_reading,
                (c.current_reading - c.previous_reading) as consumption,
                i.fixed_fees,
                i.collective_entitlement_amount,
                i.consumption_amount,
                i.penalties,
                i.total_amount,
                c.reading_date,
                i.status,
                i.payment_date
            FROM invoices i
            JOIN consumption c ON i.consumption_id = c.id
            JOIN subscribers s ON i.subscriber_id = s.id
            WHERE i.id = :id
        ');
        $stmt->bindValue(':id', $invoice_id, SQLITE3_INTEGER);
        $result = $stmt->execute();
        $invoice = $result->fetchArray(SQLITE3_ASSOC);

        // Get updated summary statistics
        $stmt = $db->prepare('
            SELECT 
                SUM(total_amount) as total_amount,
                SUM(CASE WHEN status = "paid" THEN total_amount ELSE 0 END) as total_paid,
                SUM(CASE WHEN status != "paid" THEN total_amount ELSE 0 END) as total_unpaid,
                SUM(
                    CASE 
                        WHEN c.reading_date >= :start_date AND c.reading_date <= :end_date 
                        THEN (c.current_reading - c.previous_reading)
                        ELSE 0 
                    END
                ) as total_consumption
            FROM invoices i
            JOIN consumption c ON i.consumption_id = c.id
            WHERE c.reading_date BETWEEN :start_date AND :end_date
        ');
        $stmt->bindValue(':start_date', $_POST['start_date'], SQLITE3_TEXT);
        $stmt->bindValue(':end_date', $_POST['end_date'], SQLITE3_TEXT);
        $result = $stmt->execute();
        $summary = $result->fetchArray(SQLITE3_ASSOC);

        $db->exec('COMMIT');

        // Log the activity
        logActivity('تسديد فاتورة', "رقم الفاتورة: $invoice_id");

        $response['success'] = true;
        $response['message'] = 'تم تحديث حالة الفاتورة بنجاح';
        $response['data'] = [
            'invoice' => $invoice,
            'summary' => $summary
        ];
    }
} catch (Exception $e) {
    $db->exec('ROLLBACK');
    $response['message'] = 'حدث خطأ أثناء تحديث حالة الفاتورة: ' . $e->getMessage();
}

echo json_encode($response);
