<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Stock Movements History - 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/
$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/ -> /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 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_datetime function if it doesn't exist
if (!function_exists('format_datetime')) {
    function format_datetime($datetime, $format = 'M d, Y H:i') {
        if (empty($datetime)) return '';
        return date($format, strtotime($datetime));
    }
}

// Define time_ago function if it doesn't exist
if (!function_exists('time_ago')) {
    function time_ago($datetime) {
        if (empty($datetime)) return '';
        $time = strtotime($datetime);
        $now = time();
        $diff = $now - $time;
        
        if ($diff < 60) return $diff . ' seconds ago';
        if ($diff < 3600) return floor($diff / 60) . ' minutes ago';
        if ($diff < 86400) return floor($diff / 3600) . ' hours ago';
        if ($diff < 2592000) return floor($diff / 86400) . ' days ago';
        return date('M d, Y', $time);
    }
}

// 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('MOVEMENT_TYPES')) {
    $movement_types = [
        'purchase' => 'Purchase',
        'sale' => 'Sale',
        'return' => 'Return',
        'adjustment' => 'Adjustment',
        'transfer' => 'Transfer',
        'transfer_in' => 'Transfer In',
        'transfer_out' => 'Transfer Out'
    ];
    define('MOVEMENT_TYPES', serialize($movement_types));
}

// Check permission
if (function_exists('require_permission')) {
    require_permission('inventory.stock.manage');
}

// Set page title
$page_title = 'Stock Movements';

// 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']) : '';
$product_id = isset($_GET['product_id']) && $_GET['product_id'] !== '' ? (int)$_GET['product_id'] : null;
$movement_type = isset($_GET['movement_type']) ? trim($_GET['movement_type']) : '';
$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']) : 'created_at';
$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) * 2;

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

if (!empty($search)) {
    $where .= " AND (p.product_name LIKE ? OR p.product_code LIKE ?)";
    $search_term = "%$search%";
    $params = array_merge($params, [$search_term, $search_term]);
}

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

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

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

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

// Validate sort column
$allowed_sort = ['movement_id', 'created_at', 'movement_type', 'quantity'];
if (!in_array($sort, $allowed_sort)) {
    $sort = 'created_at';
}

// Get stock movements
$movements = [];
$total = 0;

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

        // Get paginated data
        $offset = ($page - 1) * $per_page;
        
        $sql = "
            SELECT 
                sm.*,
                p.product_name, p.product_code, p.unit_of_measure,
                u.first_name, u.last_name
            FROM stock_movements sm
            JOIN pos_products p ON sm.product_id = p.product_id
            LEFT JOIN users u ON sm.created_by = u.user_id
            WHERE $where
            ORDER BY $sort $order
            LIMIT " . (int)$per_page . " OFFSET " . (int)$offset;
        
        $movements = db_fetch_all($sql, $params) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching movements: " . $e->getMessage());
    }
}

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

// Get products for filter
$products = [];
if (function_exists('db_fetch_all')) {
    try {
        $products = db_fetch_all("
            SELECT product_id, product_name, product_code 
            FROM pos_products 
            WHERE stock_item = 1 AND is_active = 1
            ORDER BY product_name
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching products: " . $e->getMessage());
    }
}

// Get movement types
$movement_types = [];
if (defined('MOVEMENT_TYPES')) {
    $movement_types = @unserialize(MOVEMENT_TYPES) ?: [];
}
if (empty($movement_types)) {
    $movement_types = [
        'purchase' => 'Purchase',
        'sale' => 'Sale',
        'return' => 'Return',
        'adjustment' => 'Adjustment',
        'transfer' => 'Transfer',
        'transfer_in' => 'Transfer In',
        'transfer_out' => 'Transfer Out'
    ];
}

// Get summary statistics
$stats = [
    'total' => $total,
    'in' => 0,
    'out' => 0,
    'net' => 0
];

if (function_exists('db_fetch_value')) {
    try {
        $stats['in'] = db_fetch_value("SELECT COALESCE(SUM(quantity), 0) FROM stock_movements WHERE quantity > 0") ?: 0;
        $stats['out'] = db_fetch_value("SELECT COALESCE(SUM(quantity), 0) FROM stock_movements WHERE quantity < 0") ?: 0;
        $stats['net'] = db_fetch_value("SELECT COALESCE(SUM(quantity), 0) FROM stock_movements") ?: 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>Stock Movements</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-success { background-color: #28a745 !important; }
            .bg-danger { background-color: #dc3545 !important; }
            .bg-warning { background-color: #ffc107 !important; color: #000; }
            .badge-lg { font-size: 1rem; padding: 0.4rem 0.8rem; }
            .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="#">Stock Movements</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">Stock Movements</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">Stock Movements</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- 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 Movements</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-exchange-alt"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo $stats['in']; ?></h3>
                        <p>Stock In</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-arrow-down"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo abs($stats['out']); ?></h3>
                        <p>Stock Out</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-arrow-up"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo $stats['net']; ?></h3>
                        <p>Net Change</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-chart-line"></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 product..." 
                               value="<?php echo escape_html($search); ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="product_id">
                            <option value="">All Products</option>
                            <?php foreach ($products as $product): ?>
                                <option value="<?php echo $product['product_id'] ?? 0; ?>" <?php echo $product_id == ($product['product_id'] ?? 0) ? 'selected' : ''; ?>>
                                    <?php echo escape_html($product['product_name'] ?? ''); ?> (<?php echo escape_html($product['product_code'] ?? ''); ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="movement_type">
                            <option value="">All Types</option>
                            <?php foreach ($movement_types as $value => $label): ?>
                                <option value="<?php echo $value; ?>" <?php echo $movement_type == $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>
                    
                    <div class="col-md-1 ms-auto">
                        <a href="adjustments.php" class="btn btn-warning w-100">
                            <i class="fas fa-balance-scale"></i>
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Movements Table -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-history me-1"></i>
                    Stock Movement History
                </h3>
            </div>
            
            <div class="card-body p-0">
                <?php if (empty($movements)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-exchange-alt fa-4x mb-3"></i>
                        <h5>No stock movements found</h5>
                        <p>Movements will appear here when stock is received, sold, or adjusted</p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>Date/Time</th>
                                    <th>Product</th>
                                    <th>Type</th>
                                    <th class="text-end">Quantity</th>
                                    <th>Reference</th>
                                    <th>Notes</th>
                                    <th>Created By</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($movements as $movement): ?>
                                <tr class="<?php echo ($movement['quantity'] ?? 0) > 0 ? 'table-success' : 'table-danger'; ?>">
                                    <td>
                                        <?php echo isset($movement['created_at']) ? date('M d, Y H:i', strtotime($movement['created_at'])) : 'N/A'; ?>
                                        <br>
                                        <small class="text-muted"><?php echo isset($movement['created_at']) ? time_ago($movement['created_at']) : ''; ?></small>
                                    </td>
                                    <td>
                                        <a href="/HMSPOS/pos/products/view.php?id=<?php echo $movement['product_id'] ?? 0; ?>">
                                            <strong><?php echo escape_html($movement['product_name'] ?? ''); ?></strong>
                                        </a>
                                        <br>
                                        <small class="text-muted"><?php echo escape_html($movement['product_code'] ?? ''); ?></small>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php 
                                            $type = $movement['movement_type'] ?? '';
                                            echo $type == 'purchase' ? 'success' : 
                                                ($type == 'sale' ? 'info' : 
                                                ($type == 'return' ? 'warning' : 
                                                ($type == 'adjustment' ? 'secondary' : 'danger')));
                                        ?>">
                                            <?php echo $movement_types[$type] ?? ucfirst($type); ?>
                                        </span>
                                    </td>
                                    <td class="text-end">
                                        <span class="badge bg-<?php echo ($movement['quantity'] ?? 0) > 0 ? 'success' : 'danger'; ?> badge-lg">
                                            <?php echo ($movement['quantity'] ?? 0) > 0 ? '+' : ''; ?><?php echo $movement['quantity'] ?? 0; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if (!empty($movement['reference_type'])): ?>
                                            <span class="badge bg-info">
                                                <?php echo ucfirst($movement['reference_type']); ?> #<?php echo $movement['reference_id'] ?? 0; ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <small><?php echo escape_html($movement['notes'] ?: '-'); ?></small>
                                    </td>
                                    <td>
                                        <small><?php echo escape_html(($movement['first_name'] ?? '') . ' ' . ($movement['last_name'] ?? '')); ?></small>
                                    </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; ?> movements
                        </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); ?>&product_id=<?php echo $product_id; ?>&movement_type=<?php echo $movement_type; ?>&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); ?>&product_id=<?php echo $product_id; ?>&movement_type=<?php echo $movement_type; ?>&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); ?>&product_id=<?php echo $product_id; ?>&movement_type=<?php echo $movement_type; ?>&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); ?>&product_id=<?php echo $product_id; ?>&movement_type=<?php echo $movement_type; ?>&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); ?>&product_id=<?php echo $product_id; ?>&movement_type=<?php echo $movement_type; ?>&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>

<style>
.badge-lg {
    font-size: 1rem;
    padding: 0.4rem 0.8rem;
}
</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>';
}
?>