<?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;
}

// Paginacija
$current_page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$items_per_page = 20;
$offset = ($current_page - 1) * $items_per_page;

// Filteri
$status = isset($_GET['status']) ? $_GET['status'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// Izgradnja upita
$conditions = [];
$params = [];

if (!empty($status) && in_array($status, ['pending', 'processing', 'shipped', 'delivered', 'canceled'])) {
    $conditions[] = "o.status = ?";
    $params[] = $status;
}

if (!empty($date_from)) {
    $conditions[] = "o.created_at >= ?";
    $params[] = $date_from . " 00:00:00";
}

if (!empty($date_to)) {
    $conditions[] = "o.created_at <= ?";
    $params[] = $date_to . " 23:59:59";
}

if (!empty($search)) {
    $conditions[] = "(o.order_number LIKE ? OR o.name LIKE ? OR o.email LIKE ? OR o.phone LIKE ?)";
    $params[] = "%{$search}%";
    $params[] = "%{$search}%";
    $params[] = "%{$search}%";
    $params[] = "%{$search}%";
}

$where_clause = !empty($conditions) ? "WHERE " . implode(" AND ", $conditions) : "";

// Ukupan broj porudžbina
$count_sql = "SELECT COUNT(*) as count FROM orders o {$where_clause}";
$total_orders = get_row($count_sql, $params)['count'];
$total_pages = ceil($total_orders / $items_per_page);

// Sortiranje
$sort_column = isset($_GET['sort']) ? $_GET['sort'] : 'created_at';
$sort_order = isset($_GET['order']) && $_GET['order'] === 'asc' ? 'ASC' : 'DESC';

// Dozvoljene kolone za sortiranje
$allowed_columns = ['id', 'order_number', 'name', 'total', 'status', 'created_at'];
if (!in_array($sort_column, $allowed_columns)) {
    $sort_column = 'created_at';
}

// Dohvatanje porudžbina
$sql = "
    SELECT o.*, 
           (SELECT COUNT(*) FROM order_items oi WHERE oi.order_id = o.id) as item_count
    FROM orders o
    {$where_clause}
    ORDER BY o.{$sort_column} {$sort_order}
    LIMIT {$offset}, {$items_per_page}
";

$orders = get_rows($sql, $params);

// Formatiranje URL-a za sortiranje i paginaciju
$filter_params = [];
if (!empty($status)) $filter_params[] = "status=" . urlencode($status);
if (!empty($date_from)) $filter_params[] = "date_from=" . urlencode($date_from);
if (!empty($date_to)) $filter_params[] = "date_to=" . urlencode($date_to);
if (!empty($search)) $filter_params[] = "search=" . urlencode($search);

$base_url = "?" . implode("&", $filter_params);
if (!empty($filter_params)) $base_url .= "&";

// Dohvatanje statistike porudžbina
$order_stats = [
    'total' => get_row("SELECT COUNT(*) as count FROM orders")['count'],
    'pending' => get_row("SELECT COUNT(*) as count FROM orders WHERE status = 'pending'")['count'],
    'processing' => get_row("SELECT COUNT(*) as count FROM orders WHERE status = 'processing'")['count'],
    'shipped' => get_row("SELECT COUNT(*) as count FROM orders WHERE status = 'shipped'")['count'],
    'delivered' => get_row("SELECT COUNT(*) as count FROM orders WHERE status = 'delivered'")['count'],
    'canceled' => get_row("SELECT COUNT(*) as count FROM orders WHERE status = 'canceled'")['count'],
    'today' => get_row("SELECT COUNT(*) as count FROM orders WHERE DATE(created_at) = CURDATE()")['count'],
    'this_month' => get_row("SELECT COUNT(*) as count FROM orders WHERE MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())")['count'],
    'total_sales' => get_row("SELECT SUM(total) as sum FROM orders WHERE status != 'canceled'")['sum'] ?? 0,
];

// Naslov stranice
$page_title = 'Porudžbine';

// 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">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 active">Porudžbine</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<section class="content">
    <div class="container-fluid">
        <!-- Statistika porudžbina -->
        <div class="row">
            <div class="col-12 col-sm-6 col-md-3">
                <div class="info-box">
                    <span class="info-box-icon bg-info"><i class="fas fa-shopping-cart"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Ukupno porudžbina</span>
                        <span class="info-box-number"><?php echo $order_stats['total']; ?></span>
                    </div>
                </div>
            </div>
            <div class="col-12 col-sm-6 col-md-3">
                <div class="info-box">
                    <span class="info-box-icon bg-success"><i class="fas fa-money-bill-alt"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Ukupna prodaja</span>
                        <span class="info-box-number"><?php echo format_price($order_stats['total_sales']); ?></span>
                    </div>
                </div>
            </div>
            <div class="col-12 col-sm-6 col-md-3">
                <div class="info-box">
                    <span class="info-box-icon bg-warning"><i class="fas fa-clock"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Na čekanju</span>
                        <span class="info-box-number"><?php echo $order_stats['pending']; ?></span>
                    </div>
                </div>
            </div>
            <div class="col-12 col-sm-6 col-md-3">
                <div class="info-box">
                    <span class="info-box-icon bg-danger"><i class="fas fa-calendar-day"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Danas</span>
                        <span class="info-box-number"><?php echo $order_stats['today']; ?></span>
                    </div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Lista porudžbina</h3>
            </div>
            
            <div class="card-body">
                <!-- Filteri -->
                <form action="" method="get" class="mb-4">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>Status</label>
                                <select name="status" class="form-control">
                                    <option value="">Svi statusi</option>
                                    <option value="pending" <?php echo $status === 'pending' ? 'selected' : ''; ?>>Na čekanju</option>
                                    <option value="processing" <?php echo $status === 'processing' ? 'selected' : ''; ?>>U obradi</option>
                                    <option value="shipped" <?php echo $status === 'shipped' ? 'selected' : ''; ?>>Poslato</option>
                                    <option value="delivered" <?php echo $status === 'delivered' ? 'selected' : ''; ?>>Isporučeno</option>
                                    <option value="canceled" <?php echo $status === 'canceled' ? 'selected' : ''; ?>>Otkazano</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Od datuma</label>
                                <input type="date" name="date_from" class="form-control" value="<?php echo $date_from; ?>">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Do datuma</label>
                                <input type="date" name="date_to" class="form-control" value="<?php echo $date_to; ?>">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>Pretraga</label>
                                <input type="text" name="search" class="form-control" placeholder="Broj porudžbine, ime, email..." value="<?php echo htmlspecialchars($search); ?>">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>&nbsp;</label>
                                <button type="submit" class="btn btn-primary btn-block">Filtriraj</button>
                            </div>
                        </div>
                    </div>
                </form>
                
                <!-- Status tabovi -->
                <div class="d-flex justify-content-between align-items-center flex-wrap mb-3">
                    <ul class="nav nav-tabs">
                        <li class="nav-item">
                            <a class="nav-link <?php echo empty($status) ? 'active' : ''; ?>" href="<?php echo empty($status) ? '#' : '?' . http_build_query(array_diff_key($_GET, ['status' => '', 'page' => ''])); ?>">
                                Sve (<?php echo $order_stats['total']; ?>)
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?php echo $status === 'pending' ? 'active' : ''; ?>" href="<?php echo $status === 'pending' ? '#' : '?status=pending&' . http_build_query(array_diff_key($_GET, ['status' => '', 'page' => ''])); ?>">
                                Na čekanju (<?php echo $order_stats['pending']; ?>)
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?php echo $status === 'processing' ? 'active' : ''; ?>" href="<?php echo $status === 'processing' ? '#' : '?status=processing&' . http_build_query(array_diff_key($_GET, ['status' => '', 'page' => ''])); ?>">
                                U obradi (<?php echo $order_stats['processing']; ?>)
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?php echo $status === 'shipped' ? 'active' : ''; ?>" href="<?php echo $status === 'shipped' ? '#' : '?status=shipped&' . http_build_query(array_diff_key($_GET, ['status' => '', 'page' => ''])); ?>">
                                Poslato (<?php echo $order_stats['shipped']; ?>)
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?php echo $status === 'delivered' ? 'active' : ''; ?>" href="<?php echo $status === 'delivered' ? '#' : '?status=delivered&' . http_build_query(array_diff_key($_GET, ['status' => '', 'page' => ''])); ?>">
                                Isporučeno (<?php echo $order_stats['delivered']; ?>)
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?php echo $status === 'canceled' ? 'active' : ''; ?>" href="<?php echo $status === 'canceled' ? '#' : '?status=canceled&' . http_build_query(array_diff_key($_GET, ['status' => '', 'page' => ''])); ?>">
                                Otkazano (<?php echo $order_stats['canceled']; ?>)
                            </a>
                        </li>
                    </ul>
                </div>
                
                <!-- Tabela porudžbina -->
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th width="60">
                                    <a href="<?php echo $base_url; ?>sort=id&order=<?php echo $sort_column === 'id' && $sort_order === 'DESC' ? 'asc' : 'desc'; ?>">
                                        ID
                                        <?php if ($sort_column === 'id'): ?>
                                            <i class="fas fa-sort-<?php echo $sort_order === 'DESC' ? 'down' : 'up'; ?>"></i>
                                        <?php endif; ?>
                                    </a>
                                </th>
                                <th>
                                    <a href="<?php echo $base_url; ?>sort=order_number&order=<?php echo $sort_column === 'order_number' && $sort_order === 'DESC' ? 'asc' : 'desc'; ?>">
                                        Broj porudžbine
                                        <?php if ($sort_column === 'order_number'): ?>
                                            <i class="fas fa-sort-<?php echo $sort_order === 'DESC' ? 'down' : 'up'; ?>"></i>
                                        <?php endif; ?>
                                    </a>
                                </th>
                                <th>
                                    <a href="<?php echo $base_url; ?>sort=name&order=<?php echo $sort_column === 'name' && $sort_order === 'DESC' ? 'asc' : 'desc'; ?>">
                                        Klijent
                                        <?php if ($sort_column === 'name'): ?>
                                            <i class="fas fa-sort-<?php echo $sort_order === 'DESC' ? 'down' : 'up'; ?>"></i>
                                        <?php endif; ?>
                                    </a>
                                </th>
                                <th>Kontakt</th>
                                <th>
                                    <a href="<?php echo $base_url; ?>sort=total&order=<?php echo $sort_column === 'total' && $sort_order === 'DESC' ? 'asc' : 'desc'; ?>">
                                        Ukupno
                                        <?php if ($sort_column === 'total'): ?>
                                            <i class="fas fa-sort-<?php echo $sort_order === 'DESC' ? 'down' : 'up'; ?>"></i>
                                        <?php endif; ?>
                                    </a>
                                </th>
                                <th>Stavke</th>
                                <th>
                                    <a href="<?php echo $base_url; ?>sort=status&order=<?php echo $sort_column === 'status' && $sort_order === 'DESC' ? 'asc' : 'desc'; ?>">
                                        Status
                                        <?php if ($sort_column === 'status'): ?>
                                            <i class="fas fa-sort-<?php echo $sort_order === 'DESC' ? 'down' : 'up'; ?>"></i>
                                        <?php endif; ?>
                                    </a>
                                </th>
                                <th>
                                    <a href="<?php echo $base_url; ?>sort=created_at&order=<?php echo $sort_column === 'created_at' && $sort_order === 'DESC' ? 'asc' : 'desc'; ?>">
                                        Datum
                                        <?php if ($sort_column === 'created_at'): ?>
                                            <i class="fas fa-sort-<?php echo $sort_order === 'DESC' ? 'down' : 'up'; ?>"></i>
                                        <?php endif; ?>
                                    </a>
                                </th>
                                <th width="120">Akcije</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($orders)): ?>
                            <tr>
                                <td colspan="9" class="text-center">Nema pronađenih porudžbina</td>
                            </tr>
                            <?php else: ?>
                                <?php foreach ($orders as $order): ?>
                                <tr>
                                    <td><?php echo $order['id']; ?></td>
                                    <td>
                                        <a href="/admin/orders/view.php?id=<?php echo $order['id']; ?>">
                                            <?php echo $order['order_number']; ?>
                                        </a>
                                    </td>
                                    <td><?php echo htmlspecialchars($order['name']); ?></td>
                                    <td>
                                        <?php if (!empty($order['phone'])): ?>
                                        <a href="tel:<?php echo $order['phone']; ?>"><?php echo $order['phone']; ?></a><br>
                                        <?php endif; ?>
                                        <?php if (!empty($order['email'])): ?>
                                        <a href="mailto:<?php echo $order['email']; ?>"><?php echo $order['email']; ?></a>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo format_price($order['total']); ?></td>
                                    <td><?php echo $order['item_count']; ?></td>
                                    <td>
                                        <span class="badge badge-<?php echo get_order_status_class($order['status']); ?>">
                                            <?php echo get_order_status_name($order['status']); ?>
                                        </span>
                                    </td>
                                    <td><?php echo date('d.m.Y. H:i', strtotime($order['created_at'])); ?></td>
                                    <td>
                                        <div class="btn-group">
                                            <a href="/admin/orders/view.php?id=<?php echo $order['id']; ?>" class="btn btn-info btn-sm" title="Pregled">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="/admin/orders/edit.php?id=<?php echo $order['id']; ?>" class="btn btn-primary btn-sm" title="Izmeni">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <a href="/admin/orders/delete.php?id=<?php echo $order['id']; ?>" class="btn btn-danger btn-sm" title="Obriši" onclick="return confirm('Da li ste sigurni da želite da obrišete ovu porudžbinu?');">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Paginacija -->
                <?php if ($total_pages > 1): ?>
                <div class="mt-4 d-flex justify-content-center">
                    <ul class="pagination">
                        <?php if ($current_page > 1): ?>
                        <li class="page-item">
                            <a class="page-link" href="<?php echo $base_url; ?>page=<?php echo $current_page - 1; ?>">
                                <i class="fas fa-angle-left"></i> Prethodna
                            </a>
                        </li>
                        <?php endif; ?>
                        
                        <?php
                        $start_page = max(1, $current_page - 2);
                        $end_page = min($total_pages, $current_page + 2);
                        
                        for ($i = $start_page; $i <= $end_page; $i++):
                        ?>
                        <li class="page-item <?php echo $i == $current_page ? 'active' : ''; ?>">
                            <a class="page-link" href="<?php echo $base_url; ?>page=<?php echo $i; ?>">
                                <?php echo $i; ?>
                            </a>
                        </li>
                        <?php endfor; ?>
                        
                        <?php if ($current_page < $total_pages): ?>
                        <li class="page-item">
                            <a class="page-link" href="<?php echo $base_url; ?>page=<?php echo $current_page + 1; ?>">
                                Sledeća <i class="fas fa-angle-right"></i>
                            </a>
                        </li>
                        <?php endif; ?>
                    </ul>
                </div>
                <?php endif; ?>
                
                <!-- Export opcije -->
                <div class="mt-3">
                    <div class="btn-group">
                        <a href="/admin/orders/export.php?format=csv<?php echo !empty($filter_params) ? '&' . implode('&', $filter_params) : ''; ?>" class="btn btn-outline-secondary">
                            <i class="fas fa-file-csv"></i> Izvezi CSV
                        </a>
                        <a href="/admin/orders/export.php?format=excel<?php echo !empty($filter_params) ? '&' . implode('&', $filter_params) : ''; ?>" class="btn btn-outline-secondary">
                            <i class="fas fa-file-excel"></i> Izvezi Excel
                        </a>
                        <a href="/admin/orders/export.php?format=pdf<?php echo !empty($filter_params) ? '&' . implode('&', $filter_params) : ''; ?>" class="btn btn-outline-secondary">
                            <i class="fas fa-file-pdf"></i> Izvezi PDF
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
    $(document).ready(function() {
        // Automatski submit forme prilikom promene status taba
        $('.nav-tabs .nav-link').click(function(e) {
            if ($(this).attr('href') !== '#') {
                window.location = $(this).attr('href');
                e.preventDefault();
            }
        });
    });
</script>

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