<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * POS Outlets 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/outlets/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/outlets/ -> /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('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount, 0);
    }
}

if (!function_exists('csrf_token')) {
    function csrf_token() {
        return $_SESSION['csrf_token'] ?? bin2hex(random_bytes(32));
    }
}

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.outlets.view');
// }

// Set page title
$page_title = 'POS Outlets Management';

// 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'] ?? '';
$type = $_GET['type'] ?? '';
$status = $_GET['status'] ?? '';

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

if (!empty($search)) {
    $where .= " AND (outlet_name LIKE ? OR outlet_code LIKE ? OR location LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

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

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

// Get outlets with statistics
$outlets = [];
try {
    $outlets = db_fetch_all("
        SELECT 
            o.*,
            (SELECT COUNT(*) FROM pos_products WHERE outlet_id = o.outlet_id) as product_count,
            (SELECT COUNT(*) FROM pos_sales WHERE outlet_id = o.outlet_id) as sales_count,
            (SELECT COUNT(*) FROM pos_shifts WHERE outlet_id = o.outlet_id AND status = 'open') as open_shifts,
            (SELECT COALESCE(SUM(total_amount), 0) FROM pos_sales WHERE outlet_id = o.outlet_id AND DATE(sale_time) = CURDATE()) as today_sales
        FROM pos_outlets o
        WHERE $where
        ORDER BY o.outlet_name
    ", $params) ?: [];
} catch (Exception $e) {
    error_log("Error fetching outlets: " . $e->getMessage());
}

// Get outlet types for filter
$outlet_types = [
    'restaurant' => 'Restaurant',
    'bar' => 'Bar',
    'pool' => 'Pool Bar',
    'spa' => 'Spa',
    'gift_shop' => 'Gift Shop',
    'other' => 'Other'
];

// Get summary statistics
$stats = [
    'total_outlets' => 0,
    'active_outlets' => 0,
    'total_products' => 0,
    'total_sales_today' => 0
];

try {
    $stats['total_outlets'] = (int)db_fetch_value("SELECT COUNT(*) FROM pos_outlets WHERE is_active = 1") ?: 0;
    $stats['active_outlets'] = (int)db_fetch_value("SELECT COUNT(*) FROM pos_outlets WHERE is_active = 1") ?: 0;
    $stats['total_products'] = (int)db_fetch_value("SELECT COUNT(*) FROM pos_products WHERE is_active = 1") ?: 0;
    $stats['total_sales_today'] = (float)db_fetch_value("SELECT COALESCE(SUM(total_amount), 0) FROM pos_sales WHERE DATE(sale_time) = CURDATE()") ?: 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>POS Outlets Management</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="#">POS Outlets Management</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">POS Outlets Management</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">Outlets</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; ?>

        <!-- 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_outlets']; ?></h3>
                        <p>Total Outlets</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-store"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo $stats['active_outlets']; ?></h3>
                        <p>Active Outlets</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo $stats['total_products']; ?></h3>
                        <p>Total Products</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-box"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo format_currency($stats['total_sales_today']); ?></h3>
                        <p>Today's Sales</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="card card-outline card-primary">
                    <div class="card-body">
                        <?php if (function_exists('has_permission') && has_permission('pos.outlets.manage')): ?>
                            <a href="create.php" class="btn btn-primary me-2">
                                <i class="fas fa-plus-circle"></i> New Outlet
                            </a>
                        <?php endif; ?>
                        <a href="../categories/index.php" class="btn btn-info me-2">
                            <i class="fas fa-tags"></i> Manage Categories
                        </a>
                        <a href="../products/index.php" class="btn btn-success me-2">
                            <i class="fas fa-box"></i> Manage Products
                        </a>
                        <a href="../reports/daily-sales.php" class="btn btn-warning me-2">
                            <i class="fas fa-chart-bar"></i> Sales Reports
                        </a>
                        <button type="button" class="btn btn-secondary" onclick="exportOutlets()">
                            <i class="fas fa-download"></i> Export
                        </button>
                    </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-4">
                        <input type="text" class="form-control" name="search" placeholder="Search outlets..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    
                    <div class="col-md-3">
                        <select class="form-select" name="type">
                            <option value="">All Types</option>
                            <?php foreach ($outlet_types as $value => $label): ?>
                                <option value="<?php echo $value; ?>" <?php echo $type == $value ? 'selected' : ''; ?>>
                                    <?php echo $label; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </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-12">
                        <a href="?" class="btn btn-secondary">
                            <i class="fas fa-times me-1"></i> Clear Filters
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Outlets Table -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-store me-1"></i>
                    POS Outlets (<?php echo count($outlets); ?>)
                </h3>
            </div>
            
            <div class="card-body p-0">
                <?php if (empty($outlets)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-store fa-4x mb-3"></i>
                        <h5>No outlets found</h5>
                        <p>Create your first POS outlet to get started</p>
                        <?php if (function_exists('has_permission') && has_permission('pos.outlets.manage')): ?>
                            <a href="create.php" class="btn btn-primary">
                                <i class="fas fa-plus me-1"></i> New Outlet
                            </a>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>Code</th>
                                    <th>Name</th>
                                    <th>Type</th>
                                    <th>Location</th>
                                    <th class="text-center">Products</th>
                                    <th class="text-center">Sales Today</th>
                                    <th class="text-center">Open Shifts</th>
                                    <th>Status</th>
                                    <th width="150">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($outlets as $outlet): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo escape_html($outlet['outlet_code'] ?? ''); ?></strong>
                                    </td>
                                    <td><?php echo escape_html($outlet['outlet_name'] ?? ''); ?></td>
                                    <td>
                                        <span class="badge bg-info">
                                            <?php echo $outlet_types[$outlet['outlet_type'] ?? 'other'] ?? ucfirst($outlet['outlet_type'] ?? 'other'); ?>
                                        </span>
                                    </td>
                                    <td><?php echo !empty($outlet['location']) ? escape_html($outlet['location']) : '-'; ?></td>
                                    <td class="text-center">
                                        <span class="badge bg-info"><?php echo $outlet['product_count'] ?? 0; ?></span>
                                    </td>
                                    <td class="text-center">
                                        <?php if (($outlet['today_sales'] ?? 0) > 0): ?>
                                            <span class="badge bg-success"><?php echo format_currency($outlet['today_sales']); ?></span>
                                        <?php else: ?>
                                            <span class="badge bg-secondary">0</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <?php if (($outlet['open_shifts'] ?? 0) > 0): ?>
                                            <span class="badge bg-warning"><?php echo $outlet['open_shifts']; ?></span>
                                        <?php else: ?>
                                            <span class="badge bg-secondary">0</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if (!empty($outlet['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="view.php?id=<?php echo $outlet['outlet_id'] ?? 0; ?>" 
                                               class="btn btn-sm btn-info" title="View">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            
                                            <?php if (function_exists('has_permission') && has_permission('pos.outlets.manage')): ?>
                                                <a href="edit.php?id=<?php echo $outlet['outlet_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-warning" title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                            <?php endif; ?>
                                            
                                            <?php if (function_exists('has_permission') && has_permission('pos.outlets.manage') && ($outlet['product_count'] ?? 0) == 0 && ($outlet['sales_count'] ?? 0) == 0): ?>
                                                <button type="button" class="btn btn-sm btn-danger" 
                                                        onclick="deleteOutlet(<?php echo $outlet['outlet_id'] ?? 0; ?>, '<?php echo escape_html($outlet['outlet_name'] ?? ''); ?>')"
                                                        title="Delete">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
            
            <?php if (!empty($outlets)): ?>
            <div class="card-footer">
                <div class="row">
                    <div class="col-md-6">
                        <small class="text-muted">
                            <i class="fas fa-info-circle me-1"></i>
                            Showing <?php echo count($outlets); ?> outlets
                        </small>
                    </div>
                    <div class="col-md-6 text-end">
                        <button type="button" class="btn btn-sm btn-primary" onclick="exportOutlets()">
                            <i class="fas fa-download"></i> Export to CSV
                        </button>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </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 Outlet</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 outlet <strong id="deleteOutletName"></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="outlet_id" id="deleteOutletId">
                    <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>

<script>
function deleteOutlet(outletId, outletName) {
    document.getElementById('deleteOutletId').value = outletId;
    document.getElementById('deleteOutletName').textContent = outletName;
    
    const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
    modal.show();
}

function exportOutlets() {
    // Collect current filter parameters
    const params = new URLSearchParams(window.location.search);
    params.set('export', 'csv');
    
    // Redirect to export endpoint
    window.location.href = 'export-outlets.php?' + params.toString();
}

// Auto-refresh every 60 seconds to update live data (commented out to prevent constant reloads)
// setTimeout(function() {
//     location.reload();
// }, 60000);
</script>

<style>
.table td {
    vertical-align: middle;
}
.btn-group .btn {
    margin: 0 2px;
}
.badge {
    font-size: 0.85rem;
}
.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-warning { background-color: #ffc107; color: #000; }
.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>';
}
?>