<?php
require_once '../init.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $items = isset($_POST['items']) ? json_decode($_POST['items'], true) : [];
    $subtotal = floatval($_POST['subtotal'] ?? 0);
    $tax = floatval($_POST['tax'] ?? 0);
    $discount = floatval($_POST['discount'] ?? 0);
    $totalAmount = floatval($_POST['total'] ?? 0);
    $paymentMethod = $_POST['payment_method'] ?? '';
    
    if (empty($items) || $totalAmount <= 0 || empty($paymentMethod)) {
        $_SESSION['error'] = 'Data transaksi tidak lengkap';
        Helper::redirect('../pos/index.php');
    }
    
    // Process transaction
    $result = $transaction->create($_SESSION['user_id'], $items, $subtotal, $tax, $discount, $paymentMethod);
    
    if ($result['success']) {
        // Clear cart from session
        unset($_SESSION['cart']);
        
        $_SESSION['success'] = 'Transaksi berhasil disimpan. Invoice: ' . $result['invoice_number'];
        Helper::redirect('receipt.php?invoice=' . $result['invoice_number']);
    } else {
        $_SESSION['error'] = $result['message'];
        Helper::redirect('../pos/index.php');
    }
}

Helper::redirect('../pos/index.php');
