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


// Provera da li je korisnik prijavljen kao admin
if (!is_admin()) {
    header('Location: /admin/login.php');
    exit;
}

// Provera ID-ja porudžbine
$order_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($order_id <= 0) {
    header('Location: /admin/orders/');
    exit;
}

// Dohvatanje podataka o porudžbini
$order = get_row("SELECT * FROM orders WHERE id = ?", [$order_id]);
if (!$order) {
    header('Location: /admin/orders/');
    exit;
}

// Dohvatanje stavki porudžbine
$order_items = get_rows("
    SELECT oi.*, p.name as product_name, p.sku 
    FROM order_items oi
    LEFT JOIN products p ON oi.product_id = p.id
    WHERE oi.order_id = ?
    ORDER BY oi.id ASC
", [$order_id]);

// Procesiranje forme
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validacija osnovnih podataka
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $city = trim($_POST['city'] ?? '');
    $zip = trim($_POST['zip'] ?? '');
    $payment_method = trim($_POST['payment_method'] ?? '');
    $shipping_method = trim($_POST['shipping_method'] ?? '');
    $status = trim($_POST['status'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    
    // Čuvanje starog statusa za poređenje
    $old_status = $order['status'];
    
    // Validacija
    $errors = [];
    
    if (empty($name)) {
        $errors[] = "Ime i prezime je obavezno polje.";
    }
    
    if (empty($address)) {
        $errors[] = "Adresa je obavezno polje.";
    }
    
    if (empty($city)) {
        $errors[] = "Grad je obavezno polje.";
    }
    
    if (!in_array($status, ['pending', 'processing', 'shipped', 'delivered', 'canceled', 'u_obradi'])) {
        $errors[] = "Neispravan status porudžbine.";
    }
    
    // Ako nema grešaka, ažuriramo porudžbinu
    if (empty($errors)) {
        // Ažuriranje osnovnih podataka porudžbine
        $result = execute_query("
            UPDATE orders 
            SET name = ?, email = ?, phone = ?, address = ?, 
                city = ?, zip = ?, payment_method = ?, shipping_method = ?,
                status = ?, notes = ?, updated_at = NOW()
            WHERE id = ?
        ", [
            $name, $email, $phone, $address, 
            $city, $zip, $payment_method, $shipping_method, 
            $status, $notes, $order_id
        ]);
        
        // Procesiranje stavki porudžbine
        if (isset($_POST['item_id']) && is_array($_POST['item_id'])) {
            foreach ($_POST['item_id'] as $key => $item_id) {
                $item_id = intval($item_id);
                $quantity = max(1, intval($_POST['quantity'][$key] ?? 1));
                $price = floatval($_POST['price'][$key] ?? 0);
                
                if ($item_id > 0) {
                    // Ažuriranje postojeće stavke
                    execute_query("
                        UPDATE order_items 
                        SET quantity = ?, price = ?
                        WHERE id = ? AND order_id = ?
                    ", [$quantity, $price, $item_id, $order_id]);
                }
            }
        }
        
        // Preračunavanje ukupne cene
        $total = 0;
        $updated_items = get_rows("SELECT price, quantity FROM order_items WHERE order_id = ?", [$order_id]);
        foreach ($updated_items as $item) {
            $total += $item['price'] * $item['quantity'];
        }
        
        // Ažuriranje ukupne cene
        execute_query("UPDATE orders SET total = ? WHERE id = ?", [$total, $order_id]);
        
        // Provera da li je status promenjen i slanje emaila ako jeste
        if ($status !== $old_status) {
            // Dohvatanje ažurirane porudžbine
            $updated_order = get_row("SELECT * FROM orders WHERE id = ?", [$order_id]);
            
            // Instanciraj email helper
            $email_helper = new EmailHelper();
            
            // Pošalji obaveštenje kupcu o promeni statusa
            $email_helper->sendOrderStatusUpdate($updated_order, $status, $old_status);
        }
        
        // Redirekcija na stranicu za pregled porudžbine
        header("Location: /admin/orders/view.php?id={$order_id}&updated=1");
        exit;
    }
}

// Naslov stranice
$page_title = 'Izmena porudžbine #' . $order['order_number'];

// Uključivanje header-a
require_once '../includes/header.php';
?>

<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Izmena porudžbine</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/admin/">Kontrolna tabla</a></li>
                    <li class="breadcrumb-item"><a href="/admin/orders/">Porudžbine</a></li>
                    <li class="breadcrumb-item"><a href="/admin/orders/view.php?id=<?php echo $order_id; ?>">Porudžbina #<?php echo $order['order_number']; ?></a></li>
                    <li class="breadcrumb-item active">Izmena</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<section class="content">
    <div class="container-fluid">
        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger">
                <h5><i class="icon fas fa-ban"></i> Greške pri validaciji:</h5>
                <ul class="mb-0">
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo $error; ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>
        
        <form action="" method="post">
                <?php echo csrf_token_field(); ?>

            <div class="row">
                <div class="col-md-8">
                    <!-- Osnovni podaci o porudžbini -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Osnovni podaci</h3>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="order_number">Broj porudžbine</label>
                                        <input type="text" class="form-control" id="order_number" value="<?php echo $order['order_number']; ?>" readonly>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="created_at">Datum porudžbine</label>
                                        <input type="text" class="form-control" id="created_at" value="<?php echo date('d.m.Y. H:i', strtotime($order['created_at'])); ?>" readonly>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="status">Status</label>
                                        <select name="status" id="status" class="form-control">
                                            <option value="pending" <?php echo $order['status'] === 'pending' ? 'selected' : ''; ?>>Na čekanju</option>
                                            <option value="processing" <?php echo $order['status'] === 'processing' ? 'selected' : ''; ?>>U obradi</option>
                                            <option value="shipped" <?php echo $order['status'] === 'shipped' ? 'selected' : ''; ?>>Poslato</option>
                                            <option value="delivered" <?php echo $order['status'] === 'delivered' ? 'selected' : ''; ?>>Isporučeno</option>
                                            <option value="canceled" <?php echo $order['status'] === 'canceled' ? 'selected' : ''; ?>>Otkazano</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="total">Ukupan iznos</label>
                                        <input type="text" class="form-control" id="total" value="<?php echo format_price($order['total']); ?>" readonly>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="payment_method">Način plaćanja</label>
                                        <select name="payment_method" id="payment_method" class="form-control">
                                            <option value="cash" <?php echo $order['payment_method'] === 'cash' ? 'selected' : ''; ?>>Gotovina</option>
                                            <option value="bank" <?php echo $order['payment_method'] === 'bank' ? 'selected' : ''; ?>>Uplata na račun</option>
                                            <option value="card" <?php echo $order['payment_method'] === 'card' ? 'selected' : ''; ?>>Platna kartica</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="shipping_method">Način dostave</label>
                                        <select name="shipping_method" id="shipping_method" class="form-control">
    <option value="pickup" <?php echo $order['shipping_method'] === 'pickup' ? 'selected' : ''; ?>>Lično preuzimanje</option>
    <option value="courier" <?php echo $order['shipping_method'] === 'courier' ? 'selected' : ''; ?>>Kurirska služba</option>
    <option value="post" <?php echo $order['shipping_method'] === 'post' ? 'selected' : ''; ?>>Poštom</option>
</select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label for="notes">Napomena</label>
                                <textarea name="notes" id="notes" class="form-control" rows="3"><?php echo htmlspecialchars($order['notes']); ?></textarea>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Stavke porudžbine -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Stavke porudžbine</h3>
                        </div>
                        <div class="card-body p-0">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Proizvod</th>
                                        <th>SKU</th>
                                        <th style="width: 150px">Cena</th>
                                        <th style="width: 100px">Količina</th>
                                        <th style="width: 150px">Ukupno</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($order_items)): ?>
                                        <tr>
                                            <td colspan="5" class="text-center">Nema stavki u porudžbini</td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($order_items as $index => $item): ?>
                                            <tr>
                                                <td>
                                                    <input type="hidden" name="item_id[<?php echo $index; ?>]" value="<?php echo $item['id']; ?>">
                                                    <?php echo htmlspecialchars($item['product_name']); ?>
                                                </td>
                                                <td><?php echo $item['sku']; ?></td>
                                                <td>
                                                    <input type="number" name="price[<?php echo $index; ?>]" class="form-control item-price" value="<?php echo $item['price']; ?>" step="0.01" min="0">
                                                </td>
                                                <td>
                                                    <input type="number" name="quantity[<?php echo $index; ?>]" class="form-control item-quantity" value="<?php echo $item['quantity']; ?>" min="1">
                                                </td>
                                                <td>
                                                    <span class="item-total"><?php echo format_price($item['price'] * $item['quantity']); ?></span>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <!-- Podaci o klijentu -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Podaci o klijentu</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="name">Ime i prezime</label>
                                <input type="text" name="name" id="name" class="form-control" value="<?php echo htmlspecialchars($order['name']); ?>" required>
                            </div>
                            <div class="form-group">
                                <label for="email">Email</label>
                                <input type="email" name="email" id="email" class="form-control" value="<?php echo htmlspecialchars($order['email']); ?>">
                            </div>
                            <div class="form-group">
                                <label for="phone">Telefon</label>
                                <input type="text" name="phone" id="phone" class="form-control" value="<?php echo htmlspecialchars($order['phone']); ?>">
                            </div>
                        </div>
                    </div>
                    
                    <!-- Adresa za dostavu -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Adresa za dostavu</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="address">Adresa</label>
                                <input type="text" name="address" id="address" class="form-control" value="<?php echo htmlspecialchars($order['address']); ?>" required>
                            </div>
                            <div class="form-group">
                                <label for="city">Grad</label>
                                <input type="text" name="city" id="city" class="form-control" value="<?php echo htmlspecialchars($order['city']); ?>" required>
                            </div>
                            <div class="form-group">
                                <label for="zip">Poštanski broj</label>
                                <input type="text" name="zip" id="zip" class="form-control" value="<?php echo htmlspecialchars($order['zip']); ?>">
                            </div>
                        </div>
                    </div>
                    
                    <!-- Dugmad za akcije -->
                    <div class="card">
                        <div class="card-body">
                            <button type="submit" class="btn btn-primary btn-block">Sačuvaj izmene</button>
                            <a href="/admin/orders/view.php?id=<?php echo $order_id; ?>" class="btn btn-default btn-block mt-2">Odustani</a>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</section>

<script>
    // Ažuriranje ukupne cene stavke
    $(document).ready(function() {
        function updateTotals() {
            $('.item-price, .item-quantity').each(function() {
                var row = $(this).closest('tr');
                var price = parseFloat(row.find('.item-price').val()) || 0;
                var quantity = parseInt(row.find('.item-quantity').val()) || 1;
                var total = price * quantity;
                
                // Formatiranje cene
                var formattedTotal = new Intl.NumberFormat('sr-RS', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }).format(total) + ' RSD';
                
                row.find('.item-total').text(formattedTotal);
            });
        }
        
        // Inicijalno ažuriranje
        updateTotals();
        
        // Ažuriranje pri promeni vrednosti
        $('.item-price, .item-quantity').on('change input', updateTotals);
    });
</script>

<?php require_once '../includes/footer.php'; ?>