<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Purchase Orders Management - List View - FIXED PATH
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root from admin/inventory/purchases/
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    // Manual calculation: /HMSPOS/admin/inventory/purchases/ -> /HMSPOS/
    $base_path = dirname(__DIR__, 4);
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Method 4: Try to find by traversing up until we find config directory
$current_dir = __DIR__;
while (!file_exists($current_dir . '/config/config.php') && $current_dir != dirname($current_dir)) {
    $current_dir = dirname($current_dir);
}
if (file_exists($current_dir . '/config/config.php')) {
    $base_path = $current_dir;
}

// Load required files
$required_files = [
    '/config/config.php',
    '/config/constants.php',
    '/config/database.php',
    '/config/helpers.php',
    '/config/auth.php',
    '/config/csrf.php'
];

foreach ($required_files as $file) {
    $file_path = $base_path . $file;
    if (file_exists($file_path)) {
        require_once $file_path;
    } else {
        error_log("Required file not found: " . $file_path);
        // Try alternate path without HMSPOS
        $alt_path = str_replace('/HMSPOS', '', $base_path) . $file;
        if (file_exists($alt_path)) {
            require_once $alt_path;
        } else {
            // Try one more fallback
            $fallback_path = dirname(__DIR__, 2) . $file;
            if (file_exists($fallback_path)) {
                require_once $fallback_path;
            }
        }
    }
}

// Require authentication
if (function_exists('require_auth')) {
    require_auth();
} else {
    // Fallback authentication check
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Define has_permission function if it doesn't exist
if (!function_exists('has_permission')) {
    function has_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Define escape_html function if it doesn't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define format_date function if it doesn't exist
if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, Y') {
        if (empty($date)) return '';
        return date($format, strtotime($date));
    }
}

// Define format_currency function if it doesn't exist
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount ?? 0, 2);
    }
}

// Define display_flash_messages function if it doesn't exist
if (!function_exists('display_flash_messages')) {
    function display_flash_messages() {
        if (isset($_SESSION['flash_messages']) && is_array($_SESSION['flash_messages'])) {
            foreach ($_SESSION['flash_messages'] as $msg) {
                $type = $msg['type'] ?? 'info';
                $message = $msg['message'] ?? '';
                echo "<div class='alert alert-{$type} alert-dismissible fade show'>";
                echo escape_html($message);
                echo "<button type='button' class='btn-close' data-bs-dismiss='alert'></button>";
                echo "</div>";
            }
            unset($_SESSION['flash_messages']);
        }
    }
}

// Define set_flash_message function if it doesn't exist
if (!function_exists('set_flash_message')) {
    function set_flash_message($type, $message) {
        if (!isset($_SESSION['flash_messages'])) {
            $_SESSION['flash_messages'] = [];
        }
        $_SESSION['flash_messages'][] = ['type' => $type, 'message' => $message];
    }
}

// Define redirect function if it doesn't exist
if (!function_exists('redirect')) {
    function redirect($url) {
        header('Location: ' . $url);
        exit;
    }
}

// Define base_url function if it doesn't exist
if (!function_exists('base_url')) {
    function base_url($path = '') {
        return '/HMSPOS/' . ltrim($path, '/');
    }
}

// Define constants if not defined
if (!defined('ITEMS_PER_PAGE')) {
    define('ITEMS_PER_PAGE', 25);
}
if (!defined('CURRENCY_SYMBOL')) {
    define('CURRENCY_SYMBOL', 'RWF');
}
if (!defined('PO_STATUSES')) {
    $po_statuses = [
        'draft' => 'Draft',
        'ordered' => 'Ordered',
        'partial' => 'Partially Received',
        'received' => 'Received',
        'cancelled' => 'Cancelled'
    ];
    define('PO_STATUSES', serialize($po_statuses));
}

// Check permission
if (function_exists('require_permission')) {
    require_permission('inventory.purchases.view');
}

// Set page title
$page_title = 'Purchase Orders';

// Get current user
$current_user = null;
if (function_exists('current_user')) {
    $current_user = current_user();
} else {
    // Fallback: get user from session
    if (isset($_SESSION['user_id'])) {
        try {
            if (function_exists('db_fetch_one')) {
                $current_user = db_fetch_one("SELECT * FROM users WHERE user_id = ?", [$_SESSION['user_id']]);
            }
        } catch (Exception $e) {
            error_log("Error fetching current user: " . $e->getMessage());
        }
    }
}

$user_id = $current_user['user_id'] ?? $_SESSION['user_id'] ?? 0;

if (!$user_id) {
    header('Location: /HMSPOS/public/login.php');
    exit;
}

// Get filter parameters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$supplier_id = isset($_GET['supplier_id']) && $_GET['supplier_id'] !== '' ? (int)$_GET['supplier_id'] : null;
$status = isset($_GET['status']) ? trim($_GET['status']) : '';
$date_from = isset($_GET['date_from']) ? trim($_GET['date_from']) : '';
$date_to = isset($_GET['date_to']) ? trim($_GET['date_to']) : '';
$sort = isset($_GET['sort']) ? trim($_GET['sort']) : 'order_date';
$order = isset($_GET['order']) ? trim($_GET['order']) : 'DESC';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$per_page = defined('ITEMS_PER_PAGE') ? ITEMS_PER_PAGE : 25;

// Build where clause
$where = "1=1";
$params = [];

if (!empty($search)) {
    $where .= " AND (po.po_number LIKE ? OR s.supplier_name LIKE ?)";
    $search_term = "%$search%";
    $params = array_merge($params, [$search_term, $search_term]);
}

if ($supplier_id) {
    $where .= " AND po.supplier_id = ?";
    $params[] = $supplier_id;
}

if (!empty($status)) {
    $where .= " AND po.status = ?";
    $params[] = $status;
}

if (!empty($date_from)) {
    $where .= " AND po.order_date >= ?";
    $params[] = $date_from;
}

if (!empty($date_to)) {
    $where .= " AND po.order_date <= ?";
    $params[] = $date_to;
}

// Validate sort column
$allowed_sort = ['po_id', 'po_number', 'order_date', 'expected_date', 'total_amount', 'status'];
if (!in_array($sort, $allowed_sort)) {
    $sort = 'order_date';
}

// Get purchase orders with details
$purchase_orders = [];
$total = 0;

if (function_exists('db_fetch_value') && function_exists('db_fetch_all')) {
    try {
        // Get total count
        $count_sql = "SELECT COUNT(*) FROM purchase_orders po WHERE $where";
        $total = db_fetch_value($count_sql, $params) ?: 0;

        // Get paginated data
        $offset = ($page - 1) * $per_page;
        
        $sql = "
            SELECT 
                po.*,
                s.supplier_name,
                COUNT(poi.item_id) as item_count,
                u.first_name, u.last_name
            FROM purchase_orders po
            JOIN suppliers s ON po.supplier_id = s.supplier_id
            LEFT JOIN purchase_order_items poi ON po.po_id = poi.po_id
            LEFT JOIN users u ON po.created_by = u.user_id
            WHERE $where
            GROUP BY po.po_id
            ORDER BY $sort $order
            LIMIT " . (int)$per_page . " OFFSET " . (int)$offset;
        
        $purchase_orders = db_fetch_all($sql, $params) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching purchase orders: " . $e->getMessage());
    }
}

// Calculate pagination
$total_pages = $per_page > 0 ? ceil($total / $per_page) : 0;

// Get suppliers for filter
$suppliers = [];
if (function_exists('db_fetch_all')) {
    try {
        $suppliers = db_fetch_all("SELECT supplier_id, supplier_name FROM suppliers WHERE is_active = 1 ORDER BY supplier_name") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching suppliers: " . $e->getMessage());
    }
}

// Get status options
$statuses = [];
if (defined('PO_STATUSES')) {
    $statuses = @unserialize(PO_STATUSES) ?: [];
}
if (empty($statuses)) {
    $statuses = [
        'draft' => 'Draft',
        'ordered' => 'Ordered',
        'partial' => 'Partially Received',
        'received' => 'Received',
        'cancelled' => 'Cancelled'
    ];
}

// Get summary statistics
$stats = [
    'total' => $total,
    'pending' => 0,
    'overdue' => 0,
    'total_value' => 0
];

if (function_exists('db_fetch_value')) {
    try {
        $stats['pending'] = db_fetch_value("SELECT COUNT(*) FROM purchase_orders WHERE status IN ('ordered', 'partial')") ?: 0;
        $stats['overdue'] = db_fetch_value("SELECT COUNT(*) FROM purchase_orders WHERE status IN ('ordered', 'partial') AND expected_date < CURDATE()") ?: 0;
        $stats['total_value'] = db_fetch_value("SELECT COALESCE(SUM(total_amount), 0) FROM purchase_orders WHERE status != 'cancelled'") ?: 0;
    } catch (Exception $e) {
        error_log("Error fetching stats: " . $e->getMessage());
    }
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Purchase Orders</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
            .small-box { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; position: relative; overflow: hidden; color: #fff; }
            .small-box .inner { padding: 20px; }
            .small-box h3 { font-size: 2rem; font-weight: 700; margin: 0 0 10px 0; }
            .small-box p { font-size: 1rem; margin: 0; }
            .small-box .icon { position: absolute; top: 10px; right: 15px; font-size: 4rem; opacity: 0.3; }
            .bg-info { background-color: #17a2b8 !important; }
            .bg-warning { background-color: #ffc107 !important; color: #000; }
            .bg-danger { background-color: #dc3545 !important; }
            .bg-success { background-color: #28a745 !important; }
            .me-1 { margin-right: 0.25rem; }
            .me-2 { margin-right: 0.5rem; }
            .ms-2 { margin-left: 0.5rem; }
            .mb-2 { margin-bottom: 0.5rem; }
            .mb-3 { margin-bottom: 1rem; }
            .mt-2 { margin-top: 0.5rem; }
            .text-end { text-align: right; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Purchase Orders</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Purchase Orders</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/inventory/dashboard.php">Inventory</a></li>
                    <li class="breadcrumb-item active">Purchase Orders</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <?php display_flash_messages(); ?>

        <!-- Summary Cards -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo $stats['total']; ?></h3>
                        <p>Total Orders</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-shopping-cart"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo $stats['pending']; ?></h3>
                        <p>Pending Orders</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-clock"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo $stats['overdue']; ?></h3>
                        <p>Overdue</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-exclamation-triangle"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo format_currency($stats['total_value']); ?></h3>
                        <p>Total Value</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-filter me-1"></i>
                    Filters
                </h3>
                <div class="card-tools">
                    <button type="button" class="btn btn-tool" data-card-widget="collapse">
                        <i class="fas fa-minus"></i>
                    </button>
                </div>
            </div>
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-3">
                        <input type="text" class="form-control" name="search" placeholder="Search PO # or supplier..." 
                               value="<?php echo escape_html($search); ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="supplier_id">
                            <option value="">All Suppliers</option>
                            <?php foreach ($suppliers as $supplier): ?>
                                <option value="<?php echo $supplier['supplier_id'] ?? 0; ?>" <?php echo $supplier_id == ($supplier['supplier_id'] ?? 0) ? 'selected' : ''; ?>>
                                    <?php echo escape_html($supplier['supplier_name'] ?? ''); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="status">
                            <option value="">All Status</option>
                            <?php foreach ($statuses as $value => $label): ?>
                                <option value="<?php echo $value; ?>" <?php echo $status == $value ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($label); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <input type="date" class="form-control" name="date_from" placeholder="From" 
                               value="<?php echo $date_from; ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <input type="date" class="form-control" name="date_to" placeholder="To" 
                               value="<?php echo $date_to; ?>">
                    </div>
                    
                    <div class="col-md-1">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                    
                    <div class="col-md-1">
                        <a href="?" class="btn btn-secondary w-100">
                            <i class="fas fa-times"></i>
                        </a>
                    </div>
                    
                    <?php if (function_exists('has_permission') && has_permission('inventory.purchases.manage')): ?>
                        <div class="col-md-1 ms-auto">
                            <a href="create-po.php" class="btn btn-success w-100">
                                <i class="fas fa-plus"></i> New
                            </a>
                        </div>
                    <?php endif; ?>
                </form>
            </div>
        </div>

        <!-- Purchase Orders Table -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-clipboard-list me-1"></i>
                    Purchase Orders (<?php echo $total; ?> total)
                </h3>
            </div>
            
            <div class="card-body p-0">
                <?php if (empty($purchase_orders)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-clipboard-list fa-4x mb-3"></i>
                        <h5>No purchase orders found</h5>
                        <p>Create your first purchase order</p>
                        <?php if (function_exists('has_permission') && has_permission('inventory.purchases.manage')): ?>
                            <a href="create-po.php" class="btn btn-primary">
                                <i class="fas fa-plus me-1"></i> New Purchase Order
                            </a>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>
                                        <a href="?sort=po_number&order=<?php echo $sort === 'po_number' && $order === 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo urlencode($search); ?>&supplier_id=<?php echo $supplier_id; ?>&status=<?php echo $status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>" class="text-decoration-none">
                                            PO #
                                            <?php if ($sort === 'po_number'): ?>
                                                <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                            <?php endif; ?>
                                        </a>
                                    </th>
                                    <th>Supplier</th>
                                    <th>
                                        <a href="?sort=order_date&order=<?php echo $sort === 'order_date' && $order === 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo urlencode($search); ?>&supplier_id=<?php echo $supplier_id; ?>&status=<?php echo $status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>" class="text-decoration-none">
                                            Order Date
                                            <?php if ($sort === 'order_date'): ?>
                                                <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                            <?php endif; ?>
                                        </a>
                                    </th>
                                    <th>Expected</th>
                                    <th class="text-center">Items</th>
                                    <th class="text-end">
                                        <a href="?sort=total_amount&order=<?php echo $sort === 'total_amount' && $order === 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo urlencode($search); ?>&supplier_id=<?php echo $supplier_id; ?>&status=<?php echo $status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>" class="text-decoration-none">
                                            Total
                                            <?php if ($sort === 'total_amount'): ?>
                                                <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                            <?php endif; ?>
                                        </a>
                                    </th>
                                    <th>Status</th>
                                    <th>Created By</th>
                                    <th width="120">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($purchase_orders as $po): ?>
                                <tr class="<?php 
                                    $is_overdue = ($po['status'] ?? '') != 'received' && !empty($po['expected_date']) && strtotime($po['expected_date']) < time();
                                    echo $is_overdue ? 'table-danger' : '';
                                ?>">
                                    <td>
                                        <a href="view.php?id=<?php echo $po['po_id'] ?? 0; ?>">
                                            <strong><?php echo htmlspecialchars($po['po_number'] ?? ''); ?></strong>
                                        </a>
                                    </td>
                                    <td>
                                        <a href="../suppliers/view.php?id=<?php echo $po['supplier_id'] ?? 0; ?>">
                                            <?php echo escape_html($po['supplier_name'] ?? ''); ?>
                                        </a>
                                    </td>
                                    <td><?php echo isset($po['order_date']) ? date('M d, Y', strtotime($po['order_date'])) : 'N/A'; ?></td>
                                    <td>
                                        <?php if (!empty($po['expected_date'])): ?>
                                            <?php echo date('M d, Y', strtotime($po['expected_date'])); ?>
                                            <?php if (($po['status'] ?? '') != 'received' && strtotime($po['expected_date']) < time()): ?>
                                                <span class="badge bg-danger">Overdue</span>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center"><?php echo $po['item_count'] ?? 0; ?></td>
                                    <td class="text-end"><?php echo format_currency($po['total_amount'] ?? 0); ?></td>
                                    <td>
                                        <span class="badge bg-<?php 
                                            $po_status = $po['status'] ?? '';
                                            echo $po_status == 'received' ? 'success' : 
                                                ($po_status == 'partial' ? 'warning' : 
                                                ($po_status == 'ordered' ? 'info' : 
                                                ($po_status == 'draft' ? 'secondary' : 'danger')));
                                        ?>">
                                            <?php echo $statuses[$po_status] ?? ucfirst($po_status); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <small><?php echo htmlspecialchars(($po['first_name'] ?? '') . ' ' . ($po['last_name'] ?? '')); ?></small>
                                    </td>
                                    <td>
                                        <div class="btn-group">
                                            <a href="view.php?id=<?php echo $po['po_id'] ?? 0; ?>" 
                                               class="btn btn-sm btn-info" title="View">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            
                                            <?php if (($po['status'] ?? '') != 'received' && ($po['status'] ?? '') != 'cancelled'): ?>
                                                <a href="receive.php?id=<?php echo $po['po_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-success" title="Receive">
                                                    <i class="fas fa-truck"></i>
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <div class="card-footer clearfix">
                <div class="row">
                    <div class="col-sm-5">
                        <span class="text-muted">
                            Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $per_page, $total); ?> of <?php echo $total; ?> orders
                        </span>
                    </div>
                    <div class="col-sm-7">
                        <ul class="pagination pagination-sm m-0 float-end">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=1&search=<?php echo urlencode($search); ?>&supplier_id=<?php echo $supplier_id; ?>&status=<?php echo $status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <i class="fas fa-angle-double-left"></i>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&supplier_id=<?php echo $supplier_id; ?>&status=<?php echo $status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <i class="fas fa-chevron-left"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                            
                            <?php
                            $start = max(1, $page - 2);
                            $end = min($total_pages, $page + 2);
                            
                            for ($i = $start; $i <= $end; $i++):
                            ?>
                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&supplier_id=<?php echo $supplier_id; ?>&status=<?php echo $status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>
                            
                            <?php if ($page < $total_pages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&supplier_id=<?php echo $supplier_id; ?>&status=<?php echo $status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <i class="fas fa-chevron-right"></i>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $total_pages; ?>&search=<?php echo urlencode($search); ?>&supplier_id=<?php echo $supplier_id; ?>&status=<?php echo $status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <i class="fas fa-angle-double-right"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</section>

<?php
// Include footer
$footer_path = $base_path . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>