<?php
/**
 * Enterprise HRM ERP System - Site Management
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/check_admin_access.php';

$pageTitle = 'Site Management';
$currentModule = 'settings';

$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Filters
$search = sanitize($_GET['search'] ?? '');
$status = sanitize($_GET['status'] ?? '');

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

if (!empty($search)) {
    $where[] = "(site_code LIKE ? OR site_name LIKE ? OR site_email LIKE ?)";
    $searchParam = "%{$search}%";
    $params = array_merge($params, [$searchParam, $searchParam, $searchParam]);
}

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

$whereClause = implode(' AND ', $where);

try {
    $db = getDB();
    
    // Get total count
    $countSql = "SELECT COUNT(*) FROM sites WHERE {$whereClause}";
    $stmt = $db->prepare($countSql);
    $stmt->execute($params);
    $totalRecords = $stmt->fetchColumn();
    $totalPages = ceil($totalRecords / $perPage);
    
    // Get sites
    $sql = "
        SELECT s.*, 
               COUNT(DISTINCT u.user_id) as user_count,
               COUNT(DISTINCT e.employee_id) as employee_count
        FROM sites s
        LEFT JOIN user_sites us ON s.site_id = us.site_id
        LEFT JOIN users u ON us.user_id = u.user_id
        LEFT JOIN employees e ON s.site_id = e.site_id
        WHERE {$whereClause}
        GROUP BY s.site_id
        ORDER BY s.created_at DESC
        LIMIT ? OFFSET ?
    ";
    $params[] = $perPage;
    $params[] = $offset;
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $sites = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Site list error: " . $e->getMessage());
    $sites = [];
    $totalRecords = 0;
    $totalPages = 0;
}

include __DIR__ . '/../includes/header.php';
?>

<div class="table-container">
    <div class="table-header">
        <h2 class="table-title">Site Management</h2>
        <div class="table-actions">
            <a href="<?php echo BASE_URL; ?>/admin/sites_create.php" class="btn btn-primary">Add New Site</a>
        </div>
    </div>
    
    <div class="table-filters">
        <div class="filter-group">
            <label>Search</label>
            <input type="text" name="search" class="form-control" placeholder="Code, Name, Email..." 
                   value="<?php echo htmlspecialchars($search); ?>" 
                   onkeypress="if(event.key==='Enter') filterTable()">
        </div>
        <div class="filter-group">
            <label>Status</label>
            <select name="status" class="form-control" onchange="filterTable()">
                <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="filter-group">
            <button type="button" class="btn btn-secondary" onclick="resetFilters()">Reset</button>
        </div>
    </div>
    
    <?php if (count($sites) > 0): ?>
    <table class="data-table">
        <thead>
            <tr>
                <th class="sortable">Site Code</th>
                <th class="sortable">Site Name</th>
                <th class="sortable">Email</th>
                <th class="sortable">Phone</th>
                <th>Users</th>
                <th>Employees</th>
                <th class="sortable">Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($sites as $site): ?>
            <tr>
                <td><strong><?php echo htmlspecialchars($site['site_code']); ?></strong></td>
                <td><?php echo htmlspecialchars($site['site_name']); ?></td>
                <td><?php echo htmlspecialchars($site['site_email'] ?? 'N/A'); ?></td>
                <td><?php echo htmlspecialchars($site['site_phone'] ?? 'N/A'); ?></td>
                <td><?php echo number_format($site['user_count']); ?></td>
                <td><?php echo number_format($site['employee_count']); ?></td>
                <td>
                    <span class="status-badge status-<?php echo htmlspecialchars($site['site_status']); ?>">
                        <?php echo ucfirst($site['site_status']); ?>
                    </span>
                </td>
                <td class="table-actions-cell">
                    <a href="<?php echo BASE_URL; ?>/admin/sites_edit.php?id=<?php echo $site['site_id']; ?>" 
                       class="btn btn-sm btn-primary">Edit</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    
    <div class="table-footer">
        <div class="table-info">
            Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $perPage, $totalRecords); ?> of <?php echo number_format($totalRecords); ?> sites
        </div>
        <div class="pagination">
            <?php if ($page > 1): ?>
            <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>" 
               class="btn btn-sm">Previous</a>
            <?php endif; ?>
            <span class="pagination-info">Page <?php echo $page; ?> of <?php echo $totalPages; ?></span>
            <?php if ($page < $totalPages): ?>
            <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>" 
               class="btn btn-sm">Next</a>
            <?php endif; ?>
        </div>
    </div>
    <?php else: ?>
    <div class="table-empty">
        <div class="table-empty-icon">🏢</div>
        <div class="table-empty-message">No sites found</div>
        <div class="table-empty-submessage">
            <a href="<?php echo BASE_URL; ?>/admin/sites_create.php" class="btn btn-primary">Add First Site</a>
        </div>
    </div>
    <?php endif; ?>
</div>

<style>
.status-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 11px;
    font-weight: 500;
    text-transform: uppercase;
}

.status-active {
    background-color: #d1fae5;
    color: #065f46;
}

.status-inactive {
    background-color: #e5e7eb;
    color: #374151;
}
</style>

<script>
function filterTable() {
    const search = document.querySelector('[name="search"]').value;
    const status = document.querySelector('[name="status"]').value;
    
    const params = new URLSearchParams();
    if (search) params.append('search', search);
    if (status) params.append('status', status);
    
    window.location.href = '?' + params.toString();
}

function resetFilters() {
    window.location.href = '<?php echo BASE_URL; ?>/admin/sites.php';
}
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>

