<?php
require_once 'includes/config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';
require_once 'includes/email_helper.php';

// Provera CSRF tokena
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !verify_csrf_token($_POST['csrf_token'])) {
        security_log('Invalid CSRF token in order processing', 'warning');
        header('Location: /checkout.php?error=security');
        exit;
    }
}

// Provera da li je forma poslata
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: /');
    exit;
}

// Provera da li je korpa prazna
$cart = get_cart();
if (empty($cart)) {
    header('Location: /');  // Preusmjeravanje na početnu
    exit;
}

// Preuzimanje podataka iz forme
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
$email = isset($_POST['email']) ? trim($_POST['email']) : '';
$address = isset($_POST['address']) ? trim($_POST['address']) : '';
$city = isset($_POST['city']) ? trim($_POST['city']) : '';
$zip = isset($_POST['zip']) ? trim($_POST['zip']) : '';
$shipping_method = isset($_POST['shipping_method']) ? $_POST['shipping_method'] : 'courier';
$payment_method = isset($_POST['payment_method']) ? $_POST['payment_method'] : 'cash';
$notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';
$base_price = isset($_POST['base_price']) ? floatval($_POST['base_price']) : 0;
$accessories = isset($_POST['accessories']) ? json_decode($_POST['accessories'], true) : [];

// Validacija obaveznih polja
if (empty($name) || empty($phone) || empty($address) || empty($city) || empty($zip)) {
    header('Location: /checkout.php?error=missing_fields');
    exit;
}

// Generisanje broja porudžbine
$order_number = generate_order_number();

// Izračunavanje konačnih ukupnih iznosa
$cart_total = $base_price;
$accessories_total = 0;

// Izračunavanje ukupne vrednosti dodataka, ako ih ima
if (!empty($accessories)) {
    foreach ($accessories as $accessory_id) {
        $accessory = get_product($accessory_id);
        if ($accessory) {
            $accessory_price = !empty($accessory['sale_price']) ? $accessory['sale_price'] : $accessory['price'];
            $accessories_total += $accessory_price;
        }
    }
}

$grand_total = $cart_total + $accessories_total;

// Kreiranje porudžbine u bazi
try {
    global $conn;
    
    // Započni transakciju
    $conn->beginTransaction();
    
    // Dobavljanje user_id ako je korisnik prijavljen
    $user_id = is_logged_in() ? $_SESSION['user_id'] : null;
    
    // Unos porudžbine u tabelu orders
    $stmt = $conn->prepare("
        INSERT INTO orders (
            user_id,
            order_number, 
            name, 
            email, 
            phone, 
            address, 
            city, 
            zip,
            total,
            shipping_method,
            payment_method,
            notes,
            status,
            created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    
    $stmt->execute([
        $user_id,
        $order_number,
        $name,
        $email,
        $phone,
        $address,
        $city,
        $zip,
        $grand_total,
        $shipping_method,
        $payment_method,
        $notes,
        'pending'
    ]);
    
    $order_id = $conn->lastInsertId();
    
    // Unos stavki porudžbine u tabelu order_items
    $stmt = $conn->prepare("
        INSERT INTO order_items (
            order_id,
            product_id,
            product_name,
            product_sku,
            price,
            quantity
        ) VALUES (?, ?, ?, ?, ?, ?)
    ");
    
    // Čuvanje stavki porudžbine za email notifikacije
    $order_items = [];
    
    // Unos proizvoda iz korpe
    foreach ($cart as $product_id => $quantity) {
        $product = get_product($product_id);
        if ($product) {
            $price = !empty($product['sale_price']) ? $product['sale_price'] : $product['price'];
            $sku = isset($product['sku']) ? $product['sku'] : '';
            
            $stmt->execute([
                $order_id,
                $product_id,
                $product['name'],
                $sku,
                $price,
                $quantity
            ]);
            
            // Dodaj u listu stavki za email
            $order_items[] = [
                'product_id' => $product_id,
                'product_name' => $product['name'],
                'product_sku' => $sku,
                'price' => $price,
                'quantity' => $quantity
            ];
        }
    }
    
    // Unos dodataka kao stavke porudžbine, ako ih ima
    if (!empty($accessories)) {
        foreach ($accessories as $accessory_id) {
            $accessory = get_product($accessory_id);
            if ($accessory) {
                $price = !empty($accessory['sale_price']) ? $accessory['sale_price'] : $accessory['price'];
                $sku = isset($accessory['sku']) ? $accessory['sku'] : '';
                
                $stmt->execute([
                    $order_id,
                    $accessory_id,
                    $accessory['name'],
                    $sku,
                    $price,
                    1 // količina za dodatke je uvek 1
                ]);
                
                // Dodaj u listu stavki za email
                $order_items[] = [
                    'product_id' => $accessory_id,
                    'product_name' => $accessory['name'],
                    'product_sku' => $sku,
                    'price' => $price,
                    'quantity' => 1
                ];
            }
        }
    }
    
    // Potvrdi transakciju
    $conn->commit();
    
    // Dohvati kompletne podatke o porudžbini za email
    $order = get_row("SELECT * FROM orders WHERE id = ?", [$order_id]);
    
    // Instanciraj email helper
    $email_helper = new EmailHelper();
    
    // Pošalji potvrdu kupcu
    $email_helper->sendOrderConfirmationToCustomer($order, $order_items);
    
    // Pošalji obaveštenje prodavcu
    $email_helper->sendNewOrderNotificationToAdmin($order, $order_items);
    
    // Isprazni korpu
    clear_cart();
    
    // Sačuvaj broj porudžbine u sesiji za thank-you stranicu
    $_SESSION['last_order_number'] = $order_number;
    $_SESSION['last_order_total'] = $grand_total;
    $_SESSION['last_order_name'] = $name;
    
    // Preusmeri na thank-you stranicu
    header('Location: /thank-you.php');
    exit;
    
} catch (Exception $e) {
    // Poništi transakciju u slučaju greške
    $conn->rollBack();
    
    // Logiraj grešku
    error_log("Order error: " . $e->getMessage());
    
    // Preusmeri sa greškom
    header('Location: /checkout.php?error=processing');
    exit;
}