<?php
date_default_timezone_set('Asia/Colombo');
include '../config.php';
include '../auth.php';
checkRole('admin');

// Handle user operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_user'])) {
        $username = $_POST['username'];
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $full_name = $_POST['full_name'];
        $role = $_POST['role'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        
        $stmt = $conn->prepare("INSERT INTO users (username, password, full_name, role, email, phone) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssss", $username, $password, $full_name, $role, $email, $phone);
        
        if ($stmt->execute()) {
            $message = "User created successfully!";
        } else {
            $error = "Error creating user: " . $stmt->error;
        }
    }
    
    if (isset($_POST['toggle_user'])) {
        $user_id = $_POST['user_id'];
        $is_active = $_POST['is_active'] ? 0 : 1;
        
        $stmt = $conn->prepare("UPDATE users SET is_active = ? WHERE id = ?");
        $stmt->bind_param("ii", $is_active, $user_id);
        $stmt->execute();
        
        $message = "User status updated!";
    }
}

// Get all users
$users = $conn->query("SELECT * FROM users ORDER BY created_at DESC")->fetch_all(MYSQLI_ASSOC);

// Get system statistics
$stats = [
    'total_sales' => $conn->query("SELECT COUNT(*) as count FROM sales")->fetch_assoc()['count'],
    'total_revenue' => $conn->query("SELECT SUM(total_amount) as total FROM sales")->fetch_assoc()['total'] ?? 0,
    'total_products' => $conn->query("SELECT COUNT(*) as count FROM products")->fetch_assoc()['count'],
    'total_customers' => $conn->query("SELECT COUNT(*) as count FROM customers")->fetch_assoc()['count'],
    'active_users' => $conn->query("SELECT COUNT(*) as count FROM users WHERE is_active = 1")->fetch_assoc()['count']
];
?>
<!DOCTYPE html>
<html>
<head>
    <title>Admin Panel - Dilrukshi Tex</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background: #f8f9fa; }
        .container { margin-top: 40px; }
        .admin-card { border-left: 4px solid #007bff; }
        .stat-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
    </style>
</head>
<body>
    <div class="container">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="fw-bold"><i class="fas fa-cogs"></i> Admin Panel</h1>
            <div>
                <a href="../pos/" class="btn btn-success me-2"><i class="fas fa-cash-register"></i> POS</a>
                <a href="../" class="btn btn-secondary"><i class="fas fa-home"></i> Dashboard</a>
            </div>
        </div>

        <?php if (isset($message)): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?= $message ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <?php if (isset($error)): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <?= $error ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <!-- System Statistics -->
        <div class="row mb-4">
            <div class="col-md-2">
                <div class="card stat-card text-center p-3">
                    <i class="fas fa-receipt fa-2x mb-2"></i>
                    <h4><?= $stats['total_sales'] ?></h4>
                    <small>Total Sales</small>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card stat-card text-center p-3">
                    <i class="fas fa-dollar-sign fa-2x mb-2"></i>
                    <h4>Rs <?= number_format($stats['total_revenue'], 2) ?></h4>
                    <small>Revenue</small>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card stat-card text-center p-3">
                    <i class="fas fa-box fa-2x mb-2"></i>
                    <h4><?= $stats['total_products'] ?></h4>
                    <small>Products</small>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card stat-card text-center p-3">
                    <i class="fas fa-users fa-2x mb-2"></i>
                    <h4><?= $stats['total_customers'] ?></h4>
                    <small>Customers</small>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card stat-card text-center p-3">
                    <i class="fas fa-user-tie fa-2x mb-2"></i>
                    <h4><?= $stats['active_users'] ?></h4>
                    <small>Active Users</small>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card stat-card text-center p-3">
                    <i class="fas fa-calendar fa-2x mb-2"></i>
                    <h4><?= date('M d') ?></h4>
                    <small>Today</small>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Add User Form -->
            <div class="col-lg-4 mb-4">
                <div class="card admin-card">
                    <div class="card-header bg-primary text-white">
                        <i class="fas fa-user-plus"></i> Add New User
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <input type="hidden" name="add_user" value="1">
                            <div class="mb-3">
                                <label class="form-label">Username *</label>
                                <input type="text" name="username" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Password *</label>
                                <input type="password" name="password" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Full Name *</label>
                                <input type="text" name="full_name" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Role *</label>
                                <select name="role" class="form-select" required>
                                    <option value="cashier">Cashier</option>
                                    <option value="manager">Manager</option>
                                    <option value="admin">Admin</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Email</label>
                                <input type="email" name="email" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Phone</label>
                                <input type="tel" name="phone" class="form-control">
                            </div>
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="fas fa-save"></i> Create User
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- User Management -->
            <div class="col-lg-8 mb-4">
                <div class="card admin-card">
                    <div class="card-header bg-success text-white">
                        <i class="fas fa-users-cog"></i> User Management
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped mb-0">
                                <thead class="table-dark">
                                    <tr>
                                        <th>User</th>
                                        <th>Role</th>
                                        <th>Contact</th>
                                        <th>Last Login</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($users as $user): ?>
                                    <tr class="<?= !$user['is_active'] ? 'table-secondary' : '' ?>">
                                        <td>
                                            <div>
                                                <strong><?= htmlspecialchars($user['full_name']) ?></strong>
                                                <br><small class="text-muted">@<?= htmlspecialchars($user['username']) ?></small>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?= $user['role'] === 'admin' ? 'danger' : ($user['role'] === 'manager' ? 'warning' : 'info') ?>">
                                                <?= ucfirst($user['role']) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($user['email']): ?>
                                            <div><small><i class="fas fa-envelope"></i> <?= htmlspecialchars($user['email']) ?></small></div>
                                            <?php endif; ?>
                                            <?php if ($user['phone']): ?>
                                            <div><small><i class="fas fa-phone"></i> <?= htmlspecialchars($user['phone']) ?></small></div>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?= $user['last_login'] ? date('M d, H:i', strtotime($user['last_login'])) : 'Never' ?>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?= $user['is_active'] ? 'success' : 'secondary' ?>">
                                                <?= $user['is_active'] ? 'Active' : 'Inactive' ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($user['id'] !== $_SESSION['user_id']): ?>
                                            <form method="POST" class="d-inline">
                                                <input type="hidden" name="toggle_user" value="1">
                                                <input type="hidden" name="user_id" value="<?= $user['id'] ?>">
                                                <input type="hidden" name="is_active" value="<?= $user['is_active'] ?>">
                                                <button type="submit" class="btn btn-sm btn-outline-<?= $user['is_active'] ? 'danger' : 'success' ?>"
                                                        onclick="return confirm('<?= $user['is_active'] ? 'Deactivate' : 'Activate' ?> this user?')">
                                                    <i class="fas fa-<?= $user['is_active'] ? 'ban' : 'check' ?>"></i>
                                                </button>
                                            </form>
                                            <?php else: ?>
                                            <small class="text-muted">Current User</small>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="card admin-card">
            <div class="card-header bg-warning text-dark">
                <i class="fas fa-bolt"></i> Quick Actions
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3 mb-3">
                        <a href="backup.php" class="btn btn-outline-primary w-100">
                            <i class="fas fa-download"></i> Backup Database
                        </a>
                    </div>
                    <div class="col-md-3 mb-3">
                        <a href="settings.php" class="btn btn-outline-secondary w-100">
                            <i class="fas fa-cog"></i> System Settings
                        </a>
                    </div>
                    <div class="col-md-3 mb-3">
                        <a href="../reports/" class="btn btn-outline-info w-100">
                            <i class="fas fa-chart-bar"></i> View Reports
                        </a>
                    </div>
                    <div class="col-md-3 mb-3">
                        <a href="logs.php" class="btn btn-outline-warning w-100">
                            <i class="fas fa-file-alt"></i> System Logs
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
