<?php
require_once '../../includes/config.php';
require_once '../../includes/db.php';
require_once '../../includes/functions.php';
require_once '../includes/admin-functions.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;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_status') {
    $new_status = isset($_POST['status']) ? trim($_POST['status']) : '';
    
    // Validacija statusa
    $valid_statuses = ['pending', 'processing', 'shipped', 'delivered', 'canceled', 'u_obradi'];
    
    if (in_array($new_status, $valid_statuses)) {
        // Korišćenje funkcije execute_query za ažuriranje
        $result = execute_query("UPDATE orders SET status = ?, updated_at = NOW() WHERE id = ?", [$new_status, $order_id]);
        
        if ($result) {
            // Uspešno ažuriranje
            header("Location: /admin/orders/view.php?id={$order_id}&status_updated=1");
            exit;
        } else {
            $error_message = "Greška prilikom ažuriranja statusa porudžbine.";
        }
    } else {
        $error_message = "Neispravan status porudžbine.";
    }
}

// Provera da li je status ažuriran
$status_updated = isset($_GET['status_updated']) && $_GET['status_updated'] == 1;

// 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]);

// Naslov stranice
$page_title = 'Pregled 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">Pregled 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 active">Pregled porudžbine #<?php echo $order['order_number']; ?></li>
                </ol>
            </div>
        </div>
    </div>
</div>

<section class="content">
    <div class="container-fluid">
        <!-- Prikaz poruka -->
        <?php if (function_exists('display_flash_messages')): ?>
            <?php display_flash_messages(); ?>
        <?php endif; ?>
        
        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger"><?php echo $error_message; ?></div>
        <?php endif; ?>
        
        <?php if ($status_updated): ?>
            <div class="alert alert-success">Status porudžbine je uspešno ažuriran.</div>
        <?php endif; ?>
        
        <div class="row">
            <div class="col-md-8">
                <!-- Osnovni podaci o porudžbini -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Porudžbina #<?php echo $order['order_number']; ?></h3>
                        <div class="card-tools">
                            <a href="/admin/orders/edit.php?id=<?php echo $order['id']; ?>" class="btn btn-primary btn-sm">
                                <i class="fas fa-edit"></i> Izmeni
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <p><strong>Broj porudžbine:</strong> <?php echo $order['order_number']; ?></p>
                                <p><strong>Datum porudžbine:</strong> <?php echo date('d.m.Y. H:i', strtotime($order['created_at'])); ?></p>
                                <p>
                                    <strong>Status:</strong> 
                                    <span class="badge badge-<?php echo get_order_status_class($order['status']); ?>">
                                        <?php echo get_order_status_name($order['status']); ?>
                                    </span>
                                </p>
                                <p><strong>Način plaćanja:</strong> <?php echo get_payment_method_name($order['payment_method']); ?></p>
<p><strong>Način dostave:</strong> <?php echo get_shipping_method_name($order['shipping_method']); ?></p>
                            </div>
                            <div class="col-md-6">
                                <p><strong>Ukupno:</strong> <?php echo format_price($order['total']); ?></p>
                                <?php if (!empty($order['notes'])): ?>
                                <p><strong>Napomena:</strong> <?php echo nl2br(htmlspecialchars($order['notes'])); ?></p>
                                <?php endif; ?>
                            </div>
                        </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 style="width: 50px">#</th>
                                    <th>Proizvod</th>
                                    <th>SKU</th>
                                    <th>Cena</th>
                                    <th style="width: 80px">Količina</th>
                                    <th>Ukupno</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($order_items)): ?>
                                    <tr>
                                        <td colspan="6" class="text-center">Nema stavki u porudžbini</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($order_items as $index => $item): ?>
                                        <tr>
                                            <td><?php echo $index + 1; ?></td>
                                            <td>
                                                <a href="/admin/products/edit.php?id=<?php echo $item['product_id']; ?>">
                                                    <?php echo htmlspecialchars($item['product_name']); ?>
                                                </a>
                                            </td>
                                            <td><?php echo $item['sku']; ?></td>
                                            <td><?php echo format_price($item['price']); ?></td>
                                            <td><?php echo $item['quantity']; ?></td>
                                            <td><?php echo format_price($item['price'] * $item['quantity']); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <th colspan="5" class="text-right">Ukupno:</th>
                                    <th><?php echo format_price($order['total']); ?></th>
                                </tr>
                            </tfoot>
                        </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">
                        <p><strong>Ime i prezime:</strong> <?php echo htmlspecialchars($order['name']); ?></p>
                        <?php if (!empty($order['email'])): ?>
                        <p><strong>Email:</strong> <a href="mailto:<?php echo $order['email']; ?>"><?php echo $order['email']; ?></a></p>
                        <?php endif; ?>
                        <?php if (!empty($order['phone'])): ?>
                        <p><strong>Telefon:</strong> <a href="tel:<?php echo $order['phone']; ?>"><?php echo $order['phone']; ?></a></p>
                        <?php endif; ?>
                    </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">
                        <address>
                            <?php echo htmlspecialchars($order['address']); ?><br>
                            <?php echo htmlspecialchars($order['city']); ?>, <?php echo $order['zip']; ?><br>
                            Srbija
                        </address>
                    </div>
                </div>
                
                <!-- Promeni status -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Promeni status</h3>
                    </div>
                    <div class="card-body">
                        <form action="" method="post">
                            <input type="hidden" name="action" value="update_status">
                            
                            <div class="form-group">
                                <select name="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>
                            
                            <button type="submit" class="btn btn-primary btn-block">Ažuriraj status</button>
                        </form>
                    </div>
                </div>
                
                <!-- Akcije -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Akcije</h3>
                    </div>
                    <div class="card-body">
                        <div class="btn-group-vertical w-100">
                            <a href="/admin/orders/invoice.php?id=<?php echo $order['id']; ?>" class="btn btn-default mb-2" target="_blank">
                                <i class="fas fa-file-invoice"></i> Pregled računa
                            </a>
                            <a href="/admin/orders/print.php?id=<?php echo $order['id']; ?>" class="btn btn-default mb-2" target="_blank">
                                <i class="fas fa-print"></i> Štampaj porudžbinu
                            </a>
                            <a href="/admin/orders/send-email.php?id=<?php echo $order['id']; ?>" class="btn btn-default mb-2">
                                <i class="fas fa-envelope"></i> Pošalji email klijentu
                            </a>
                            <a href="/admin/orders/delete.php?id=<?php echo $order['id']; ?>" class="btn btn-danger" onclick="return confirm('Da li ste sigurni da želite da obrišete ovu porudžbinu?');">
                                <i class="fas fa-trash"></i> Obriši porudžbinu
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

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