<?php
session_start();
header('Content-Type: text/html; charset=utf-8');

// Initialize stats
if (!file_exists('stats.json')) {
    header('Location: index.php');
    exit;
}

$stats = json_decode(file_get_contents('stats.json'), true);

// Handle login
if ($_POST['action'] ?? '' === 'login') {
    $password = $_POST['password'] ?? '';
    if (hash('sha256', $password) === $stats['settings']['admin_password']) {
        $_SESSION['admin'] = true;
    } else {
        $error = "Invalid password!";
    }
}

// Handle logout
if ($_GET['action'] ?? '' === 'logout') {
    session_destroy();
    header('Location: admin.php');
    exit;
}

// Check if logged in
$isLoggedIn = $_SESSION['admin'] ?? false;

// Handle settings update
if ($isLoggedIn && $_POST['action'] ?? '' === 'update_settings') {
    $stats['settings']['site_name'] = $_POST['site_name'] ?? $stats['settings']['site_name'];
    if (!empty($_POST['new_password'])) {
        $stats['settings']['admin_password'] = hash('sha256', $_POST['new_password']);
    }
    file_put_contents('stats.json', json_encode($stats, JSON_PRETTY_PRINT));
    $success = "Settings updated successfully!";
}

// Handle data reset
if ($isLoggedIn && $_POST['action'] ?? '' === 'reset_data') {
    $stats['visitors'] = [];
    $stats['pages'] = [];
    file_put_contents('stats.json', json_encode($stats, JSON_PRETTY_PRINT));
    $success = "All data has been reset!";
}

$stats = json_decode(file_get_contents('stats.json'), true);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Panel - Website Statistics</title>
    <style>
        :root {
            --primary: #4361ee;
            --secondary: #3a0ca3;
            --success: #4cc9f0;
            --danger: #f72585;
            --warning: #f8961e;
            --info: #4895ef;
            --dark: #2b2d42;
            --light: #f8f9fa;
            --gray: #6c757d;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .header {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            text-align: center;
        }
        
        .header h1 {
            color: var(--dark);
            font-size: 2.5rem;
            margin-bottom: 10px;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        
        .login-form, .admin-panel {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            max-width: 500px;
            margin: 0 auto;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            color: var(--dark);
            font-weight: 500;
        }
        
        input[type="text"],
        input[type="password"] {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            font-size: 1rem;
            transition: all 0.3s ease;
        }
        
        input[type="text"]:focus,
        input[type="password"]:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
        }
        
        .btn {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 25px;
            font-size: 1rem;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 5px 15px rgba(67, 97, 238, 0.3);
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(67, 97, 238, 0.4);
        }
        
        .btn-danger {
            background: linear-gradient(135deg, var(--danger), #b5179e);
        }
        
        .btn-danger:hover {
            box-shadow: 0 8px 25px rgba(247, 37, 133, 0.4);
        }
        
        .alert {
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .alert-error {
            background: rgba(247, 37, 133, 0.1);
            border: 1px solid var(--danger);
            color: var(--danger);
        }
        
        .alert-success {
            background: rgba(76, 201, 240, 0.1);
            border: 1px solid var(--success);
            color: var(--success);
        }
        
        .admin-actions {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-top: 30px;
        }
        
        .action-card {
            background: rgba(67, 97, 238, 0.05);
            border-radius: 15px;
            padding: 25px;
            text-align: center;
            border: 2px dashed rgba(67, 97, 238, 0.2);
        }
        
        .back-link {
            display: inline-block;
            margin-top: 20px;
            color: var(--primary);
            text-decoration: none;
            font-weight: 500;
        }
        
        .back-link:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔒 Admin Panel</h1>
            <p>Manage your website statistics</p>
        </div>
        
        <?php if (!$isLoggedIn): ?>
            <div class="login-form">
                <h2 style="text-align: center; margin-bottom: 30px; color: var(--dark);">Administrator Login</h2>
                
                <?php if (isset($error)): ?>
                    <div class="alert alert-error"><?php echo $error; ?></div>
                <?php endif; ?>
                
                <form method="POST">
                    <input type="hidden" name="action" value="login">
                    <div class="form-group">
                        <label for="password">Password:</label>
                        <input type="password" id="password" name="password" required>
                    </div>
                    <button type="submit" class="btn" style="width: 100%;">Login</button>
                </form>
                
                <a href="index.php" class="back-link">← Back to Statistics</a>
            </div>
        <?php else: ?>
            <div class="admin-panel">
                <h2 style="text-align: center; margin-bottom: 30px; color: var(--dark);">Admin Controls</h2>
                
                <?php if (isset($success)): ?>
                    <div class="alert alert-success"><?php echo $success; ?></div>
                <?php endif; ?>
                
                <form method="POST">
                    <input type="hidden" name="action" value="update_settings">
                    
                    <div class="form-group">
                        <label for="site_name">Site Name:</label>
                        <input type="text" id="site_name" name="site_name" value="<?php echo htmlspecialchars($stats['settings']['site_name']); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="new_password">New Password (leave blank to keep current):</label>
                        <input type="password" id="new_password" name="new_password">
                    </div>
                    
                    <button type="submit" class="btn" style="width: 100%;">Update Settings</button>
                </form>
                
                <div class="admin-actions">
                    <div class="action-card">
                        <h3>Reset Data</h3>
                        <p>Clear all visitor and page statistics</p>
                        <form method="POST" onsubmit="return confirm('Are you sure you want to reset all data? This cannot be undone!');">
                            <input type="hidden" name="action" value="reset_data">
                            <button type="submit" class="btn btn-danger" style="width: 100%; margin-top: 10px;">Reset All Data</button>
                        </form>
                    </div>
                    
                    <div class="action-card">
                        <h3>Session</h3>
                        <p>Manage your admin session</p>
                        <a href="admin.php?action=logout" class="btn" style="width: 100%; margin-top: 10px; display: block; text-decoration: none;">Logout</a>
                    </div>
                </div>
                
                <a href="index.php" class="back-link">← Back to Statistics</a>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>