<?php
// Admin login page - requires username and password
// Redirects to admin dashboard if credentials are correct and user is an admin
session_start();

$error = '';
$loggedInAsAdmin = false;

if (isset($_SESSION['is_admin']) && $_SESSION['is_admin'] === true) {
    $loggedInAsAdmin = true;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = isset($_POST['admin_name']) ? trim($_POST['admin_name']) : '';
    $pass = isset($_POST['admin_pass']) ? trim($_POST['admin_pass']) : '';
    
    if ($name === '' || $pass === '') {
        $error = 'Please enter username and password';
    } else {
        require __DIR__ . '/db_config.php';
        
        // Find user by username/email
        $stmt = $conn->prepare("SELECT id, username, email, password_hash FROM users WHERE username = ? OR email = ? LIMIT 1");
        $stmt->bind_param('ss', $name, $name);
        $stmt->execute();
        $res = $stmt->get_result();

        if ($res && $res->num_rows > 0) {
            $row = $res->fetch_assoc();
            $usePlain = (isset($STORE_PLAINTEXT_PASSWORDS) && $STORE_PLAINTEXT_PASSWORDS === true);
            $ok = false;
            if ($usePlain) {
                $ok = hash_equals((string)$row['password_hash'], (string)$pass);
            } else {
                $ok = password_verify($pass, $row['password_hash']);
            }
            
            if ($ok) {
                // load subadmin definitions from data if present
                $_SESSION['user_id'] = $row['id'];
                $_SESSION['username'] = $row['username'];

                // Check if this user is a full admin in admins table
                $isAdminUser = false;
                $aStmt = $conn->prepare('SELECT id, role_name FROM admins WHERE user_id = ? LIMIT 1');
                if ($aStmt) {
                    $aStmt->bind_param('i', $row['id']);
                    $aStmt->execute();
                    $aRes = $aStmt->get_result();
                    if ($aRes && $aRes->num_rows > 0) {
                        $isAdminUser = true;
                        $adminRow = $aRes->fetch_assoc();
                        $_SESSION['admin_role'] = $adminRow['role_name'] ?? 'admin';
                    }
                    $aStmt->close();
                }

                if ($isAdminUser) {
                    $_SESSION['is_admin'] = true;
                    header('Location: admin_dashboard.php');
                    exit;
                }

                // Check if user is an editor (database first, then JSON fallback)
                $isEditor = false;
                $editorPerms = [];
                
                // Try database first
                $eStmt = @$conn->prepare('SELECT permissions FROM editors WHERE user_id = ? LIMIT 1');
                if ($eStmt) {
                    $eStmt->bind_param('i', $row['id']);
                    $eStmt->execute();
                    $eRes = $eStmt->get_result();
                    if ($eRes && $eRes->num_rows > 0) {
                        $isEditor = true;
                        $eRow = $eRes->fetch_assoc();
                        $permJson = $eRow['permissions'] ?? '{}';
                        $editorPerms = json_decode($permJson, true) ?: [];
                    }
                    $eStmt->close();
                }
                
                // JSON fallback for editor
                if (!$isEditor) {
                    $editorsPath = __DIR__ . '/data/editors.json';
                    if (file_exists($editorsPath)) {
                        $json = @file_get_contents($editorsPath);
                        $editors = @json_decode($json, true);
                        if (is_array($editors)) {
                            foreach ($editors as $ed) {
                                if (is_array($ed) && isset($ed['user_id']) && $ed['user_id'] == $row['id']) {
                                    $isEditor = true;
                                    $editorPerms = $ed['permissions'] ?? [];
                                    break;
                                }
                            }
                        }
                    }
                }

                if ($isEditor) {
                    $_SESSION['is_editor'] = true;
                    $_SESSION['editor_permissions'] = $editorPerms;
                    $_SESSION['role'] = 'editor';
                    
                    // Redirect to editor dashboard
                    if (file_exists(__DIR__ . '/subadmin_dashboard.php')) {
                        header('Location: subadmin_dashboard.php');
                    } else {
                        header('Location: admin_dashboard.php');
                    }
                    exit;
                }

                // Check if user is a subadmin in subadmins table (database first, then JSON fallback)
                $isSubAdmin = false;
                $subadminPerms = [];
                
                // Try database first
                $sStmt = @$conn->prepare('SELECT permissions FROM subadmins WHERE user_id = ? LIMIT 1');
                if ($sStmt) {
                    $sStmt->bind_param('i', $row['id']);
                    $sStmt->execute();
                    $sRes = $sStmt->get_result();
                    if ($sRes && $sRes->num_rows > 0) {
                        $isSubAdmin = true;
                        $subRow = $sRes->fetch_assoc();
                        $permJson = $subRow['permissions'] ?? '{}';
                        $subadminPerms = json_decode($permJson, true) ?: [];
                    }
                    $sStmt->close();
                }
                
                // JSON fallback for subadmin
                if (!$isSubAdmin) {
                    $subadminsPath = __DIR__ . '/data/subadmins.json';
                    if (file_exists($subadminsPath)) {
                        $json = @file_get_contents($subadminsPath);
                        $subs = @json_decode($json, true);
                        if (is_array($subs)) {
                            foreach ($subs as $sub) {
                                if (is_array($sub) && isset($sub['user_id']) && $sub['user_id'] == $row['id']) {
                                    $isSubAdmin = true;
                                    $subadminPerms = $sub['permissions'] ?? [];
                                    break;
                                }
                            }
                        }
                    }
                }

                if ($isSubAdmin) {
                    $_SESSION['is_subadmin'] = true;
                    $_SESSION['subadmin_permissions'] = $subadminPerms;
                    $_SESSION['role'] = 'subadmin';
                    
                    // Redirect to subadmin dashboard
                    if (file_exists(__DIR__ . '/subadmin_dashboard.php')) {
                        header('Location: subadmin_dashboard.php');
                    } else {
                        header('Location: admin_dashboard.php');
                    }
                    exit;
                }

                // If we reach here, user authenticated but is not admin or sub-admin
                $error = 'You do not have admin or sub-admin access.';
            } else {
                $error = 'Incorrect password';
            }
        } else {
            $error = 'Admin user not found or not authorized';
        }
        $stmt->close();
        $conn->close();
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>Admin Login</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="css/responsive-system.css">
    <title>Admin Login</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: Inter, system-ui, Arial, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; display: flex; align-items: center; justify-content: center; }
        .login-card { background: #fff; padding: 40px; border-radius: 12px; box-shadow: 0 20px 60px rgba(0,0,0,0.3); width: 100%; max-width: 420px; }
        h1 { color: #333; margin-bottom: 8px; font-size: 28px; }
        .subtitle { color: #666; margin-bottom: 24px; font-size: 14px; }
        .form-group { margin-bottom: 16px; }
        label { display: block; color: #333; font-weight: 600; margin-bottom: 6px; font-size: 14px; }
        input { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; }
        input:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); }
        button { width: 100%; padding: 12px; background: #667eea; color: #fff; border: none; border-radius: 6px; font-size: 16px; font-weight: 600; cursor: pointer; margin-top: 8px; }
        button:hover { background: #5568d3; }
        .error { background: #ffebee; color: #c62828; padding: 12px; border-radius: 6px; margin-bottom: 16px; border-left: 4px solid #f44336; }
        .success { background: #e8f5e9; color: #2e7d32; padding: 12px; border-radius: 6px; margin-bottom: 16px; border-left: 4px solid #4caf50; }
        .back-link { text-align: center; margin-top: 16px; }
        .back-link a { color: #667eea; text-decoration: none; font-size: 14px; }
        .back-link a:hover { text-decoration: underline; }
    </style>
</head>
<body>
    
    <div class="login-card">
        <h1>Admin Login</h1>
        <p class="subtitle">Enter your credentials to access the admin dashboard</p>
        
        <?php if ($error): ?>
            <div class="error"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        
        <?php if ($loggedInAsAdmin): ?>
            <div class="success">✓ You are already logged in as admin. <a href="admin_dashboard.php">Go to dashboard →</a></div>
        <?php endif; ?>
        
        <form method="POST">
            <div class="form-group">
                <label for="admin_name">Username or Email</label>
                <input type="text" id="admin_name" name="admin_name" placeholder="Enter username or email" autocomplete="username" required>
            </div>
            <div class="form-group">
                <label for="admin_pass">Password</label>
                <input type="password" id="admin_pass" name="admin_pass" placeholder="Enter password" autocomplete="current-password" required>
            </div>
            <button type="submit">Sign In as Admin</button>
        </form>

        <div class="back-link">
            <a href="index.php">← Back to site</a>
        </div>
    </div>
</body>
</html>
