import os

# Define the Core Logic component repository for Phase 2
PHASE_2_DATA = {
    # -------------------------------------------------------------------------
    # BACKEND API HANDLERS (api/)
    # -------------------------------------------------------------------------
    "api/auth_handler.php": """ false, 'message' => 'Method Not Allowed']));
}

// CSRF Protection
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    http_response_code(403);
    exit(json_encode(['success' => false, 'message' => 'Invalid CSRF validation token']));
}

$inputs = sanitize($_POST);
$identifier = $inputs['identifier'] ?? '';
$password = $_POST['password'] ?? '';

try {
    $db = Database::getConnection();
    // Dual-identity prepared statement
    $stmt = $db->prepare("SELECT id, username, email, password_hash, status FROM users WHERE username = ? OR email = ? LIMIT 1");
    $stmt->execute([$identifier, $identifier]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password_hash'])) {
        if ($user['status'] !== 'active') {
            exit(json_encode(['success' => false, 'message' => 'Account is currently '  $]]));
        }

        // Secure session hydration
        session_regenerate_id(true);
        $_SESSION['] = $user['id'];
        $_SESSION['] = $user['];
        
        // Fetch cumulative roles
        $roleStmt = $db->prepare("SELECT g.name FROM groups g JOIN user_groups ug ON g.id = ug.group_id WHERE ug.user_id = ?");
        $roleStmt->execute([$]]);
        $_SESSION['] = $roleStmt->fetchAll(PDO::FETCH_COLUMN);

        // Audit Logging
        $logStmt = $db->prepare("INSERT INTO login_logs (user_id, ip_address) VALUES (?, ?)");
        $logStmt->execute([$], $_SERVER['REMOTE_ADDR']]);

        echo json_encode(['success' => true, 'message' => 'Authentication successful']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid credentials provided']);
    }
} catch (Exception $e) {
    Logger::logError($e->getMessage(), __FILE__, __LINE__);
}
""",

    "api/admin_handler.php": """<?php
/**
 * User CRUD & Multi-Group Alignment Controller
 */
require_once __DIR__ . '/../core/init.php';
Auth::enforceAccess(['admin']);

header('Content-Type: application/json');

$action = $_GET['action'] ?? '';

try {
    $db = Database::getConnection();

    if ($action === 'create_user') {
        $inputs = sanitize($_POST);
        $hashed = password_hash($_POST['password'], PASSWORD_ARGON2ID);
        
        $db->beginTransaction();
        $stmt = $db->prepare("INSERT INTO users (username, email, password_hash) VALUES (?, ?, ?)");
        $stmt->execute([$inputs['], $inputs['email'], $hashed]);
        $userId = $db->lastInsertId();

        if (!empty($_POST['groups'])) {
            $groupStmt = $db->prepare("INSERT INTO user_groups (user_id, group_id) VALUES (?, ?)");
            foreach ($_POST['groups'] as $groupId) {
                $groupStmt->execute([$$groupId]);
            }
        }
        $db->commit();
        echo json_encode(['success' => true, 'message' => ']);
    }
    
    if ($action === 'list_users') {
        $stmt = $db->query("SELECT u.id, u.username, u.email, u.status, GROUP_CONCAT(g.name) as roles 
                            FROM users u 
                            LEFT JOIN user_groups ug ON u.id = ug.user_id 
                            LEFT JOIN groups g ON ug.group_id = g.id 
                            GROUP BY u.id");
        echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
    }
} catch (Exception $e) {
    if ($db->inTransaction()) $db->rollBack();
    Logger::logError($e->getMessage(), __FILE__, __LINE__);
}
""",

    # -------------------------------------------------------------------------
    # CORE REUSABLE CLASSES (core/auth.php updates)
    # -------------------------------------------------------------------------
    "core/auth_extended.php": """<?php
/**
 * Advanced Session & Role-Based Access Control Extensions
 */
class AuthExtended extends Auth {
    public static function logout(): void {
        session_unset();
        session_destroy();
        if (isset($_COOKIE['remember_me'])) {
            setcookie('remember_me', '', time() - 3600, '/');
        }
        header("Location: /login.php");
        exit;
    }

    public static function changePassword(int $userId, string $newPassword): bool {
        $hashed = password_hash($newPassword, PASSWORD_ARGON2ID);
        $db = Database::getConnection();
        $stmt = $db->prepare("UPDATE users SET password_hash = ? WHERE id = ?");
        return $stmt->execute([$hashed, $]);
    }
}
"""
}

def execute_phase_2_deployment():
    print("Initializing Phase 2: Core Processing Controllers...")
    for path_str, content in PHASE_2_DATA.items():
        normalized_path = os.path.normpath(path_str)
        directory = os.path.dirname(normalized_path)
        if directory and not os.path.exists(directory):
            os.makedirs(directory, exist_ok=True)
        with open(normalized_path, "w", encoding="utf-8") as f:
            f.write(content.lstrip())
        print(f"Deployed controller: /{normalized_path}")
    print("\nPhase 2 deployment complete. Backend authentication and admin logic is now active.")

if __name__ == "__main__":
    execute_phase_2_deployment()

