<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Product Categories Management - List View - FIXED VERSION
 * 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
// Current file: /HMSPOS/pos/categories/index.php
// Need to go up to: /HMSPOS/
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root
$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/pos/categories/ -> /HMSPOS/
    $base_path = dirname(dirname(dirname(__DIR__)));
}

// 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';
}

// Load required files
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/auth.php';

// Load helpers if they exist
if (file_exists($base_path . '/config/helpers.php')) {
    require_once $base_path . '/config/helpers.php';
}
if (file_exists($base_path . '/config/csrf.php')) {
    require_once $base_path . '/config/csrf.php';
}
if (file_exists($base_path . '/config/constants.php')) {
    require_once $base_path . '/config/constants.php';
}

// Require authentication
require_auth();

// 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 helper functions if they don't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('truncate_text')) {
    function truncate_text($text, $length = 50) {
        if (strlen($text) <= $length) return $text;
        return substr($text, 0, $length) . '...';
    }
}

if (!function_exists('csrf_field')) {
    function csrf_field() {
        $token = $_SESSION['csrf_token'] ?? bin2hex(random_bytes(32));
        if (!isset($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = $token;
        }
        return '<input type="hidden" name="csrf_token" value="' . $token . '">';
    }
}

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

if (!function_exists('display_flash_messages')) {
    function display_flash_messages() {
        if (isset($_SESSION['flash_messages']) && !empty($_SESSION['flash_messages'])) {
            foreach ($_SESSION['flash_messages'] as $flash) {
                $type = $flash['type'] ?? 'info';
                $message = $flash['message'] ?? '';
                echo '<div class="alert alert-' . $type . ' alert-dismissible fade show" role="alert">';
                echo htmlspecialchars($message);
                echo '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
                echo '</div>';
            }
            $_SESSION['flash_messages'] = [];
        }
    }
}

// Check permission (commented out for now)
// if (function_exists('require_permission')) {
//     require_permission('pos.categories.view');
// }

// Set page title
$page_title = 'Product Categories';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

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

// Get filter parameters
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';

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

if (!empty($search)) {
    $where .= " AND (category_name LIKE ? OR category_code LIKE ? OR description LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

if ($status === 'active') {
    $where .= " AND is_active = 1";
} elseif ($status === 'inactive') {
    $where .= " AND is_active = 0";
}

// Get categories with product counts
$categories = [];
try {
    $categories = db_fetch_all("
        SELECT c.*,
               (SELECT COUNT(*) FROM pos_products WHERE category_id = c.category_id) as product_count
        FROM pos_categories c
        WHERE $where
        ORDER BY c.sort_order, c.category_name
    ", $params) ?: [];
} catch (Exception $e) {
    error_log("Error fetching categories: " . $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>Product Categories</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; }
        </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="#">Product Categories</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">Product Categories</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/pos/dashboard.php">POS</a></li>
                    <li class="breadcrumb-item active">Categories</li>
                </ol>
            </div>
        </div>
    </div>
</div>

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

        <!-- 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-5">
                        <input type="text" class="form-control" name="search" placeholder="Search categories..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    
                    <div class="col-md-3">
                        <select class="form-select" name="status">
                            <option value="">All Status</option>
                            <option value="active" <?php echo $status == 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="inactive" <?php echo $status == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-search"></i> Apply
                        </button>
                    </div>
                    
                    <div class="col-md-2">
                        <a href="?" class="btn btn-secondary w-100">
                            <i class="fas fa-times"></i> Clear
                        </a>
                    </div>
                    
                    <div class="col-12 text-end">
                        <?php if (function_exists('has_permission') && has_permission('pos.categories.manage')): ?>
                            <a href="create.php" class="btn btn-success">
                                <i class="fas fa-plus"></i> New Category
                            </a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>

        <!-- Categories Table -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-tags me-1"></i>
                    Product Categories (<?php echo count($categories); ?>)
                </h3>
                <div class="card-tools">
                    <?php if (!empty($categories)): ?>
                    <button type="button" class="btn btn-sm btn-info" onclick="saveOrder()">
                        <i class="fas fa-save"></i> Save Order
                    </button>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="card-body p-0">
                <?php if (empty($categories)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-tags fa-4x mb-3"></i>
                        <h5>No categories found</h5>
                        <p>Create your first product category</p>
                        <?php if (function_exists('has_permission') && has_permission('pos.categories.manage')): ?>
                            <a href="create.php" class="btn btn-primary">
                                <i class="fas fa-plus me-1"></i> New Category
                            </a>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover" id="categoriesTable">
                            <thead>
                                <tr>
                                    <th width="80">Order</th>
                                    <th>Code</th>
                                    <th>Name</th>
                                    <th>Description</th>
                                    <th class="text-center">Products</th>
                                    <th>Status</th>
                                    <th width="120">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="sortable">
                                <?php foreach ($categories as $category): ?>
                                <tr data-id="<?php echo $category['category_id'] ?? 0; ?>">
                                    <td class="sort-handle">
                                        <i class="fas fa-grip-vertical text-muted me-2"></i>
                                        <span class="badge bg-secondary"><?php echo $category['sort_order'] ?? 0; ?></span>
                                    </td>
                                    <td>
                                        <strong><?php echo escape_html($category['category_code'] ?? ''); ?></strong>
                                    </td>
                                    <td><?php echo escape_html($category['category_name'] ?? ''); ?></td>
                                    <td>
                                        <?php echo escape_html(truncate_text($category['description'] ?? '', 50)); ?>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge bg-info"><?php echo $category['product_count'] ?? 0; ?></span>
                                    </td>
                                    <td>
                                        <?php if (!empty($category['is_active'])): ?>
                                            <span class="badge bg-success">Active</span>
                                        <?php else: ?>
                                            <span class="badge bg-danger">Inactive</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="btn-group">
                                            <a href="edit.php?id=<?php echo $category['category_id'] ?? 0; ?>" 
                                               class="btn btn-sm btn-warning" title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            
                                            <?php if (($category['product_count'] ?? 0) == 0): ?>
                                                <button type="button" class="btn btn-sm btn-danger" 
                                                        onclick="deleteCategory(<?php echo $category['category_id'] ?? 0; ?>, '<?php echo escape_html($category['category_name'] ?? ''); ?>')"
                                                        title="Delete">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <form method="POST" id="orderForm" action="update-order.php">
                        <?php if (function_exists('csrf_field')): ?>
                            <?php echo csrf_field(); ?>
                        <?php endif; ?>
                        <input type="hidden" name="order" id="categoryOrder" value="">
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger">
                <h5 class="modal-title">Delete Category</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete category <strong id="deleteCategoryName"></strong>?</p>
                <p class="text-danger"><i class="fas fa-exclamation-triangle me-1"></i> This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <form method="POST" action="delete.php" id="deleteForm">
                    <?php if (function_exists('csrf_field')): ?>
                        <?php echo csrf_field(); ?>
                    <?php endif; ?>
                    <input type="hidden" name="category_id" id="deleteCategoryId">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- SortableJS -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>

<script>
$(document).ready(function() {
    // Initialize sortable if there are rows to sort
    const sortableElement = document.querySelector('.sortable');
    if (sortableElement) {
        new Sortable(sortableElement, {
            handle: '.sort-handle',
            animation: 150,
            onEnd: function() {
                updateOrderNumbers();
            }
        });
    }
});

function updateOrderNumbers() {
    $('.sortable tr').each(function(index) {
        $(this).find('.badge-secondary').text(index + 1);
    });
}

function saveOrder() {
    const order = [];
    $('.sortable tr').each(function() {
        order.push($(this).data('id'));
    });
    
    $('#categoryOrder').val(JSON.stringify(order));
    $('#orderForm').submit();
}

function deleteCategory(categoryId, categoryName) {
    document.getElementById('deleteCategoryId').value = categoryId;
    document.getElementById('deleteCategoryName').textContent = categoryName;
    
    const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
    modal.show();
}
</script>

<style>
.sort-handle {
    cursor: grab;
}
.sort-handle:active {
    cursor: grabbing;
}
.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; }
.text-end { text-align: right; }
.w-100 { width: 100%; }
.badge.bg-info { background-color: #17a2b8; color: #fff; }
.badge.bg-success { background-color: #28a745; color: #fff; }
.badge.bg-danger { background-color: #dc3545; color: #fff; }
.badge.bg-secondary { background-color: #6c757d; color: #fff; }
</style>

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